<?php
/**
* @version      $Id: admin_shoptheme_editor.php 
* @package      Easyshop
* @copyright    Copyright (C) 2005 - 2011 TA-EDV
* @license      proprietary
* @author       Richard Kammermayer <rkd@ta-edv.de>
* Easyshop is a web shop system
*/

include_once './core/statistic.class.php';

class admin_statistic_editor {
	private $base_object;
	private $layout_object;
	private $statistic_object;
	
	function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->layout_object = $layout_object;
		$this->statistic_object = new Statistic($base_object);
	} // end __construct

	function run() {
		if (isset($_GET['action'])) {
			$action = $_GET['action'];
		} elseif (isset($_POST['action'])) {
			$action = $_POST['action'];
		} else {
			$action = false;
		}
		
		if (isset($_GET['id'])) {
			$id = $_GET['id'];
		} elseif (isset($_POST['id'])) {
			$id = $_POST['id'];
		} else {
			$id = false;
		}
		
		if ($action == "get_tab") {
			$this->get_tab($id);
		} elseif ($action == "view_stat") {
			$this->view_stat($id);
		} elseif ($action == "get_csv") {
			$this->get_csv($id);
		} else {
			return $this->setup_list($id);
		}
	} // end run
	
	private function setup_list($id) {
		if ($id) {
			$data = $this->statistic_object->get_by_id($id);
			
			if ($data) {			
				$this->layout_object->assign('form_data', $data);
			} else {
				$this->layout_object->assign('error_message', "Diese Statistik existiert nicht.");
			}
		}
		// implied else, no action taken when you create something new
		
		$tabs = array (
			'year' => 'Jahr',
			'month' => 'Monat',
			/*'week' => 'Woche',*/
			'day' => 'Tag'	
		);
		$stat_tabs = array();
		foreach ($tabs as $tab_key => $tab_value) {
				$temp['name'] = $tab_value;
				$temp['id'] = $tab_key;
				$temp['selector'] = $tab_key;
	
				$stat_tabs[] = $temp;
		}
		$this->layout_object->assign('tabs', $stat_tabs);
		
		return $this->layout_object->fetch('admin_statistic_editor.tpl');
	} // end default_action
	

	private function get_tab($id) {
		$data = array();
		if ($id) {
			$data = $this->statistic_object->get_by_id($id);
		
			// get today date
			$today = getdate();
			$this->layout_object->assign('today', $today);
			
			// set years
			$years = array();
			for ($y=0;$y<5;$y++) {
				$years[] = $today['year'] - $y;
			}
			$this->layout_object->assign('years', $years);
			
			
			
			$this->layout_object->assign('tab_id', $_GET['tab_id']);
			
			if ($data) {
				$this->layout_object->assign('form_data', $data);
			} else {
				$this->layout_object->assign('error_message', "Diese Statistik existiert nicht.");
			}
		}
		
		$this->layout_object->assign('statistic_data', $data);
		echo $this->layout_object->fetch('admin_statistic_filter.tpl');
		exit();
	}
	
	private function view_stat($id) {
		$data = array();
		if ($id) {
			$tab_id = $_GET['tab_id'];
			$filter = array('period' => $tab_id);
			if ($tab_id == 'year') {
				$year = $_POST['year'];
				$filter['date_start'] = $year.'-01-01';
				$filter['date_end'] = $year.'-12-31';
			}
			else if ($tab_id == 'month') {
				$year = $_POST['year'];
				$month = $_POST['month'];
				$filter['date_start'] = $year.'-'.$month.'-01';
				$monat = mktime(0, 0, 0, $month, 1, $year);
				$max_days_of_month = date("t", $monat);
				$filter['date_end'] = $year.'-'.$month.'-'.$max_days_of_month;
			}
			else if ($tab_id == 'week') {
				$filter['date_start'] = '2012-01-01';
				$filter['date_end'] = '2012-12-31';
			}
			else if ($tab_id == 'day') {
				$year = substr($_POST['date'],6,4);
				$month = substr($_POST['date'],3,2);
				$day = substr($_POST['date'],0,2);
				$filter['date_start'] = $year.'-'.$month.'-'.$day;
				$filter['date_end'] = $year.'-'.$month.'-'.$day;
			}
			else {
				echo "No date selected!";
				exit();
			}
			
			
			$data = $this->statistic_object->get_by_id($id);
		
			$this->layout_object->assign('filter', $filter);
			
			if ($data) {
				$this->layout_object->assign('form_data', $data);
			} else {
				$this->layout_object->assign('error_message', "Diese Statistik existiert nicht.");
			}
		}
		
		// get today date
		$today = getdate();
		$this->layout_object->assign('today', $today);
		
		// load modules
		$module_file = 'core/statistics/'.$data->modul.'.inc.php';
		$stat_modul = $data->modul;
		if(file_exists($module_file)) {
			include_once $module_file;
			$modul_object = new $stat_modul($this->base_object);
			$data->statistic_data = $modul_object->run($filter);
		} else {
			echo "Statistic modul not found!";
			exit();
		}
		
		// Generate modern Plotly charts
		$plotly_chart_bar = $this->generate_plotly_chart($data->statistic_data, $filter, 'bar');
		$plotly_chart_line = $this->generate_plotly_chart($data->statistic_data, $filter, 'line');

		$this->layout_object->assign('plotly_chart_bar', $plotly_chart_bar);
		$this->layout_object->assign('plotly_chart_line', $plotly_chart_line);
		$this->layout_object->assign('statistic_data', $data);
		echo $this->layout_object->fetch('admin_statistic_view.tpl');
		exit();
	}

	private function generate_plotly_chart($statistic_data, $filter, $chart_type = 'bar') {
		// Prepare data for Python chart service
		$chart_config = array(
			'type' => $chart_type,
			'title' => ($chart_type == 'bar' ? 'Säulendiagramm' : 'Liniendiagramm'),
			'period' => $filter['period']
		);

		$input_data = array(
			'data' => $statistic_data,
			'config' => $chart_config
		);

		$json_input = json_encode($input_data);

		// Call Python chart service
		$python_script = ROOT_DIR . 'modules/import/chart_service.py';
		$command = "echo " . escapeshellarg($json_input) . " | python3 " . escapeshellarg($python_script) . " 2>&1";

		$output = shell_exec($command);

		if (empty($output)) {
			return '<div style="padding: 20px; background: #fee; border: 1px solid #fcc;">Chart-Generierung fehlgeschlagen</div>';
		}

		return $output;
	}
	
	private function get_csv($id) {
		if ($id) {
			$tab_id = $_GET['tab_id'];
			$filter = array('period' => $tab_id);
			$filter['date_start'] = $_GET['date_start'];
			$filter['date_end'] = $_GET['date_end'];
			
			$data = $this->statistic_object->get_by_id($id);

		}

		// load modules
		$module_file = 'core/statistics/'.$data->modul.'.inc.php';
		$stat_modul = $data->modul;
		if(file_exists($module_file)) {
			include_once $module_file;
			$modul_object = new $stat_modul($this->base_object);
			$data->statistic_data = $modul_object->run($filter);
		} else {
			echo "Statistic modul not found!";
			exit();
		}

		$csv = '';
	    foreach ($data->statistic_data as $row) {
	        $csv .= implode(";",$row)."\r\n";
	    }
	    
	    $csv = utf8_decode($csv);
	    
	    echo $csv;
	    $application="text/csv";
	    header( "Content-Type: $application" );
	    header( "Content-Disposition: attachment; filename=statistik.csv");
	    header( "Content-Description: csv File" );
	    header( "Pragma: no-cache" );
	    header( "Expires: 0" );
		exit();
	}
	
	// only used in ajax, so i terminate with exit
	private function save() {
		if (isset($_POST['form_field'])) {
			$data = $_POST['form_field'];
			
			if ($data['id'] == '') {
				unset($data['id']);
			}
			
			$result = $this->statistic_object->save($data);
			
			if ($result) {
				$return = array('status' => 'success', 'id' => $result);
			} else {
				$return = array('status' => 'error', 'message' => 'save failed');
			}
		} else {
			$return = array('status' => 'error', 'message' => 'no forms data');
		}
		
		echo json_encode($return);
		
		exit();
	} // end save
	
} // end
