<?php
global $con;
if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){
	include_once("../connect.php");
	
}else{
	include_once("connect.php");
	
}

$function = $_REQUEST['f'];
if($function == "getMyCustomers"){
	
	getMyCustomers($_REQUEST['sid']);
}


	//this function usually is called via a GET request to display Customers that don't have orders from the last 30 days
function getMyCustomers($sid){
	
	global $con;
	//$query = "SELECT AccountNumber, MAX(OrderDate) as LastOrder, TIMESTAMPDIFF(DAY, MIN(INVOICE.InvoiceDate), NOW()) AS DueDays FROM CUSTOMER JOIN ORDER_HEAD USING(`AccountNumber`) JOIN INVOICE LEFT JOIN PAYMENT_DETAIL ON INVOICE.InvoiceNumber = PAYMENT_DETAIL.InvoiceNumber WHERE CUSTOMER.Salesman LIKE '" . $sid . "' GROUP BY AccountNumber ORDER BY LastLogin ASC";
	$query = "SELECT AccountNumber, MAX(OrderDate) as LastOrder,LastLogin, TIMESTAMPDIFF(DAY, IF(LastLogin,LastLogin,0), NOW()) AS LastLoginDays, TIMESTAMPDIFF(DAY, MAX(OrderDate), NOW()) AS LastOrderDays FROM CUSTOMER JOIN ORDER_HEAD USING(`AccountNumber`) WHERE CUSTOMER.Salesman LIKE '" . $sid . "' GROUP BY AccountNumber ORDER BY LastLogin ASC";
	$result = mysqli_query($con, $query);
	$return = array();
	//store data in array to later convert to JSON
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		$customer = new Customer($row['AccountNumber']);
		unset($customer->Salesman);
		$customer->DueDays = $customer->getDueDays();
		$customer->LastOrderDate = date("m/d/Y h:m a", strtotime($row['LastOrder']));
		$customer->LastLogin = date("m/d/Y h:m a", strtotime($customer->LastLogin));
		$customer->LastLoginDays = $row['LastLoginDays'];
		$customer->LastOrderDays = $row['LastOrderDays'];
		//$customer->getInvoices();
		array_push($return,$customer);	
	}
	
	
	echo json_encode($return);
	return $return;
}

?>