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

$str=" ";

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

$grn_no= trim($_POST['grn_no']);
$grnd_loc_id= trim($_POST['loc_id']);
$error=0;
$se=0;


/////!!!!!!!!!!!!!!!!!!  sequence   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$querydoc=mysqli_query($con,"select * from sequence where seq_id=1 ")or die(mysqli_error());
while($row=mysqli_fetch_array($querydoc)){  
$grn_new_no=$row['cno'];
}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~   End of sequence ~~~~~~~~~~~~~~~~~~



/////!!!!!!!!!!!!!!!!!!  Open grn_temp_header   !!!!!!!!!!!!!!!!!!!!!!!!!!!!
$query=mysqli_query($con," select * from grn_temp_header where grnd_no='$grn_no'  ")or die(mysqli_error($con));
$count=mysqli_num_rows($query);

if ($count>0)
{
	
	while($rowsp=mysqli_fetch_array($query)){
		$gdate=$rowsp['grnd_date'];
		$loc_id=$rowsp['grand_loc_id'];
		$note=$rowsp['refnote'];
		$supinv=$rowsp['invoice_no'];
	}

	
	   	/// !!!!!!!!!!!!!!!!!!!     GRN  item detail
	       $queryd=mysqli_query($con," select grn_temp_detail.*,ifnull(item_stocks.loc_qoh,0) as loc_qoh
from grn_temp_detail
left join grn_temp_header on grn_temp_detail.grnd_no=grn_temp_header.grnd_no
left join item_stocks on item_stocks.loc_id=grn_temp_header.grand_loc_id and item_stocks.item_id=grn_temp_detail.item_id where grn_temp_detail.grnd_no='$grn_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'];	
					$issue_qty=$rowd['issue_qty'];
					$costprice=$rowd['cost_price'];	
					$loc_qoh=$rowd['loc_qoh'];
					$se=$rowd['se'];
				    if ($issue_qty < 0) {
                        $tran = ($loc_qoh >= abs($issue_qty)) ? 1 : 0;
                    } elseif ($issue_qty > 0) {
                        $tran = 1;
                    }


/////!!!!!!!!!!!!!!!!!!  opening Item Matsre table   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$queryitem=mysqli_query($con,"select * from item_master where item_id=$item_id ")or die(mysqli_error());
while($rowitem=mysqli_fetch_array($queryitem)){  
$qoh=$rowitem['qoh'];
$cost_price=$rowitem['cost_price'];
}
///~~~~~~~~~~~~~~~~~~~~~~~~~~~   End of  Item Matsre table ~~~~~~~~~~~~~~~~~~

/////Fing weighted average cost
    $currentTotalCost = $cost_price * $qoh;
    $newTotalCost = $currentTotalCost + ($costprice * $issue_qty);
    $newQuantityOnHand = $qoh + $issue_qty;
   // $newAverageCost = $newTotalCost / $newQuantityOnHand;


if ($newQuantityOnHand == 0) {
            $newAverageCost = 0; // Set to 0 if no quantity remains.
        } else {
            $newAverageCost = $newTotalCost / $newQuantityOnHand;
        }




///////////////////////////
        //////////////////////location stock
//$queryitemst=mysqli_query($con,"select * from item_stocks where item_id=$item_id and loc_id= $loc_id ")or die(mysqli_error());
//while($rowitemst=mysqli_fetch_array($queryitemst)){  
//$qoh=$rowitemst['qoh'];
//$loc_qoh=$rowitemst['loc_qoh'];
//}



        ///////////////////////




//if ($issue_qty<>0 AND $tran==1){
if ($issue_qty != 0 && $tran == 1) {
		if ( mysqli_query($con,"INSERT INTO grn_detail(grn_no,item_id,issue_qty,cost_price,se) 
	        VALUES($grn_new_no,$item_id,$issue_qty,$costprice,$se )  ")or die(mysqli_error($con)))
	        {  
            $queryitem=mysqli_query($con," select * from item_stocks where item_id=$item_id and loc_id= $loc_id  ")or die(mysqli_error($con));
			$countitem=mysqli_num_rows($queryitem);
			
			if ($countitem>0)
			{
	        if ( mysqli_query($con,"update item_stocks set loc_qoh = loc_qoh + $issue_qty where item_id=$item_id and  loc_id='$loc_id' ")or die(mysqli_error($con)))
		        { }	
            }  //// 	if ($countitem>0)

             else {

            if ( mysqli_query($con,"INSERT INTO item_stocks(item_id,loc_id,loc_qoh) 
	        VALUES($item_id,$loc_id,$issue_qty )  ")or die(mysqli_error($con)))
	        {   }

        }   //// end of  else {


            if ( mysqli_query($con,"update item_master set cost_price = $newAverageCost , qoh=qoh +$issue_qty where item_id=$item_id  ")or die(mysqli_error($con)))
		        { }	
				///////////////////////end of stock update
	          }
	        //mysqli_begin_transaction($con);
	      } //if ($issue_qty<>0){
	        	
	       	}	///while

			} // end of if ($countd>0)
	     //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~end of item detail   	
			
	

	if ( mysqli_query($con,"INSERT INTO grn_header(grn_no,grn_date,gran_loc_id,refnote,invoice_no,userid,edate) 
		VALUES($grn_new_no,'$gdate',$loc_id,'$note','$supinv',$userid,'$edate' )  ")or die(mysqli_error($con)))
	        {

	if ( mysqli_query($con,"update sequence set cno =cno + 1  where seq_id=1  ")or die(mysqli_error($con)))			
						{   							
							
		if ( mysqli_query($con,"delete from grn_temp_header where grnd_no='$grn_no' ")or die(mysqli_error($con))) {					
			if ( mysqli_query($con,"delete from grn_temp_detail where grnd_no='$grn_no' ")or die(mysqli_error($con))) {	

							if (!mysqli_commit($con)) {
							    echo("Transaction commit failed\n");
							    exit();
							}
							else {
					//echo "<script>document.location='item_grn_pdf.php?grn_no=$grn_new_no '</script>";
echo "<script>window.open('item_grn_pdf.php?grn_no=$grn_new_no', '_blank');
window.location.href = 'home.php';
</script>";
 
							}
			}	//if ( mysqli_query($con,"delete from grn_temp_detail where grnd_no='$grn_no' ")or die(mysqli_error($con))) {				
			} //if ( mysqli_query($con,"delete from grn_temp_header where grnd_no='$grn_no' ")or die(mysqli_error($con))) {	



					} ///if ( mysqli_query($con,"update sequence set cno =cno + 1  where seq_id=1  ")or die(mysqli_error($con)))





	 		}  //~~~~~~~~~ end of if ( mysqli_query($con,"INSERT INTO grn_header(
	 		else {

	 			//mysqli_rollback($con);

	 		}

}///if ($count>1)
?>
<script>
        function printPage() {
        	//alert("Please enter the route you visited !!!"); 
           // window.print(); // This initiates the print dialog
       // http://localhost:81/officesync/pages/stock_req_print.php
url=' http://localhost:81/saleshub/pages/item_grn_pdf.php?grn_no=<?php echo $grn_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 = "item_grn.php";
            }, 500);
        } else {
            printWindow.print();
            printWindow.close();
            window.location.href = "item_grn.php";
        }
    }, true);



        }

window.onload = function() {

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