<?php
//echo "lol";
//die();
if(stripos($_SERVER['SCRIPT_NAME'],"/admin/")===false?false:true){
	include_once("../connect.php");
	include_once("../session.php");
}else{
	include_once("connect.php");
	include_once("session.php");
}
//die("ee");
$function = isset($_REQUEST['f'])?$_REQUEST['f']:null;
if($function == "saveAssignment"){


	saveAssignment($_POST);
}elseif($function == "getAssignmentsByDriver"){

   getAssignmentsByDriver($_REQUEST['sm']);
}elseif($function == "deleteAssignment"){

   deleteAssignment($_REQUEST['id']);
}
function deleteAssignment($id){
	$assignment = new Assignment($id);
	$assignment->Deleted  = 1;
	if($assignment->save()){
		echo "true";
	}else{
		echo "false";
	}

}
function saveAssignment($Data){
	global $con;

	if($Data['AssignmentID'] === "" || $Data['AssignmentID'] === "0"){
		$Data['AssignmentID'] = NULL;
		$assignment = new Assignment($Data['AssignmentID']);
		$assignment->create();
		$assignment->AssignmentDate = "NOW()";
	}else{
		$assignment = new Assignment($Data['AssignmentID']);
	}

	$assignment->ShipToName = $Data['ShipToName'];
	$assignment->ShipToAddress1 = $Data['ShipToAddress1'];
	$assignment->ShipToAddress2 = $Data['ShipToAddress2'];
	$assignment->ShipToCity = $Data['ShipToCity'];
	$assignment->ShipToState = $Data['ShipToState'];
	$assignment->ShipToZip = $Data['ShipToZip'];
	$assignment->AccountNumber = $Data['AccountNumber'];
	$assignment->AssignmentTitle = $Data['AssignmentTitle'];
	$assignment->AssignmentText = $Data['AssignmentText'];
	$assignment->ContactName = $Data['ContactName'];
	$assignment->ContactPhone = $Data['ContactPhone'];
	//var_dump($assignment->AssignmentDate);
	$assignment->save();
	$result = new stdClass();
	$result->Result = true;
	$result->Data = $assignment;
	echo json_encode($result);

}
function getAssignmentsByDriver($SalesmanID){
	global $con;
	if($SalesmanID == "%"){
		$orNull = " OR DeliveryUser IS NULL";
	}
	$query = "SELECT AssignmentID FROM `ASSIGNMENT_HEAD` WHERE (DeliveryUser LIKE '$SalesmanID' $orNull) AND Completed = false AND Deleted = 0";
	$result = mysqli_query($con, $query);
	$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);

	foreach ($rows as $key => $value) {
		$rows[$key] = new Assignment($rows[$key]['AssignmentID']);
		$rows[$key]->Driver = new Salesman($rows[$key]->DeliveryUser);
	}

	echo safe_json_encode($rows);
}


?>
