<?php
ob_start();
if(!isset($_SESSION)){ session_start(); } 
if(!isset($_SESSION['update_grn'])) { $_SESSION['update_grn'] = array(); } 
include 'load.php';
if(!isset($_GET['gid'])){
    header('Location: list-grn.php');
}
$gid = $_GET['gid'];
$grninfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM grn WHERE grn_no='$gid'"));
$cart_items = array();    	
$grniteminfo = mysqli_query($conn, "SELECT * FROM grn_item WHERE grn_no='$gid'");




if(isset($_POST['save']) || isset($_POST['print']))

{		

       
        $total = 0;

		

        $qnumber = $_POST['qnumber'];
        $supplier = $_POST['supplier'];
        $date = $_POST['date'];
        $alldiscount = $_POST['alldiscount'];
		$rdallownce = $_POST['rdallownce'];
        //$lastcharalldiscount = substr($alldiscount, -1);
        
       
        
        foreach ($_SESSION['update_grn'] as $key => $cart_item) {
            $pprice = 0;
            $productid = $cart_item['product_id'];
            $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
            $lastchar = substr($cart_item['discount'], -1); 
          //  if($lastchar=="%"){
                //$disrate = floatval(substr($cart_item['discount'], 0, -1));
                $dis =  ($cart_item['price']/100)*$cart_item['discount'];
                $pprice = $cart_item['price']-$dis;
           // }else{
           //     $pprice = $cart_item['price']-$cart_item['discount'];
               
          //  }
            $total = $total+($cart_item['quantity']*$pprice);
        }
     //  if($lastcharalldiscount=="%"){
                  //  $disrateall = floatval(substr($alldiscount, 0, -1));
                    $disall =  ($total/100)*$alldiscount;
                    $alldisprice = $total-$disall;
					$tmalldisprice = $alldisprice-$rdallownce;
                 //   }else{
                   //     $alldisprice = $total-$alldiscount;
                    
                  //  }


       // $sql = "INSERT INTO grn (grn_nomber, supplier, date,total, alldiscount,discountedtotal)
           // VALUES ('$qnumber', '$supplier', '$date', '$total','$alldiscount','$alldisprice')";
$sql = "UPDATE grn 
        SET supplier = '$supplier', 
            date = '$date', 
            total = '$total', 
            alldiscount = '$alldiscount', 
            discountedtotal = '$tmalldisprice',
			rdallownce = '$rdallownce'			
        WHERE grn_no  = '$gid'";
        

        if ($conn->query($sql) === TRUE) {
                $grniteminfo = mysqli_query($conn, "SELECT * FROM grn_item WHERE grn_no='$gid'");
                if ($grniteminfo->num_rows > 0) {
                    while($row = $grniteminfo->fetch_assoc()) {
                        $productid1 = $row['product_id'];
                        $qty1 = $row['qty'];
                        $sql4 = "UPDATE tbl_stock SET qty = qty - $qty1 WHERE prid='$productid1'";
                        $conn->query($sql4);
                    }
                }
            $sql5 = "DELETE FROM grn_item WHERE grn_no='$gid'";
              $conn->query($sql5);   
            $last_id = $gid;

            foreach ($_SESSION['update_grn'] as $key => $cart_item) {
                $productid = $cart_item['product_id'];
                $quantity = $cart_item['quantity'];
                $discount = $cart_item['discount'];
                $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
                $price = $cart_item['price'];
                 $lastchar = substr($cart_item['discount'], -1);
               // if($lastchar=="%"){
                    //$disrate = floatval(substr($cart_item['discount'], 0, -1));
                    $dis =  ($cart_item['price']/100)*$cart_item['discount'];
                    $pprice = $cart_item['price']-$dis;
                //    }else{
                 //      $pprice = $cart_item['price']-$cart_item['discount'];
                    
                  //  }
                $sql1 = "INSERT INTO grn_item (product_id, grn_no, qty,price, discount,discount_price)
                            VALUES ('$productid', '$last_id', '$quantity','$price','$discount','$pprice')";
                if ($conn->query($sql1) === TRUE) {
                    $sql3 = "UPDATE tbl_stock SET qty = qty + $quantity WHERE prid='$productid'";
                    $conn->query($sql3);
                    unset($_SESSION['update_grn']);
                   if(isset($_POST['print'])){
                         header("location: view-grn.php?gid=".$last_id);
                    }else{
                         header("location: list-grn.php");
                    }
                }

            }

        }
	}

    
        





?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="POS - Payroll | Pos & Invetory System | Dashboard
">
<meta name="keywords" content="Payroll | Pos & Invetory System | Dashboard
">
<meta name="author" content="Payroll | Pos & Invetory System | Dashboard
">
<meta name="robots" content="noindex, nofollow">

<title>Home | Payroll | Pos & Invetory System | Dashboard
</title>


<?php
require_once 'headercss.php';
?>
</head>
<body>
<div id="global-loader">
<div class="whirly-loader"> </div>
</div>

<div class="main-wrapper">
<?php
require_once 'header.php';
?>

<?php
require_once 'navbar.php';
?>

<div class="page-wrapper">
<div class="content">
<div class="page-header">
<div class="page-title">
<h4>Edit GRN</h4>
<h6>Update GRN</h6>
</div>
</div>


<div class="card">
<div class="card-body">










<form method="POST" enctype="multipart/form-data">
<?php

if(isset($errMSG)){

?>
									
<div class="alert alert-danger border-0 bg-danger alert-dismissible fade show py-2">
<div class="d-flex align-items-center">
<div class="font-35 text-white"><i class="bx bxs-message-square-x"></i>
</div>
<div class="ms-3">
<h6 class="mb-0 text-white">Error Alerts</h6>
<div class="text-white"> <?php echo $errMSG; ?>!</div>
</div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
									
<?php

}
	
else if(isset($successMSG)){

?>
									
<div class="alert alert-success border-0 bg-success alert-dismissible fade show py-2">
<div class="d-flex align-items-center">
<div class="font-35 text-white"><i class="bx bxs-check-circle"></i>
</div>
<div class="ms-3">
<h6 class="mb-0 text-white">Success Alerts</h6>
<div class="text-white"><?php echo $successMSG; ?>!</div>
</div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
									
<?php

}






?>
        <div class="row">
                <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>GRN Number</label>
                            <input type="text" class="form-control" name="qnumber" value="<?php echo $grninfo['grn_nomber']; ?>" required readonly>
                            
                        </div>

                </div>
                    <div class="col-lg-3 col-sm-3 col-12">
                        <div class="form-group">
                                <label>Supplier</label>
                                <select class="form-control" id="supplier" name="supplier">
                                    <option value="">Select Customer</option>
                                    <?php $customers = mysqli_query($conn, "SELECT * FROM mobilesuppliers"); 
                                    
                                        if ($customers->num_rows > 0) {
                                            while($row = $customers->fetch_assoc()) {
                                                $coid = $row['spid'];
                                                $cname = $row['spname']; 
                                                if($coid==$grninfo['supplier']){ ?>
                                                        <option value="<?php echo $coid; ?>" selected><?php  echo $cname; ?></option>
                                               <?php }else{ ?>
                                                    <option value="<?php echo $coid; ?>"><?php  echo $cname; ?></option>
                                               <?php } ?>
                                               
                                                   
                                          <?php 
 }
                                       }
                                    ?>
                                </select>
                        </div>
                    </div>
                    <div class="col-lg-3 col-sm-3 col-12">
                    <div class="form-group">
                            <label>Date</label>
                            <input type="date" class="form-control" name="date" required value="<?php echo $grninfo['date']; ?>">
                            
                        </div>
                    </div>
                        <div class="col-lg-3 col-sm-3 col-12">
                            <div class="form-group">
                                    <label>All Discount</label>
                                    <input type="text" class="form-control" name="alldiscount" required value="<?php echo $grninfo['alldiscount']; ?>"> 
                                    
                                </div>
                        
                </div>
               <div class="col-lg-3 col-sm-3 col-12">
                            <div class="form-group">
                                    <label>RD Allownce</label>
                                    <input type="text" class="form-control" name="rdallownce" required>
                                    
                                </div>
                        
                </div>
                
               
               
                
                

                <hr>
                
                
               
                <div class="col-lg-12">
                        <a href="#" class="btn btn-cancel">Cancel</a>
                        <button type="submit" name="save" class="btn btn-submit me-2">Save</button>
                        <button type="submit" name="print" class="btn btn-submit me-2 btn btn-primary">Print</button>
                </div>
        </div>
        </form>
        </div>
        </div>

        
        












<div class="card">
    <div class="card-header">
        <div class="page-title">
            <h6 style="color: #fff;padding: 10px;">Add Items</h6>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"></script>
<div class="card-body">
    <form method="POST" enctype="multipart/form-data" action="edit-add-grn-item-session.php">
    <div class="row">
        <div class="col-md-3">
                <div class="form-group">
                    <label>Product</label>
                    <select class="form-control select2" id="productlist" name="product" required>
                        <option value="">Select Product</option>
                        <?php $products = mysqli_query($conn, "SELECT * FROM mobileproducts"); 
                        
                            if ($products->num_rows > 0) {
                                while($row = $products->fetch_assoc()) {
                                    $productid = $row['prid'];
                                    $productname = $row['proname']; ?>
                                    
                                        <option value="<?php echo $productid; ?>"><?php echo $productname; ?></option>
                                  
                              <?php  }
                            }
                        ?>
                    </select>
                    </div>
        </div>
        
            <div class="col-md-3">
                    <div class="form-group">
                        <label>Qty</label>
                        <input type="number" name="quntity" class="form-control" id="qty" placeholder="" required>
                    </div>
            </div>
            
            
            <div class="col-md-3">
                    <div class="form-group">
                        <label>Discount</label>
                        <input type="text" class="form-control" id="discount" name="discount" placeholder="" value="0">
                    </div>
            </div>
            <div class="col-md-3">
                    <div class="form-group">
                        <label>Price</label>
                        <input type="text" class="form-control" id="price" name="price" placeholder="" required>
                    </div>
            </div>
            <div class="col-md-12 mb-4">
                    <button type="submit" class="btn btn-submit me-2">Add</button>
                    
                        </form>
            </div>

    </div>
    <table class="table">
  <thead class="thead-dark">
    <tr>
      
      <th scope="col">Product</th>
      <th scope="col">Quantity</th>
      
       <th scope="col">Discount</th>
       <th scope="col">Rate</th>
      <th scope="col">Amount</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <?php 
     $tot = 0;
    if(isset($_SESSION['update_grn'])){ 
       
        foreach ($_SESSION['update_grn'] as $key => $cart_item) {	
            $amount = 0;
            $productid = $cart_item['product_id'];
            $productinfo = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE prid='$productid'"));
            ?>
         <tr>
            <td><?php echo $productinfo['proname']; ?></td>
            <td><?php echo $cart_item['quantity']; ?></td>
            <td><?php echo $cart_item['discount']; ?></td>
            <td>Rs.<?php echo $cart_item['price']; ?></td>
            
            <?php 
            $lastchar = substr($cart_item['discount'], -1); 
          //  if($lastchar=="%"){
               // $disrate = floatval(substr($cart_item['discount'], 0, -1));
                $dis =  ($cart_item['price']/100)*$cart_item['discount'];
                $pprice = (float)$cart_item['price']-(float)$dis;
          //  }else{
           //     $pprice = (float)$cart_item['price']-(float)$cart_item['discount'];
               
           // }
            ?>
            <td>Rs.<?php echo $cart_item['quantity']*$pprice; 
            $tot = $tot + $cart_item['quantity']*$pprice;
            
            ?></td>
            <td><i style="cursor:pointer;" id="<?php echo $key; ?>" class="fa fa-trash delete"></i></td>
        </tr>
      <?php }

    } ?>
   
  
  </tbody>
   <tfoot>
    <tr>
        <td></td>
        <td></td>
        
      <td><strong>Total</strong></td>
      <td><strong></strong></td>
      <td><strong>Rs.<?php echo $tot; ?></strong></td>
    </tr>
  </tfoot>
</table>
</div>
</div>




</div>
        </div>
 </div>


<script src="assets/js/jquery-3.6.0.min.js"></script>

<script src="assets/js/feather.min.js"></script>

<script src="assets/js/jquery.slimscroll.min.js"></script>

<script src="assets/js/jquery.dataTables.min.js"></script>
<script src="assets/js/dataTables.bootstrap4.min.js"></script>

<script src="assets/js/bootstrap.bundle.min.js"></script>

<script src="assets/plugins/select2/js/select2.min.js"></script>

<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
<script src="assets/plugins/sweetalert/sweetalerts.min.js"></script>

<script src="assets/js/script.js"></script>

<script>
$(document).ready(function(){
   

    $('.delete').on('click', function() {
        var key = $(this).attr('id');
        $.ajax({
           type: "POST",
           data: {key:key},
           url: "delete-edit-grn-item.php",
           success: function(data){
            location.reload();
           }
        });
    });

    
      $(".select2").select2({
          
      });
});




</script>


</body>
</html>