<?php 
session_start();
include('../includes/dbcon.php');

$str=" ";


$edate=date("Y-m-d");
$userid=$_SESSION['rm_id'];

$dd = $_POST["dd"];
$appamt_doc= $_POST['appamt'];

$cus_id= mysqli_real_escape_string($con,trim($_POST["cus_id"]));
$rtype= mysqli_real_escape_string($con,trim($_POST["rtype"]));
$amount= mysqli_real_escape_string($con,trim($_POST["amount"]));
$cus_id= mysqli_real_escape_string($con,trim($_POST["cus_id"]));
$ref= mysqli_real_escape_string($con,trim($_POST["ref"]));
//$note= $_POST["note"];
$cashdate= mysqli_real_escape_string($con,trim($_POST["cashdate"]));
$emp_id= mysqli_real_escape_string($con,trim($_POST["emp_id"]));
$deposit=0;


if (empty($cus_id)){
    echo "<script type='text/javascript'>alert('Please select The Customer !');</script>";
	echo "<script>document.location='receipt_new.php'</script>";
}

if (empty($amount)){
 echo "<script type='text/javascript'>alert('Please Enter Amount !');</script>";
	echo "<script>document.location='receipt_new.php'</script>";
}


if (empty($rtype)){
 echo "<script type='text/javascript'>alert('Please select The Payment Mode  !');</script>";
	echo "<script>document.location='receipt_new.php'</script>";
}





$cost="MAT";
$error=0;
$seq=0;
if ($rtype=='Cash'){
	$chqno=0;
	$Chqbank='';
	$chqbranch='';
	$dep_bank=0;
	$cdate=date("1970-01-01");
	$refdate=$_POST["cashdate"];
	$realise_date=$_POST["cashdate"];
	$seq=7;
	$deposit=0;
	$depdate= date("1970-01-01");
}
if ($rtype=='Cheque'){
	$chqno= $_POST["chqno"];
	$cdate= $_POST["chqdate"];
	$Chqbank= $_POST["cbank"];
	$chqbranch= $_POST["cbranch"];
	$dep_bank=0;
	$seq=12;
	$refdate=date("1970-01-01");
	$depdate= date("1970-01-01");
	$deposit=0;
	$realise_date=date("1970-01-01");
}

if ($rtype=='DD'){
	$chqno=0;
	$Chqbank='';
	$chqbranch='';
	$dep_bank= $_POST["abank"];
	$cdate=date("1970-01-01");
	$refdate=date("1970-01-01");
	$seq=14;	
	$depdate= $_POST["adate"];
	$deposit=1;
	$realise_date= $_POST["adate"];
}

$sysapp_amt=0;
$tot_app=0;

$error=0;


mysqli_begin_transaction($con);

/////!!!!!!!!!!!!!!!!!!  sequence   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$querydoc=mysqli_query($con,"select * from sequence where seq_type='re' ")or die(mysqli_error());
while($row=mysqli_fetch_array($querydoc)){  
	$prefix=$row['prefix'];

		//if (empty($prefix)){  $new_receipt_no=$row['cno']; }
//	else { $new_receipt_no=$prefix . $row['cno']; }
$prefix=$row['prefix'];
//$inv_new_no=$prefix . $row['cno'];
$numberOfDigits = 6;
$cno=$row['cno'];
$new_receipt_no = $prefix . sprintf('%0' . $numberOfDigits . 'd', $cno);

}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~   End of sequence ~~~~~~~~~~~~~~~~~~


///////  Insert into seheader and chqheader /////////////////

if ( mysqli_query($con,"INSERT INTO seheader(docid,docdate,doctype,cost,amount,refno,empcode,party_id,party_type,cancel,dbcr,userid,edate) 
 VALUES('$new_receipt_no','$edate','Re','$cost',0-$amount,'$ref',$emp_id,$cus_id,1,0,'cr',$userid,'$edate' )  ")or die(mysqli_error($con)))
	        {

	        	
	        			if ( mysqli_query($con,"update sequence set cno =cno + 1  where seq_type='re'  ")or die(mysqli_error($con)))			
						{   

				if ( mysqli_query($con,"INSERT INTO chqheader(docid,docdate,type,refno,cost,amount,empcode,cus_id,cancel,Chqno,chqdate,Chqbank,chqbranch,realize,deposit,dep_bank,ChqReturn,userid,edate,realise_date,dep_date) 
 VALUES('$new_receipt_no','$edate','$rtype','$ref','$cost',$amount,$emp_id,$cus_id,0,'$chqno','$cdate','$Chqbank','$chqbranch',0,$deposit ,$dep_bank,0,$userid,'$edate','$realise_date','$depdate')  ")or die(mysqli_error($con)))

	        {      

	        }	//// end of INSERT INTO chqheader 
	        else {  $error=1;}

	      }   //// end of update sequence 
	      else {  $error=1;}     

	  }  //// end of INSERT INTO seheader
	  else {  $error=1;}
				 
	
///~~~~~~~~~~~~~~~ End of   inserting into seheader and chqheader /////////////////


for($i = 0; $i<count($dd); $i++){
	$appamt= $appamt_doc[$i];
	$appdocid=$dd[$i];


if (!empty($appamt)){
if ($appamt>0) {



		// --- getting O/S of a document--------------		
		$sqlsp=mysqli_query($con,"SELECT *,IFNULL((SELECT SUM(applyamount)FROM sedetail
WHERE sedetail.docid=seheader.docid AND seheader.party_id=sedetail.party_id AND
 docid IN (SELECT docid FROM seheader WHERE cancel<>1 AND docdate<= '$edate' )
 AND Refdocno IN (SELECT docid FROM seheader AS sh2 WHERE cancel<>1 AND docdate<= '$edate' )
 ),0) 
  AS app,
  (seheader.amount-
  IFNULL((SELECT SUM(applyamount)FROM sedetail
WHERE sedetail.docid=seheader.docid AND seheader.party_id=sedetail.party_id AND
 docid IN (SELECT docid FROM seheader WHERE cancel<>1 AND docdate<= '$edate' )
 AND Refdocno IN (SELECT docid FROM seheader AS sh2 WHERE cancel<>1 AND docdate<= '$edate' )
 ),0) )
  AS bal
 FROM seheader
 WHERE seheader.cancel<>1 AND seheader.party_id=$cus_id  AND seheader.docid='$appdocid' ")or die(mysqli_error($con));
	        	$count=mysqli_num_rows($sqlsp);	
	        	if ($count>0) {
	        
	        		while($row=mysqli_fetch_array($sqlsp)){			
					 	   $docid=$row['docid'];	
					 	   $bal=$row['bal'];

					 	   if ($appamt<=$bal){  $sysapp_amt=$appamt;    }
					 	   else { $sysapp_amt=$bal;  }

					 	   $tot_app=$tot_app + $sysapp_amt ;
					 	   if ($tot_app<=$amount){

//////////////////settlement detail  /////////////////////
					 	   	///////apply doc settlement
if ( mysqli_query($con,"INSERT INTO sedetail(docid,applyamount,applydate,Refdocno,initdoc,party_id,userid,edate) 
 VALUES('$docid',$sysapp_amt,'$edate','$new_receipt_no','$new_receipt_no','$cus_id',$userid,'$edate')  ")or die(mysqli_error($con)))
{


		if ( mysqli_query($con,"INSERT INTO sedetail(docid,applyamount,applydate,Refdocno,initdoc,party_id,userid,edate) 
		 VALUES('$new_receipt_no',0-$sysapp_amt,'$edate','$docid','$new_receipt_no','$cus_id',$userid,'$edate')  ")or die(mysqli_error($con)))
		{


				/////insert into chqdetail

		if ( mysqli_query($con,"INSERT INTO chqdetail(docid,app_docid,applyamount) 
		 VALUES('$new_receipt_no','$docid',$sysapp_amt)  ")or die(mysqli_error($con)))
		{ } else {  $error=1;}
				///~~~~~~~~~~~~~~end of /////insert into chqdetail

		} else {  $error=1;}

}  /////if ( mysqli_query($con,"INSERT INTO sedetail(
 else {  $error=1;}
			

///~~~~~~~~~~~~~end of apply doc settlement ----------------------

					 	   }

				   }	

				}

			} ////if ($appamt>0) {
		}  ///if (!empty($appamt)){



}  //////for($i = 0; $i<count($dd); $i++){
if ($error==0){
mysqli_commit($con);
//echo "<script>document.location='receipt_new.php'</script>";
echo '<script>';								 
echo 'var invoiceWindow = window.open("receipt.php?docid=' . $new_receipt_no . '", "Receipt", "width=800,height=800");';
echo 'function printAndClose() {';
echo 'invoiceWindow.print();';
echo '};';
echo 'invoiceWindow.print();';
echo 'invoiceWindow.onafterprint = function() {';
echo 'invoiceWindow.close();'; // Close the window after printing
echo 'window.location.href = "receipt_new.php";'; // Navigate to inv_new.php after closing the window
echo '};';
echo '</script>';
}

else {
mysqli_rollback($con);
mysqli_close($con);
	echo "<script type='text/javascript'>alert('Some Error Occured!');</script>";
	echo "<script>document.location='receipt_new.php'</script>";
}



?>