<?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']);
}elseif($function == "saveTaxInfo"){
	saveTaxInfo();
}


	//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;
}

function saveTaxInfo(){
	$taxID1 = $_POST["TaxID1"];
	$taxExpiration1 = $_POST["Tax1Expiration"];
	$taxExempt1 = $_POST["Tax1Exempt"];
	$taxID2 = $_POST["TaxID2"];
	$taxExpiration2 = $_POST["Tax2Expiration"];
	$taxExempt2 = $_POST["Tax2Exempt"];
	$accountNumber = $_POST["AccountNumber"];
	if($accountNumber != "" && !is_null($accountNumber)){
		$customer = new Customer($accountNumber);
		$customer->Contact = $_POST["Contact"];
		$customer->ContactPhone = $_POST["ContactPhone"];
		$customer->Email = $_POST["Email"];
		$customer->TaxID1 = $taxID1;
		$customer->TaxID2 = $taxID2;
		$customer->TaxIDExpiration1 = date("Y-m-d", strtotime($taxExpiration1));
		$customer->TaxIDExpiration2 = date("Y-m-d", strtotime($taxExpiration2));
		$customer->TaxExempt1 = $taxExempt1;
		$customer->TaxExempt2 = $taxExempt2;
		$customer->save();
		header("Content-Type: application/json");
		echo true;

		;
	}else{
		echo "Error account number not received";
	}
	
}

?>