<?php


$reports["_ZENCART_SALES"] = Array(
	"ClassName" => "ZenCartSales",
	"Category" => "_ZENCART",
	"icon" => "images/icons/32x32/zencart.png",
	"Options" => "daterangeField,columnSelector,displaymode",
	"Filename" => "zencart_sales",
	"Distribution" => "Premium",
	"Order" => 8,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
); 

Class ZenCartSales extends Report {
	
	function Settings() {
		$this->DefaultDisplay = "table";
		$this->DisplayModes = "table,linechart";
		
		$this->columnDefinitions[] = array("Label" => _DATE);
		$this->columnDefinitions[] = array("Label" => _TOTAL_REVENUE);
		$this->columnDefinitions[] = array("Label" => _TAXES);
		$this->columnDefinitions[] = array("Label" => _SHIPPING);		
		$this->columnDefinitions[] = array("Label" => _SALES);			
		$this->columnDefinitions[] = array("Label" => _ORDERS);	
		
		if(empty($this->period)){ $this->period ='_DAYS'; }
		if(empty($this->order_status)){ $this->order_status = 0; }
		if(empty($this->order_status_name)) { $this->order_status_name = _ALL_STATUSSES; }
		
		$this->tableprefix =$this->profile->GetOtherSettings("externalConnection.prefix.zenCartConnect", "");
	}
	
	function DisplayCustomForm() {
		global $session;
		$connection = $this->checkExternalConnection("zenCartConnect");
		if($connection != false) {
			$query = "SELECT DISTINCT(orders_status_id) AS status_id, `orders_status_name` AS status_name FROM `{$this->tableprefix}orders_status` ORDER BY `orders_status_name` ASC";
			
			$result = mysql_query($query, $connection);
			echo "<div class='form-group'>";
				echo "<label for='order_status'>"._ORDER_STATUS."</label>";
				echo "<input type='hidden' id='order_status_name' name='order_status_name' value='{$this->order_status_name}'>";
				
				echo "<select id='order_status' name='order_status' class='form-control'>";
					echo "<option value='0'>"._ALL_STATUSSES."</option>";
				while($row = mysql_fetch_assoc($result)) {
					if($row['status_id'] == $this->order_status) {
						$selected = ' selected ';
					} else {
						$selected = '';
					}
					echo "<option {$selected} value='{$row['status_id']}'>{$row['status_name']}</option>";
				}
				echo "</select>";
				if($session->canEditProfiles()) {
					echo "<a data-title='"._VIEW_ZENCART_CONF."'' href='definereport.php?conf={$this->profile->profilename}&labels=_ZENCART_SALES' class='optionlink open_iframe_window'>". _VIEW_ZENCART_CONF ."</a>";
				}
			echo "</div>";
			echo "<script type='text/javascript'>";
				echo "$('#order_status').change(function() {
					$('#order_status_name').attr('value', $(this).find('option[value=\"' + $(this).val() + '\"]').html());
				});";
			echo "</script>";
			$sel1 = "";
			$sel2 = "";
			$sel3 = "";
			if ($this->period=='_DAYS') {
				$sel1="checked";
			} else if ($this->period=='_WEEKS') { 
				$sel2="checked";
			} else if ($this->period=='_MONTHS') { 
				$sel3="checked";
			}
			echo "<div class='form-group'><label>".strtoupper(substr(_REPORT,0,1)).substr(_REPORT,1).' '._PERIOD."</label>";
			
			echo "<div><input class='noTextInput report_option_field' style='width: 25px; margin: 0;' type=\"radio\" id='period' name=\"period\" value=\"_DAYS\" {$sel1}> "._DAYS."</div>";
			echo "<div><input class='noTextInput report_option_field' style='width: 25px; margin: 0;' type=\"radio\" id='period' name=\"period\" value=\"_WEEKS\" {$sel2}> "._WEEKS."</div>";
			echo "<div><input class='noTextInput report_option_field' style='width: 25px; margin: 0;' type=\"radio\" id='period' name=\"period\" value=\"_MONTHS\" {$sel3}> "._MONTHS."</div>";
			echo "</div><br/>";
		} else if($session->canEditProfiles()) {
			echo "<a data-title='"._VIEW_ZENCART_CONF."'' href='definereport.php?conf={$this->profile->profilename}&labels=_ZENCART_SALES' class='optionlink open_iframe_window'>". _VIEW_ZENCART_CONF ."</a>";
		}
	}
	
	function DefineQuery() {
		global $db;
		if ($this->order_status != '0') {
			$sql = " AND o.orders_status = ". $db->Quote($this->order_status);
		} else {
			$sql = "";
		}
		
		if (!empty($this->from)) {
			$sql .= " AND DATE(o.date_purchased) >= '" . date('Y-m-d', $this->from) . "'";
		}

		if (!empty($this->to)) {
			$sql .= " AND DATE(o.date_purchased) <= '" . date('Y-m-d', $this->to) . "'";
		}
		
		if ($this->period=='_DAYS') {
			$qd=",'%Y-%m-%d'"; 
		} else if ($this->period=='_WEEKS') { 
			$this->allowDateFormat = false;
			$qd=",'%u'";
		} else if ($this->period=='_MONTHS') { 
			$this->allowDateFormat = false;
			$qd=",'%M'"; 
		}
		
		$query = "SELECT DATE_FORMAT(o.date_purchased{$qd}) AS `datum`, 
			FORMAT((SUM((SELECT value FROM {$this->tableprefix}orders_total WHERE o.orders_id = orders_id AND class = 'ot_total'))),2) as total_revenue,
			FORMAT((SUM((SELECT value FROM {$this->tableprefix}orders_total WHERE o.orders_id = orders_id AND class = 'ot_tax'))),2) as total_tax,
			FORMAT((SUM((SELECT value FROM {$this->tableprefix}orders_total WHERE o.orders_id = orders_id AND class = 'ot_shipping'))),2) as total_shipping,
			FORMAT((SUM((SELECT value FROM {$this->tableprefix}orders_total WHERE o.orders_id = orders_id AND class = 'ot_subtotal'))),2) as sales,
			COUNT(o.orders_id) as orders,
			o.currency as curr
			FROM
				{$this->tableprefix}orders AS o, {$this->tableprefix}orders_status AS os
			WHERE
				o.orders_status = os.orders_status_id {$sql}
			GROUP BY DATE(o.date_purchased)
			ORDER BY `datum` ASC";
		
		// echo $query;
		return $query;
	}
	
	function GetReportData() {
		$data = [];
		$import = [];
		$connection = $this->checkExternalConnection("zenCartConnect");
		if($connection == false){ echoNotice($this->SettingsButton()._CONNECTION_TO_DATABASE_FAILED); exit();  }
		$query = $this->DefineQuery();
		$f = $this->from;
		$t = $this->to;
		if($this->period == '_DAYS'){		
			while($f < $t){
				$d = date('Y-m-d', $f);
				$import[$d]["total_revenue"] = 0.00;
				$import[$d]["total_tax"] = 0.00;
				$import[$d]["total_shipping"] = 0.00;
				$import[$d]["sales"] = 0.00;
				$import[$d]["orders"] = 0;
				$f = $f + 86400;
			}		
		}

		$currency = ""; 		
		$result = mysql_query($query,$connection);
		while($row = mysql_fetch_array($result)) {
			$currency = $row["curr"];
			$d = $row["datum"];
			$import[$d]["total_revenue"] = $row["total_revenue"];
			$import[$d]["tax"] = $row["total_tax"];
			$import[$d]["ship"] = $row["total_shipping"];
			$import[$d]["turnover"] = $row["sales"];
			$import[$d]["orders"] = $row["orders"];
		}
		$i = 0;
		foreach($import as $k => $v){				
			if($this->period == '_WEEKS'){
				$data[$i][0] = _WEEK." {$k}";
			}else{
				$data[$i][0] = $k;
			}
			$data[$i][1] = (empty($v["total_revenue"]) ? 0.00 : $v["total_revenue"]);
			$data[$i][2] = (empty($v["tax"]) ? 0.00 : $v["tax"]);
			$data[$i][3] = (empty($v["ship"]) ? 0.00 : $v["ship"]);
			$data[$i][4] = (empty($v["turnover"]) ? 0.00 : $v["turnover"]);
			$data[$i][5] = (empty($v["orders"]) ? 0 : $v["orders"]);
			$i ++;
		}
		mysql_close($connection);
		
		if(empty($this->order_status_name)) { $this->order_status_name = _ALL_STATUSSES; }
		
		$this->addlabel .= _ORDER_STATUS.": {$this->order_status_name}";
		$this->addlabel .= " | ". _CURRENCY .": {$currency}";
		
		return $data;
	}
	
	function DefineReport() {
		$this->externDbConnectForm("zenCartConnect");	
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		return false;
	}
}
?>