<?php
//global $con;

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

$function = $_REQUEST['f'];
if($function == "saveLostSale"){
	
	saveLostSale($_REQUEST);
}elseif($function == "getLostSalesDetails"){
	getLostSalesDetails($_REQUEST['sku']);
}


	//this function will add a new lost sale
function saveLostSale($data){
	global $isCustomer;
	//global $customer;
	//global $salesman;
	global $con;
	$item = new stdClass();
	$item->AccountNumber = $_SESSION['isCustomer']?$_SESSION['AccountNumber']:$_SESSION['SalesmanID'];
	$item->SKU = $data['sku'];
	$item->Description = $data['description'];
	$item->Qty = $data['qty'];
	$item->Price = isset($data['price'])?$data['price']:0;
	$item->CompetitionPrice = isset($data['competitionPrice'])?$data['competitionPrice']:0;
	$item->CompetitionSource = isset($data['competitionSource'])?$data['competitionSource']:"";
	$item->Reason = isset($data['reason'])?$data['reason']:"Product not found";
	$item->Comments = isset($data['comments'])?$data['comments']:"";
	//SECURITY - Sanitize input by user 
	foreach(get_object_vars($item) as $key => $value){
		$item->$key = mysqli_real_escape_string($con, $value);
	}
	//var_dump($item);
	$query = "INSERT INTO LOST_SALE (`AccountNumber`, `SKU`, `Description`, `Qty`, `Price`, `CompetitionPrice`, `CompetitionSource`, `Reason`, `LostSaleDate`, `Comments`) VALUES ('" . $item->AccountNumber . "', '" . $item->SKU . "', '" . $item->Description . "', '" . $item->Qty . "',  '" . $item->Price . "', '" . $item->CompetitionPrice . "', '" . $item->CompetitionSource . "', '" . $item->Reason . "', DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $item->Comments . "')";
	//var_dump($query);
	if(mysqli_query($con, $query)){
		
		echo "true";	
	}else{
		echo "false: " . mysqli_error($con);
	}
	
	 
}
function getLostSalesDetails($sku){
	global $con;
	
	$sku = str_ireplace('-','',$sku);
	$query = "SELECT * FROM LOST_SALE WHERE REPLACE(SKU, '-', '') LIKE '" . $sku . "'";
	//echo $query;
	
	$result = mysqli_query($con, $query);
	$return = array();
	
	while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
		//var_dump($row);
		if(strlen($row['AccountNumber']) > 3){
			$customer = new Customer($row['AccountNumber']);
			$row['isCustomer'] = true;
			$row['Customer'] = $customer;
		}else{
			$salesman = new Salesman($row['AccountNumber']);
			//var_dump($salesman);
			$row['isCustomer'] = false;
			$row['Salesman'] = $salesman;
		}
		
		array_push($return, $row);
	}
	//$return['sql'] = $query;
	echo json_encode($return);
}
?>