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

$str=" ";
$r_id=0;

$edate=date("Y-m-d");
$edate1=date("Y-m-d h:i:sa");
$userid=$_SESSION['rm_id'];

$inv_no= trim($_POST['inv_no']);
$loc_id= trim($_POST['loc_id']);
$pcash= trim($_POST['pcash1']);
$mdiscount= trim($_POST['discount']);
$error=0;
$no_of_item=0;
$inv_discount=0;

$qty_sale=0;
$vat=0;
$cost='MAT';
$tot_inv_gross=0;


$pcash = isset($_POST['pcash1']) ? trim($_POST['pcash1']) : 0;



//echo $inv_new_no;

/////!!!!!!!!!!!!!!!!!!  Open inv_temp_header   !!!!!!!!!!!!!!!!!!!!!!!!!!!!
$query=mysqli_query($con," select * from einv_temp_header where invd_id='$inv_no'  ")or die(mysqli_error($con));
$count=mysqli_num_rows($query);

if ($count>0)
{
 //echo "hh";
	while($rowsp=mysqli_fetch_array($query)){			
		//$grnd_no=$rowd['grnd_no'];	
		$invd_date=$rowsp['invd_date'];
		$loc_id=$rowsp['loc_id'];	
		$cus_id=$rowsp['cus_id'];
		$invd_ref=$rowsp['invd_ref'];
		$note=$rowsp['note'];
		$discount=$mdiscount ; //$rowsp['discount'];
		$invtype_id=$rowsp['invtype_id'];
		$emp_id=$rowsp['emp_id'];
		$r_id=$rowsp['r_id'];
		$vat_inv=$rowsp['vat_inv'];
		$sup_code=$rowsp['sup_code'];
		$delivery_id=$rowsp['delivery_id'];
		$po=$rowsp['po'];
	} ////  while($rowsp=mysqli_fetch_array($query)){	
if($vat_inv > 0 ) { $seq_no=7 ;} 
else {$seq_no=6 ; } 
 
 
 /////!!!!!!!!!!!!!!!!!!  sequence   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//$querydoc=mysqli_query($con,"select * from sequence where seq_id=$seq_no ")or die(mysqli_error());
//while($row=mysqli_fetch_array($querydoc)){  
//$prefix=$row['prefix'];

//$numberOfDigits = 6;
//$cno=$row['cno'];
//$inv_new_no = $prefix . sprintf('%0' . $numberOfDigits . 'd', $cno);

$querydoc = mysqli_query($con, "SELECT * FROM esequence WHERE seq_id = $seq_no") or die(mysqli_error($con));
while ($row = mysqli_fetch_array($querydoc)) {
    $prefix = $row['prefix'];
    $cno = $row['cno'];

    // Get current month in 2 digits
    $month = date('m');

    // Number part (4 digits)
    $numberOfDigits = 4;

    // Format the invoice number
    $inv_new_no = $prefix . $month . sprintf('%0' . $numberOfDigits . 'd', $cno);

    // Example result: INV050001
}




}

 //echo $inv_new_no;
///~~~~~~~~~~~~~~~~~~~~~~~~~~~   End of sequence ~~~~~~~~~~~~~~~~~~
 
 if (empty($inv_new_no)){ exit();  } 


	$queryd=mysqli_query($con," SELECT einv_temp_detail.*,item_master.item_name,item_master.sales_price AS sp,item_master.cost_price AS cp,
		item_stocks.loc_qoh
 		FROM einv_temp_detail
		LEFT JOIN item_master ON item_master.item_id=einv_temp_detail.item_id
		LEFT JOIN item_stocks ON item_stocks.item_id=einv_temp_detail.item_id AND item_stocks.loc_id=$loc_id 
		where einv_temp_detail.invd_id='$inv_no' order by eseq
   		")or die(mysqli_error($con));

			$countd=mysqli_num_rows($queryd);
			mysqli_begin_transaction($con);
			if ($countd>0)
			{

				while($rowd=mysqli_fetch_array($queryd)){ 	
					$item_id=$rowd['item_id'];	
					$qty=$rowd['qty'];
					$sp=$rowd['sp'];
					$cp=$rowd['cp'];
					$loc_qoh=$rowd['loc_qoh'];		
					$item_dis=$rowd['item_dis'];
					$vat_amt=$rowd['vat'];
					$eseq=$rowd['eseq'];
					
						if 	($qty >= 0) {

                					if 	($loc_qoh >= $qty) {
                						$qty_sale=$qty;
                
                					}
                					else
                					{
                						$qty_sale=$loc_qoh;
                
                					}
					
						}
						
						else { $qty_sale=$qty; } 
					

					    $tot_temp=0  ;
		            	$tot_temp_vat=0;



 if ($qty_sale<>0) {    
		         if ($sp>0.00) { 		
		         	if ($item_id>0) {	
	///////////////////////////////////////////////////////////////////////////////	    
		         	    		if ( mysqli_query($con,"INSERT INTO einv_detail(inv_id,item_id,qty,item_dis,sales_price,cost_price,qoh,loc_id,vat,eseq) 
	        VALUES('$inv_new_no',$item_id,$qty_sale,$item_dis,$sp,$cp,$loc_qoh,$loc_id,$vat_amt,$eseq )  ")or die(mysqli_error($con)))
	        {  
	            
	             	if ( mysqli_query($con,"update item_stocks set loc_qoh = loc_qoh - $qty_sale where item_id=$item_id and  loc_id='$loc_id' ")or die(mysqli_error($con)))
		               {         

		               	$tot_temp=($qty * $sp)-($qty * $sp * $item_dis/100 )  ;
		               	$tot_temp_vat=$tot_temp + ( $tot_temp * $vat/100 );
		               	$tot_inv_gross=$tot_inv_gross + $tot_temp_vat ;
		               	
		               	 if ($discount<>0) {

                                    $inv_discount= $tot_inv_gross * $discount/100;
                                    $net_total=$tot_inv_gross - $inv_discount;
                                   }
                                   else
                                    { 
                                       $net_total=$tot_inv_gross;
                                    }
		               	
		               	
		               //	echo $tot_temp;
		               	//echo $tot_temp_vat;
		               	// echo "hh";
		                   }
		                   
		                   if ( mysqli_query($con,"update item_master set  qoh=qoh - $qty_sale where item_id=$item_id  ")or die(mysqli_error($con)))
		{
			
			$no_of_item=$no_of_item+1;
			//echo "<script>document.location='Admin_location_view.php'</script>"; 
		}	
	        }  //// INSERT INTO inv_detail
	///////////////////////////////////////////////////////////////////////////////////////	         	    
		         	    
		         	}}}  ////////////////end of if ($qty_sale>0) {    if ($sp>0.00) { 	if ($item_id>0) {
		         		
		         



} /////	while($rowsp=mysqli_fetch_array($query)){	

} ////   	if ($countd>0)


if ($no_of_item>0) {
      if ( mysqli_query($con,"INSERT INTO einv_header(inv_id,inv_date,loc_id,inv_ref,cus_id,note,discount,inv_type,invtype_id,edate,emp_id,vat_inv,sup_code,delivery_id,po) 
	VALUES('$inv_new_no','$edate',$loc_id,'$invd_ref','$cus_id','$note',$discount,1,$invtype_id,'$edate1',$emp_id ,$vat_inv,'$sup_code',$delivery_id,'$po')  ")or die(mysqli_error($con)))
	        {
	            
	           
 if ( mysqli_query($con,"INSERT INTO eseheader(docid,docdate,doctype,cost,amount,refno,empcode,party_id,party_type,cancel,dbcr,userid,edate) 
 VALUES('$inv_new_no','$edate','sa','$cost',$net_total,'$invd_ref',$emp_id,$cus_id,1,0,'db',$userid,'$edate' )  ")or die(mysqli_error($con)))
	        {
	            	if ( mysqli_query($con,"update esequence set cno =cno + 1  where seq_id=$seq_no  ")or die(mysqli_error($con)))			
						{   
						  if ( mysqli_query($con,"delete from einv_temp_detail where invd_id='$inv_no' ")or die(mysqli_error($con))) {	
if ( mysqli_query($con,"delete from einv_temp_header where invd_id='$inv_no' ")or die(mysqli_error($con))) {	
    if($pcash>0 ){
    create_receipt($con, $inv_new_no, $cus_id, $net_total, 'cash', $emp_id,$pcash);
    }
    
    
    
    if (!mysqli_commit($con)) {
							    echo("Transaction commit failed\n");
							    exit();
							}
    
    else {
					        //echo "<script>document.location='invoice.php?inv_no=$inv_new_no '</script>";
								 echo '<script>';

								 
//echo 'var invoiceWindow = window.open("invoice.php?inv_no=' . $inv_new_no . '", "Invoice", "width=800,height=800");';
if ($vat_inv > 0) {
    echo 'var invoiceWindow = window.open("invoicetax.php?inv_no=' . $inv_new_no . '", "Invoice", "width=800,height=800");';
} else {
    echo 'var invoiceWindow = window.open("einvoice.php?inv_no=' . $inv_new_no . '", "Invoice", "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 = "einv_new.php";'; // Navigate to inv_new.php after closing the window
echo '};';
echo '</script>';


							}
    
    
    
    
    
    
    
    
    
    
}

						  } 
						}
	        }

}    ///INSERT INTO inv_header
    
    
} ///if ($no_of_item>0) {








//} /////if ($count>0)



function create_receipt($con, $inv_new_no, $cus_id, $net_total, $rtype, $emp_id,$amount) {
    $edate = date("Y-m-d");
    $edate1 = date("Y-m-d h:i:sa");
    $userid = $_SESSION['rm_id'];
    
    $cost="MAT";
$error=0;
$seq=0;
    
    	$chqno=0;
	$Chqbank='';
	$chqbranch='';
	$dep_bank=0;
	$cdate=date("1970-01-01");
	$refdate=$edate;
	$realise_date=$edate;
	$seq=7;
	$deposit=0;
	$depdate= date("1970-01-01");
    
    /////!!!!!!!!!!!!!!!!!!  sequence   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$querydoc=mysqli_query($con,"select * from esequence where seq_type='re' ")or die(mysqli_error());
while($row=mysqli_fetch_array($querydoc)){  
	$prefix=$row['prefix'];


$prefix=$row['prefix'];
$numberOfDigits = 6;
$cno=$row['cno'];
$new_receipt_no = $prefix . sprintf('%0' . $numberOfDigits . 'd', $cno);

}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~   End of sequence ~~~~~~~~~~~~~~~~~~
if ( mysqli_query($con,"INSERT INTO eseheader(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 esequence set cno =cno + 1  where seq_type='re'  ")or die(mysqli_error($con)))			
						{  
						    
						  if ( mysqli_query($con,"INSERT INTO echqheader(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)))

	        {  
	           
	          // $mp=" INSERT INTO sedetail(docid,applyamount,applydate,Refdocno,initdoc,party_id,userid,edate) 
 //VALUES('$inv_new_no',2400,'$edate','$new_receipt_no','$new_receipt_no',$cus_id,$userid,'$edate')  ";
 //echo $mp;
	           
	           if ( mysqli_query($con,"INSERT INTO esedetail(docid,applyamount,applydate,Refdocno,initdoc,party_id,userid,edate) 
 VALUES('$inv_new_no',$amount,'$edate','$new_receipt_no','$new_receipt_no',$cus_id,$userid,'$edate')  ")or die(mysqli_error($con)))
                {  
                    
                    
		if ( mysqli_query($con,"INSERT INTO esedetail(docid,applyamount,applydate,Refdocno,initdoc,party_id,userid,edate) 
		 VALUES('$new_receipt_no',0-$amount,'$edate','$inv_new_no','$new_receipt_no','$cus_id',$userid,'$edate')  ")or die(mysqli_error($con)))
		{  
		    ///echo "ddd"; 
		    	if ( mysqli_query($con,"INSERT INTO echqdetail(docid,app_docid,applyamount) 
		 VALUES('$new_receipt_no','$inv_new_no',$amount)  ")or die(mysqli_error($con)))
		{ }
		    
		}
                
                    
                }
                
	        }
						    
			}
	            
	        }
 
            }

?>
