<?php
	header('Content-Type: application/json');
	require ('my_functions.php');
	include('Aira_settings.php');
	
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$customername = trim($_POST['customername']);
	$cashpaid = (str_replace(",", "", trim($_POST['cashpaid'])) == "" ) ? 0 : str_replace(",", "", trim($_POST['cashpaid']));
	$receiptmode = trim($_POST['receiptmode']);
	$cartitems = json_decode(stripslashes($_POST['cartitems']), TRUE);
	$notes = trim($_POST['notes']);
	 
	$repaired_by = trim($_POST['mechanic']);
	
	$customer_id = trim($_POST['customername']);
	//now capture whoserved the client
	$attendant = trim($_POST['attendant']);
	
	
	$bill = 0;
	$customerchange = 0;
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 3 || $_SESSION["connectedusergroup"] == 4)
		{
			if(empty($cartitems))
			{
				$err = $err."Cart Items Required!<br>";
			}
			else
			{
				foreach($cartitems as $cartitem)
				{
					$bill += ($cartitem['sellprice'] * $cartitem['quantity']);
				}
				
				$customerchange = ($cashpaid - $bill);
			}
		}
		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();
			
			$trxnConnextn->startTransaction();
			$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
			
			$usershopcode = $trxnConnextn->queryFirstField("SELECT shop_code FROM shop WHERE id=%i LIMIT 1", $_SESSION["connecteduserbranch"]);
			
			$usereceiptnumberseq = $trxnConnextn->queryFirstField("SELECT receipt_number FROM cash_sale_receipt_number_seq WHERE id=%i", $_SESSION["connecteduserbranch"]);
			$trxnConnextn->query("UPDATE cash_sale_receipt_number_seq SET receipt_number=%i WHERE id=%i", ($usereceiptnumberseq + 1), $_SESSION["connecteduserbranch"]);
			$receiptnumberseq = $trxnConnextn->queryFirstField("SELECT receipt_number FROM cash_sale_receipt_number_seq WHERE id=%i", $_SESSION["connecteduserbranch"]);
			
			#$customer_claim = $trxnConnextn->queryFirstField("SELECT claim FROM customers WHERE id={$customer_id}");
			$customer_claim = Commission_settings(  1);
			$customer_name = 'Cash sale';
			if($customer_id > 0){
			
			 $customer_name = $trxnConnextn->queryFirstField("SELECT name FROM customers WHERE id={$customer_id}");
			}
			
			
		
			$receiptnumber = $usershopcode . str_pad($receiptnumberseq, 10, '0', STR_PAD_LEFT);
			
			$trxnConnextn->insert
			('cash_receipt', 
				array
				(
					'created_date' => date("Y-m-d H:i:s"),
					'created_by' => $_SESSION["connecteduserid"],
					'value_date' => date("Y-m-d"),
					'receipt_number' => $receiptnumber,
					'shop' => $_SESSION["connecteduserbranch"],
					'customer_name' => ($customer_name != "") ? $customer_name : "Sales",
					'bill' => $bill,
					'amount' => $cashpaid,
					'receipt_mode' => $receiptmode,
					'customer_change' => $customerchange,
					'memo' => $notes,
					'attendant' => $attendant,
					'repaired_by' => $repaired_by,
					'customer_id' => $customer_id,
					'claim' => $customer_claim,
					'sale_type' => 1
				)
			);
			
			$insertedrecord = $trxnConnextn->insertId();
			
			foreach($cartitems as $cartitem)
			{
				
				 $pice_id = $cartitem['priceid'];
				$qty = $cartitem['quantity'];
 
				$shop =  $_SESSION["connecteduserbranch"];
				
				$item_id = Item_id($pice_id, $shop );
				$bal_qn = Stock_level($item_id   , $shop);
				 $balance = $bal_qn[0];
				$stock_id = $bal_qn[1];
				 
				 
				$balance = $balance-$qty;
				if($balance < 1){
					$balance = 0;
				}
				
				Change_quantity( $balance , $stock_id, $_SESSION["connecteduserid"]);
		 
				
				
				
				
				$trxnConnextn->insert
				('cash_sale_item', 
					array
					(
						'created_date' => date("Y-m-d H:i:s"),
						'created_by' => $_SESSION["connecteduserid"],
						'shop' => $_SESSION["connecteduserbranch"],
						'receipt' => $insertedrecord,
						'price_id' => $cartitem['priceid'],
						'sell_price' => $cartitem['sellprice'],
						'quantity' => $cartitem['quantity'],
						'serial_number' => ($cartitem['serialnumber'] != "") ? $cartitem['serialnumber'] : NULL,
						 
					    'sales_type' => 1
					)
				);
			}
		
			$trxnConnextn->commit();
			//send_receipt($insertedrecord);
			$savestatusmessage = "<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Cash Sale Successfully Processed!</div>";
			$server_response[] = array('issaved' => 1, 'message' => $savestatusmessage, 'receipt' => $insertedrecord);
			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);
	}
?>