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

}else{
	include_once("connect.php");

}

$function = $_REQUEST['f'];
if($function == "processPayment"){
    $paymentID = $_REQUEST['pid'];
        processPayment($paymentID);
}elseif($function == "flagLoadedReceipt"){
    $paymentID = $_REQUEST['pid'];
    flagLoadedReceipt($paymentID);
}elseif($function == "receiveCPD"){
    $paymentID = $_REQUEST['pid'];
    receiveCPD($paymentID);
}elseif($function == "voidPayment"){
    $paymentID = $_REQUEST['pid'];
    $reason = $_REQUEST['Reason'];
	//var_dump($_REQUEST);
    voidPayment($paymentID,$reason);
}elseif($function == "voidPaymentDetails"){
    $paymentID = $_REQUEST['pid'];
    voidPaymentDetails($paymentID);
}elseif($function == "getPaymentByCredit"){
    $creditNumber = mysqli_real_escape_string($con, $_REQUEST['number']);
    getPaymentByCredit($creditNumber);
}elseif($function == "createDeposit"){

	createDeposit($_REQUEST['data']);
}elseif($function == "createReconciliation"){

	createReconciliation($_REQUEST['sm'], $_REQUEST['notes']);
}elseif ($function == "refreshAging") {
	refreshAging();
}elseif ($function == "transferARToLoss"){
	$customer = new Customer($_POST['an']);
	$result = $customer->transferARToLoss();
	if($result){
		echo "true";
	}else{
		echo $result;
	}
}elseif ($function == "sendCollectionsEmail") {
	$customer = new Customer($_POST['an']);
	if($customer->sendCollectionsEmail()){
		echo "true";
	}else{
		echo "Error! Check customer email!";
	}
	// code...
}


function voidPaymentDetails($paymentID){
	include_once("functions.php");
    $payment = new Payment($paymentID);
       echo $payment->GetVoidDetails();
}
function processPayment($paymentID){
		include_once("../session.php");
       $payment = new Payment($paymentID);
	//   var_dump($payment);
       echo $payment->ProcessPayment();
}
function receiveCPD($paymentID){
	include_once("../session.php");
    $payment = new Payment($paymentID);
	//var_dump($payment);
    echo $payment->ReceiveCPD();
}
function flagLoadedReceipt($paymentID){
    $payment = new Payment($paymentID);
    $payment->FlagLoadedReceipt();
}
function voidPayment($paymentID, $reason){
    if($reason == ""){
        die('Invalid Reason!');
    }
	//ini_set("display_errors", 1);
	//error_reporting(E_ALL);
	include_once("functions.php");
	//include_once("../classes/ClassLoader.php");
	include_once("../modules/payment/payment.classes.php");
    $payment = new Payment($paymentID);
	//var_dump($payment);
    $payment->VoidPayment($reason);
}
function getPaymentByCredit($creditNumber){
    global $con;
    $query = "SELECT * FROM PAYMENT_CREDIT WHERE CreditNumber LIKE '$creditNumber' OR Reference LIKE '%$creditNumber%'";
    $result = mysqli_query($con, $query);

    if(mysqli_num_rows($result) > 0){
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        echo $row['PaymentID'];
    }else{
        echo "false";
    }
}
function receivePayments($salesman, $data){
	global $con;

}
function createDeposit($depositData){
	include_once("../session.php");
	global $con;
	$return = new stdClass();
	$return->Result = true;
	$return->DepositID = 0;
	$return->Error = "";
	$depositData = (object) $depositData;
	$depositDate = $depositData->Date;
	$depositNotes = $depositData->Notes;
	mysqli_query($con,"SET time_zone = '-4:00';");
	$query = "INSERT INTO PAYMENT_DEPOSIT_HEAD (DepositDate, CreationDate, Username, TotalChecks, TotalCash, TotalTransfer, TotalDeposit, Notes, Depositor) VALUES (
	'$depositDate',
	NOW(),
	'" . $_SESSION['Username'] . "',
	" . $depositData->Checks . ",
	" . $depositData->Cash . ",
	" . $depositData->Transfers . ",
	" . $depositData->TotalDeposit . ",
	'" . mysqli_real_escape_string($con, $depositNotes) . "',
	'" . mysqli_real_escape_string($con, $depositData->Depositor) . "');";
	$return->Result = $return->Result && mysqli_query($con, $query);
	if(mysqli_error($con)){
			$return->Error = mysqli_error($con);
	}
	$depositID = mysqli_insert_id($con);
	$return->DepositID = $depositID;
	foreach($depositData->PaymentList as $key=>$paymentID){
		$query = "INSERT INTO PAYMENT_DEPOSIT_DETAIL (DepositID, PaymentID) VALUES ('$depositID','$paymentID');";
		$return->Result = $return->Result && mysqli_query($con, $query);
		if(mysqli_error($con)){
			$return->Error = mysqli_error($con);
		}
	}
	$query = "UPDATE PAYMENT_HEAD SET Deposited = 1 WHERE ID IN (SELECT PaymentID FROM PAYMENT_DEPOSIT_DETAIL WHERE DepositID = $depositID);";
	$return->Result = $return->Result && mysqli_query($con, $query);
	if(mysqli_error($con)){
			$return->Error = mysqli_error($con);
		}
		echo json_encode($return);

	return $return;


}

function createReconciliation($salesman, $notes){
	include_once("../session.php");
	mysqli_query($con, "SET time_zone = \"-04:00\";");
	global $con;

	$query = "SELECT PAYMENT_HEAD.ID FROM PAYMENT_HEAD WHERE Processed = 1 AND CollectingUser LIKE '$salesman' AND PaymentDate > '2019-01-01' AND PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_SALESMAN_RECONCILE_DETAIL) AND PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_REMINDER)";
	$result = mysqli_query($con, $query);
	$return = new stdClass();
	$return->Result = true;

	//var_dump($query);
	if(mysqli_num_rows($result)){
		$query = "INSERT INTO PAYMENT_SALESMAN_RECONCILE_HEAD (SalesmanID, ReconcileDate, ReconcileUser, Notes) VALUES ('$salesman',NOW(),'" . $_SESSION['Username'] . "', '" . mysqli_real_escape_string($con, $notes) . "');";

		if($result = mysqli_query($con, $query)){
			$id = mysqli_insert_id($con);
			$query = "INSERT INTO PAYMENT_SALESMAN_RECONCILE_DETAIL (ReconcileID, PaymentID) (SELECT $id, PAYMENT_HEAD.ID FROM PAYMENT_HEAD WHERE Processed = 1 AND PaymentDate > '2019-01-01' AND CollectingUser LIKE '$salesman' AND PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_SALESMAN_RECONCILE_DETAIL) AND PAYMENT_HEAD.ID NOT IN (SELECT PaymentID ID FROM PAYMENT_REMINDER))";

			if($result = mysqli_query($con, $query)){
				$return->Result = true;
				$return->Error = "";
				$return->Value = $id;
				echo json_encode($return);
				return;
			}else{
				$return->Result = false;
				$return->Error = "Error saving reconciliation details. MYSQL Query: " . $query;
				echo json_encode($return);
				return;
			}
		}else{
			$return->Result = false;
			$return->Error = "Error generating reconciliation record. MYSQL Query: " . $query;
			echo json_encode($return);
			return;
		}


	}else{
		$return->Result = false;
		$return->Error = "No invoices found to reconcile.";
		echo json_encode($return);
		return;
	}


}
function refreshAging(){
	global $con;

	$query = "DROP TABLE IF EXISTS ACCOUNTS_RECEIVABLE_AGING_DELIVERY_CACHE;
						CREATE TABLE ACCOUNTS_RECEIVABLE_AGING_DELIVERY_CACHE (SELECT * FROM ACCOUNTS_RECEIVABLE_AGING_DELIVERY);";
	if(mysqli_multi_query($con ,$query)){
		while (mysqli_next_result($con));
		echo "true";
	}else{
		echo "false";
	}

}

?>
