<?php

/**
* @desc This report lets you make split test of your pages and gives you an overview of wich one works the best.
*/

$reports["_ZENCART_SALES_PER_COUNTRY"] = Array(
	"ClassName" => "ZenCartSalesPerCountry",
	"Category" => "_ZENCART",
	"icon" => "images/icons/32x32/zencart.png",
	"Options" => "daterangeField,displaymode,limit",
	"Filename" => "zencart_sales_per_country",
	"Distribution" => "Premium",
	"Order" => 12,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
);

class ZenCartSalesPerCountry extends Report {
	function Settings() {
		$this->DefaultDisplay = "table";
		$this->DisplayModes = "table,pie";
		$this->columnDefinitions[] = array("Label" => _COUNTRY);
		$this->columnDefinitions[] = array("Label" => _TOTAL_REVENUE);
		$this->columnDefinitions[] = array("Label" => _ORDERS);
		$this->columnDefinitions[] = array("Label" => _REVENUE_PER_SALE);
		$this->columnDefinitions[] = array("Label" => _PRODUCTS_PER_ORDER);
		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 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) . "'";
		}
		
		$query = "SELECT o.`customers_country` AS `country`, 
			FORMAT(SUM((SELECT value FROM {$this->tableprefix}orders_total WHERE o.orders_id = orders_id AND class = 'ot_total')),2) as total_revenue,
			COUNT(DISTINCT(o.orders_id)) as orders,
			FORMAT((SUM((SELECT value FROM {$this->tableprefix}orders_total WHERE o.orders_id = orders_id AND class = 'ot_subtotal')) / COUNT(op.orders_id)),2) AS rev_per_sale, 
			(SUM(op.products_quantity) / COUNT(DISTINCT(op.orders_id))) AS pr_per_order,
			o.currency as curr
			
			FROM
				{$this->tableprefix}orders AS o, {$this->tableprefix}orders_products AS op, {$this->tableprefix}products_description AS pd, {$this->tableprefix}orders_status AS os
			WHERE
				pd.products_id = op.products_id AND op.orders_id = o.orders_id AND o.orders_status = os.orders_status_id {$sql}
			GROUP BY o.`customers_country`
			ORDER BY total_revenue DESC
			LIMIT {$this->limit}";
		
		return $query;
	}
	
	function GetReportData() {
		global $cnames;
		
		$countrynames = array_flip($cnames);
		
		$connection = $this->checkExternalConnection("zenCartConnect");
		if($connection == false){ echoNotice($this->SettingsButton()._CONNECTION_TO_DATABASE_FAILED); exit();  }
		
		$query = $this->DefineQuery();
		
		$result = mysql_query($query, $connection);
		$currency = "";
		$data = [];
		while($row = mysql_fetch_array($result)) {
			$currency = $row["curr"];
			$row[0] = $countrynames[$row[0]];
			$data[] = $row;
		}
		
		$this->addlabel .= _ORDER_STATUS.": {$this->order_status_name}";
		$this->addlabel .= " | ". _CURRENCY .": {$currency}";
		
		return $data;
	}
	
	function DisplayCustomForm() {
		global $session;
		$connection = $this->checkExternalConnection("zenCartConnect");

		echo "<div class='form-group'>";

		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);
			
			if(empty($this->order_status)) { $this->order_status = '0'; }
			if(empty($this->order_status_name)) { $this->order_status_name = _ALL_STATUSSES; }
			
			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>";
			
			echo "<script type='text/javascript'>";
				echo "$('#order_status').change(function() {
					$('#order_status_name').attr('value', $(this).find('option[value=\"' + $(this).val() + '\"]').html());
				});";
			echo "</script>";
		}
		
		if($session->canEditProfiles()) {
			echo "<a data-title='"._VIEW_ZENCART_CONF."'' href='definereport.php?conf={$this->profile->profilename}&testcenter=create&labels=_ZENCART_SALES_PER_COUNTRY&action=welcome' class='optionlink open_iframe_window'>". _VIEW_ZENCART_CONF ."</a>";
		}

		echo "</div>";
	}
	
	function DefineReport() {
		$this->externDbConnectForm("zenCartConnect");
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		return false;
	}
}