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

$str=" ";


$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']);
$error=0;

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


//echo $inv_new_no;

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

if ($count>0)
{

	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=$rowsp['discount'];
		$inv_id_sr=$rowsp['inv_id_sr'];
		$emp_id=$rowsp['emp_id'];
		$vat_inv=$rowsp['vat_inv'];
	} ////  while($rowsp=mysqli_fetch_array($query)){	


if($vat_inv > 0 ) { $seq_no=8 ;} 
else {$seq_no=9 ; } 


/////!!!!!!!!!!!!!!!!!!  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);
}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~   End of sequence ~~~~~~~~~~~~~~~~~~









	/// !!!!!!!!!!!!!!!!!!!      item detail
	$queryd=mysqli_query($con," SELECT inv_temp_detail.*,item_master.item_name,item_master.sales_price AS sp,item_master.cost_price AS cp,
		item_stocks.loc_qoh
 		FROM inv_temp_detail
		LEFT JOIN item_master ON item_master.item_id=inv_temp_detail.item_id
		LEFT JOIN item_stocks ON item_stocks.item_id=inv_temp_detail.item_id AND item_stocks.loc_id=$loc_id 
		where inv_temp_detail.invd_id='$inv_no'
   		")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'];	
					//echo $rowd['qty'];
					$pp=0-$rowd['qty'];
					//echo $pp;
					$qty_sale= 0-$rowd['qty'];
					$qty= $rowd['qty'];
					$sp=$rowd['sales_price'];
					$cp=$rowd['cost_price'];
					$loc_qoh=$rowd['loc_qoh'];		
					$item_dis=$rowd['item_dis'];
                    $vat_amt=$rowd['vat'];



					//qty_sale
					//if 	($loc_qoh >= $qty) {
						//$qty_sale=$qty;

					//}
					//else
					//{
						//$qty_sale=$loc_qoh;

					//}

					$tot_temp=0  ;
		            $tot_temp_vat=0;
//echo "ss";
//$rr="INSERT INTO inv_detail(inv_id,item_id,qty,item_dis,sales_price,cost_price,qoh,loc_id) 
	        //VALUES('$inv_new_no',$item_id,$pp,$item_dis,$sp,$cp,$loc_qoh,$loc_id ) ";

//echo $rr;
					
			if ( mysqli_query($con,"INSERT INTO inv_detail(inv_id,item_id,qty,item_dis,sales_price,cost_price,qoh,loc_id,vat) 
	        VALUES('$inv_new_no',$item_id,$pp,$item_dis,$sp,$cp,$loc_qoh,$loc_id,$vat_amt )  ")or die(mysqli_error($con)))
	        {  

	     
	        		//////////////// Stock Update	    
	        	if ( mysqli_query($con,"update item_stocks set loc_qoh = loc_qoh + $qty where item_id=$item_id and  loc_id='$loc_id' ")or die(mysqli_error($con)))
		               {         

		               	$tot_temp=($pp * $sp)-($pp * $sp * $item_dis/100 )  ;
		               	$tot_temp_vat=$tot_temp + ( $tot_temp * $vat/100 );
		               	$tot_inv_gross=$tot_inv_gross + $tot_temp_vat ;
		                   }	
				///////////////////////end of stock update
if ( mysqli_query($con,"update item_master set  qoh=qoh + $qty where item_id=$item_id  ")or die(mysqli_error($con)))
		{
			//echo "<script>document.location='Admin_location_view.php'</script>"; 
		}











			} ////  if ( mysqli_query($con,"INSERT INTO inv_detail(

				} ////while($rowd=mysqli_fetch_array($queryd)){ 
			}  //// if ($countd>0)

///Final inv tot calculation /////////////////////




///~~~~~~~~~~~~~~Final Discount /////////////////////
$inv_gross_dis=0;
if (!empty($discount)){

	if ($discount>0 ) {

			$inv_gross_dis=	$tot_inv_gross * $discount /100 ;
			$tot_inv_gross= $tot_inv_gross - $inv_gross_dis ;
	}
}



      if ( mysqli_query($con,"INSERT INTO inv_header(inv_id,inv_date,loc_id,inv_ref,cus_id,note,discount,inv_type,inv_id_sr,edate,emp_id,vat_inv) 
		VALUES('$inv_new_no','$edate',$loc_id,'$invd_ref','$cus_id','$note',$discount ,2,'$inv_id_sr','$edate1',$emp_id,$vat_inv)  ")or die(mysqli_error($con)))
	        {


	 if ( mysqli_query($con,"INSERT INTO seheader(docid,docdate,doctype,cost,amount,refno,empcode,party_id,party_type,cancel,dbcr,userid,edate) 
 VALUES('$inv_new_no','$edate','sr','$cost',$tot_inv_gross,'$invd_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_id=$seq_no  ")or die(mysqli_error($con)))			
						{   
							if ( mysqli_query($con,"delete from inv_temp_detail where invd_id='$inv_no' ")or die(mysqli_error($con))) {	


								if ( mysqli_query($con,"delete from inv_temp_header where invd_id='$inv_no' ")or die(mysqli_error($con))) {	


							if (!mysqli_commit($con)) {
							    echo("Transaction commit failed\n");
							    exit();
							}
							else {
					       // echo "<script>document.location='inv_new.php '</script>";
								//echo "aa";

							}



							}

								 }  ////  if ( mysqli_query($con,"delete from 


			}  ///// if ( mysqli_query($con,"delete from inv_temp_detail 



						} /// if ( mysqli_query($con,"update sequence set cno =cno + 1  where 
             } ///// f ( mysqli_query($con,"INSERT INTO inv_header(


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

?>
<script>
        function printPage() {
           // window.print(); // This initiates the print dialog
url='https://invox.lk/salessys/pages/sr.php?inv_no=<?php echo $inv_new_no;?> ';
 var printWindow = window.open( url, 'Print', 'left=200, top=200, width=950, height=500, toolbar=0, resizable=0' , '_blank');

    printWindow.addEventListener('load', function() {
        if (Boolean(printWindow.chrome)) {
            printWindow.print();
            setTimeout(function(){
                printWindow.close();
               window.location.href = "sri_new.php";
            }, 500);
        } else {
            printWindow.print();
            printWindow.close();
            // window.location.href = "inv_new.php";
        }
    }, true);



        }

window.onload = function() {
        printPage();
      // window.location.href = "inv_new.php";
    };
        
    </script>    
