<?php  
	require "commonincludefiles.php";
	
	if($_SESSION["cUserId"]!="" && isset($_SESSION["cUserId"]))
	{
		
		//print_r($_REQUEST);
		
		$objlms_custinvoicereceiptMgmt= new lms_custinvoicereceiptMgmt();
		$objlms_custinvoicereceiptMgmt->receipt_id=$_POST['receipt_id'];
		$objlms_custinvoicereceiptMgmt->receipt_no=$_POST['receipt_no'];
		$objlms_custinvoicereceiptMgmt->receipt_date=$_POST['receipt_date'];
		if(!isset($_POST['chk_date']) || $_POST['chk_date'] == "")
		{
			$objlms_custinvoicereceiptMgmt->chk_date=date("d/m/Y");
		}
		else{
			$objlms_custinvoicereceiptMgmt->chk_date=$_POST['chk_date'];
		}
		
		$objlms_custinvoicereceiptMgmt->customer_id=$_POST['customer_id'];
		$objlms_custinvoicereceiptMgmt->invoice_no=$_POST['invoicenos'];
		$objlms_custinvoicereceiptMgmt->amount=$_POST['amount'];
		if($_POST['cash'] == true)
			$objlms_custinvoicereceiptMgmt->payment_mode=1;
		else
			$objlms_custinvoicereceiptMgmt->payment_mode=0;
			
		$objlms_custinvoicereceiptMgmt->chequeno=$_POST['chequeno'];
		$objlms_custinvoicereceiptMgmt->bankname=$_POST['bankname'];
		$objlms_custinvoicereceiptMgmt->branchname=$_POST['branchname'];
		$objlms_custinvoicereceiptMgmt->remark=$_POST['remark'];	
		
		if($_POST["invoicenos"] != "")
		{
		$objCustomerInvoiceMgmt = new CustomerInvoiceMgmt();  
		$condition .= " AND li.customerinvoice_no in (".$_POST["invoicenos"].")";
		$result = $objCustomerInvoiceMgmt->getAllRecords(0,0,$condition,$order_field,$order_type) ;
		
		if(dbRows($result) > 0){
			$paidinvoicenos="";
			$remamount=$_POST['amount'];
			
			while($row = dbArray($result))
			{	$con="";
				if($remamount >= $row['dueamount'])
					{
					$con .= " dueamount=0, status='Paid'";	
					$remamount=$remamount-$row['dueamount'];
					$paidinvoicenos=$paidinvoicenos.$row['customerinvoice_no'].",";	
					$objCustomerInvoiceMgmt->updatestatus($row['customerinvoice_id'],$con);
					}
				else if($remamount != 0)
					{
						
						$rem= $row['dueamount']-$remamount;
						$con .= " dueamount=".$rem;
						$remamount=0;
						$paidinvoicenos=$paidinvoicenos.$row['customerinvoice_no'].",";
						$objCustomerInvoiceMgmt->updatestatus($row['customerinvoice_id'],$con);
					}
				
			}
			$objlms_custinvoicereceiptMgmt->invoice_no=substr($paidinvoicenos, 0, -1);
		}
				
				
		}
		if($objlms_custinvoicereceiptMgmt->receipt_id == "0" ||  $objlms_custinvoicereceiptMgmt->receipt_id== "")
		{ 
		$objlms_custinvoicereceiptMgmt->add(); 
		}  
		else
		{
		if($_REQUEST[act] == "del")
		{
		 	$objlms_custinvoicereceiptMgmt->updatedelstatus();
		}
		else
		{
		 	$objlms_custinvoicereceiptMgmt->edit();
		}
		}
		echo'{"success":"true"}'; 
		 
		
	}
	else
	{
		echo '{"success":"false","msg":"session expiry"}';
	}
?>