<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$receipt = $_POST['receipt'];
	$cancelreason = trim($_POST['cancelreason']);
	$recversion = $_POST['recversion'];
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 1 || $_SESSION["connectedusergroup"] == 3)
		{
			if($receipt == "")
			{
				$err = $err."Receipt Identification Required!<br>";
			}
			else
			{
				$receiptdata = DB::queryFirstRow("SELECT value_date, receipt_number, shop, customer_name, bill, is_cancelled FROM cash_receipt WHERE id=%i", $receipt);
			
				if(DB::count() != 1)
				{
					$err = $err."Receipt Not Identified!<br>";
				}
				else
				{
					if($_SESSION["connectedusergroup"] == 3 && $receiptdata['shop'] != $_SESSION["connecteduserbranch"])
					{
						$err = $err."You Cannot Cancel Receipts In A Shop Other Than Yours!<br>";
					}
					else
					{
						if($receiptdata['is_cancelled'] == 1)
						{
							$err = $err."Receipt Is Already Cancelled!<br>";
						}
						else
						{
							if($cancelreason == "")
								$err = $err."Cancel Reason Required!<br>";
						}
					}
				}
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}

	if($err == "")
	{
		DB::$error_handler = false;
		DB::$throw_exception_on_error = true;
		
		try
		{
			$trxnConnextn = new MeekroDB();
			$nonTrxnConnextn = new MeekroDB();
			
			$trxnConnextn->startTransaction();
			$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
			$trxnConnextn->query("SELECT * FROM cash_receipt WHERE id=%i FOR UPDATE", $receipt);
			
			$trxnConnextn->update
			('cash_receipt', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'is_cancelled' => 1,
					'cancelled_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'cancelled_by' => $_SESSION["connecteduserid"],
					'cancel_reason' => $cancelreason,
					'version' => ($recversion + 1)
				), 
				"id=%i", $receipt
			);
					
			$trxnConnextn->update
			('cash_sale_item', 
				array
				(
					'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
					'updated_by' => $_SESSION["connecteduserid"],
					'is_cancelled' => 1
				), 
				"receipt=%i", $receipt
			);
			 
			$row = $nonTrxnConnextn->queryFirstRow("SELECT version FROM cash_receipt WHERE id=%i LIMIT 1", $receipt);
			
			if($row['version'] == $recversion)
			{
				$trxnConnextn->commit();
				$savestatusmessage = "<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Receipt Successfully Cancelled!</div>";
				$server_response[] = array('issaved' => 1, 'message' => $savestatusmessage);
				DB::$error_handler = 'meekrodb_error_handler';
				DB::$throw_exception_on_error = false;
				echo json_encode($server_response);
			}
			else
			{
				$trxnConnextn->rollback();
				$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Receipt Could Not Be Cancelled Due To Updates Just Done By Another System User</div>";
				$server_response[] = array('issaved' => 0, 'message' => $errormessage);
				DB::$error_handler = 'meekrodb_error_handler';
				DB::$throw_exception_on_error = false;
				echo json_encode($server_response);
			}
		}
		catch(MeekroDBException $e)
		{
			$err = $err.$e->getMessage()."<br>";
			$err = $err.$e->getQuery()."<br>";
			$trxnConnextn->rollback();
			$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" . $err . "</div>";
			$server_response[] = array('issaved' => 0, 'message' => $errormessage);
			DB::$error_handler = 'meekrodb_error_handler';
			DB::$throw_exception_on_error = false;
			echo json_encode($server_response);
			exit();
		}
	}
	else
	{
		$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" . $err . "</div>";
		$server_response[] = array('issaved' => 0, 'message' => $errormessage);
		echo json_encode($server_response);
	}
?>