<?php include('common/header.php'); ?>
  <!-- Main Sidebar Container -->
<?php include('common/sidenav.php'); ?>


<!--For save data-->
<?php  include_once ('includes/config.php'); ?>

<?php
 include_once ('includes/config.php');
   
// Check connection
    if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
    } 

if(isset($_POST['submit']))
{
 







   
//insert.php
//order details
$order_num =$_POST['order_num'];
$del_date=$_POST['del_date'];

$vendor =$_POST['vendor'];
$vehicle =$_POST['vehicle'];
$item =$_POST["item"];
$qty =$_POST["qty"];
$vmeasurement = $_POST['vmeasurement'];
$vendorem=$_POST["totalvmeaurement"];
$actual_price =$_POST["actual_price"];
$total = $_POST['total'];
$slipno =$_POST["slipno"];
$diesel =$_POST["diesel"];
$cost =$_POST["cost"];
$vehm =$_POST["vehm"];
$tax = $_POST["tax"];
$amcost = $_POST['amcost'];

$dstatus = $_POST["status"];


 // Check connection
    if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
    } 
  else
  
  

  
 $id = $_GET['id'];
  
  
  //order add
      
   /* if($amcost >= $total)
    {
        echo"<script type='text/javascript'>alert('Cost Should be Less than or equal to Total.');</script>";
      echo "<script>(window.location.href='shipmentedit.php?id=$id');</script>";
    }
     else{*/
     $query = "Update `shipment` SET `s_date`='".$del_date."',`material_id`='".$item."',`vendor_id`='".$vendor."',`qty`='".$qty."',`measure_id`='".$vehicle."',`vmeasurement`='".$vmeasurement."',
     `measurement_total`='".$vendorem."',
     `s_rate`='".$actual_price."',
     `ship_total`='".$total."',
     `slip_no`='".$slipno."',
     `s_diesel`='".$diesel."',
     `material_cost`='".$cost."',
     `veh_maintaince`='".$vehm."',
     `tax_driver_exp`='".$tax."',s_status='".$dstatus."',`allmcost_total`='".$amcost."' WHERE sh_id='$id'";
     //order add
     $resnew = mysqli_query($con, $query);
    // }
    
    
    
       
   echo "<div class='container'><div class='custom-alert'>Record Successfully Added!</div></div>";
        echo "<script>setTimeout(function() { window.location.href='shipment.php'; }, 1000);</script>";
        exit(); // Prevent the rest of the code from executing
$con->close();
      
       
}

 ?>
 
 


 <?php
//vendor
include('includes/config.php');
$v = '';

$query = "SELECT * FROM `vendors` where vs_status='0' ORDER BY company_name ASC";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
 $v .= '<option value="'.$row["company_name"].'">'.$row["company_name"].' </option>';
}
?>

 <?php
//vehicle
include('includes/config.php');
$c = '';

$query = "SELECT * FROM `vehicles` ORDER BY vname ASC";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
 $c .= '<option value="'.$row["vname"].'">'.$row["vname"].' </option>';
}
?>


 <?php

//material 

include('includes/config.php');
$it = '';

$query = "SELECT * FROM `materials` where item_status!=2 ORDER BY m_name ASC";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
 $it .= '<option value="'.$row["m_name"].'">'.$row["m_name"].'</option>';
}
?>
  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
  

    <!-- Content Header (Page header) -->
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1>All Shipment</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="shipment.php">Dataview</a></li>
             
             <li class="breadcrumb-item active"><a href="dashboard.php">Dashboard</a></li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-12">


            <div class="card">
              <div class="card-header">
       
                <h3 class="card-title">Edit Shipment</h3>
              </div>
        
              <!-- /.card-header -->
              <div class="card-body">
          
                     <form method="post" id="cart">     
     <h4></h4>
       <?php
          
          $id =$_GET['id'];
    include('includes/config.php');
      $no=0;
      $results = mysqli_query($con, "SELECT * FROM `shipment` as s 
 WHERE s.sh_id='$id' ORDER BY s.sh_id ASC");
       while($row = mysqli_fetch_assoc($results)) {
       $no++;
       $vehiclename = $row['measure_id'];
       $vendorss = $row['vendor_id'];
          
  ?>        
               <div class="row">
                 <div class="col-md-3">
               <div class="form-group">
                 <label>Measurement Num#</label>
                 <input type="number" class="form-control" name="order_num" readonly value="<?php echo $row['order_num']; ?>">
                 
                 </div>
              </div>
              
                   
            
                  
                   
                      
                      <div class="col-md-3">
               <div class="form-group">
                 <label>Shipment Status </label>
                <select required="required"  class="form-control action" id="status" name="status">
                                    <option value="<?php echo $row['s_status']; ?>">Selected <?php $status = $row['s_status']; ?>
                                    <?php if($status ==1) { ?>
                                     Delivered
                                    <?php } elseif($status ==0) { ?>
                                     Pending
                                    <?php } ?>
                                    </option>
                                    <option value="0">Pending</option>
                                    <option value="1">Delivered</option>
                            </select>
                 
                 </div>
              </div>
                  
                    <div class="col-md-3">
                        <div class="form-group">
                              <label>Date</label>
                               <input type="date" id="date_picker" required="required" class="form-control" name="del_date" value="<?php echo $row['s_date']; ?>">
                        
                    </div>
                    </div>
                    
                     
                  
                  
                </div>
                
    <!-- <script language="javascript">
        var today = new Date();
        var dd = String(today.getDate()).padStart(2, '0');
        var mm = String(today.getMonth() + 1).padStart(2, '0');
        var yyyy = today.getFullYear();

        today = yyyy + '-' + mm + '-' + dd;
        $('#date_picker').attr('min',today);
    </script>-->    
                <!--purchase  -->
                <div class="row">
    <div class="col-md-12">
        
      <table class="table table-condensed table-responsive-stack" id="tab_logic">
        <thead>
          <tr >
            <th> # </th>
         
            <th style="width:10%;" class="text-center">Item</th>
             <th style="width:10%;" class="text-center"> Vendor</th>
             <th style="width:10%;" class="text-center"> Vehicle</th>
            <th class="text-center"> Qty </th>
            <th class="text-center">Measure </th>
              <th style="width:8%;" class="text-center">Price </th>
           <th class="text-center"> Amount </th>
           <th class="text-center">SpNo.</th>
           <th class="text-center">Diesel</th>
           <th class="text-center">MCost</th>
           <th class="text-center">VehM</th>
            <th class="text-center">Tax/D-Exp/O-Exp</th>
            <th hidden class="text-center">All Cost</th>
           </tr>
        </thead>
         <tbody>
         <tr id='addr0'>
            <td>1</td>
            <td ><select  onchange="autocal()"  required="required" class="form-control selectpicker actionp"  data-live-search="true" id="product_name" name="item">
                  <option value="<?php echo $row['material_id']; ?>"> <?php echo $row['material_id']; ?></option>
                  <?php echo $it; ?>
                  </select>
                 
                  </td>
                    <td ><select  required="required" class="form-control selectpicker actionv"  data-live-search="true" id="vendor" name="vendor">
                   <option value="<?php echo $row['vendor_id']; ?>"><?php echo $row['vendor_id']; ?></option>
                
                  <?php echo $v; ?>
                  </select>
                 
                  </td>
                  <td>
                       <select  required="required"  class="form-control actionv" id="vehicle" name="vehicle">
                                    <option value="<?php echo $row['measure_id']; ?>"><?php echo $row['measure_id']; ?></option>
                                   
                            </select>
                  </td>
        
        
          
            <td ><input st type="number" name='qty' required placeholder='Enter Qty' class="form-control text-center qty" step="0" min="0" value="<?php echo $row['qty']; ?>">
          <!--<input type="number" hidden name='bal_qty[]' placeholder='Enter Qty' class="form-control bal_qty" step="0" min="0" />-->
            </td>
           
             <td >
                  <?php
          
    include('includes/config.php');
      
      $resultsvm = mysqli_query($con, "SELECT * FROM `measurements` WHERE vehicle_id='$vehiclename' AND vendor_id='$vendorss' ");
       while($rowvm = mysqli_fetch_assoc($resultsvm)) {
           
          
        
  ?>        
              <select  hidden required="required" id="vmeasurement" name="vmeasurement" class="form-control actionv vmeasurement">
                    <option value="<?php echo $rowvm['vmeasurement']; ?>"><?php echo $rowvm['vmeasurement']; ?></option>
                  </select>
                    <?php } ?>
                  <input type="number" readonly name="totalvmeaurement" id="totalvmeaurement" class="form-control text-center totalvmeaurement" value="<?php echo $row['measurement_total'];  ?>">
                
             </td>
             <td >
                  <select readonly required="required" id="actual_price" name="actual_price" class="form-control actual_price">
                  <option value="<?php echo $row['s_rate']; ?>"> <?php echo $row['s_rate']; ?></option>
                  </select>
             </td>
               <td ><input type="number" name='total' required="required" placeholder='0.00' class="form-control text-center total" readonly value="<?php echo $row['ship_total']; ?>"/></td>
            
              <td><input type="text" name='slipno' required="required" placeholder='Enter No' class="form-control text-center no" step="0" min="0" value="<?php echo $row['slip_no']; ?>"/></td>
             
             <td ><input type="number" name='diesel' required="required" placeholder='Enter Expense' class="form-control diesel" step="0" min="0" value="<?php echo $row['s_diesel']; ?>"></td>
             
             <td ><input type="number" name='cost' required="required" placeholder='Enter Cost' class="form-control cost" step="0" min="0" value="<?php echo $row['material_cost']; ?>"></td>
             
             
              <td ><input type="number" name='vehm' required="required" placeholder='Enter Cost' class="form-control vehm" step="0" min="0" value="<?php echo $row['veh_maintaince']; ?>"></td>
             
               <td ><input type="number" name='tax' required="required" placeholder='Enter Driver/Expense/Tax' class="form-control tax" step="0" min="0" value="<?php echo $row['tax_driver_exp']; ?>"></td>
                <td hidden><input type="number" readonly name='amcost' placeholder='All Cost' class="form-control amcost" step="0" min="0" value="<?php echo $row['allmcost_total']; ?>"></td> 
            
          
          </tr>
          <tr id='addr1'></tr>
        </tbody>
      </table>
       <?php } ?>
      
    </div>
  </div>
<!--<div  class="row clearfix">
    <div class="col-md-12">
      <button id="add_row" onclick="return false;" class="btn btn-danger pull-left"><i class="fa fa-plus"></i></button>
      <button id='delete_row' style="margin-left:1%;" onclick="return false;" class="btn btn-danger"><i class="fa fa-minus"></i></button>
    </div>
  </div>-->
  <div  class="row clearfix" style="margin-top:20px">
      <div class="col-md-4"></div>
      <div class="col-md-4"></div>
    <div class="pull-right col-md-4">
      <table style="display:none;" class="table table-striped table-hover " id="tab_logic_total">
        <tbody>
          <tr>
            <th class="text-center">Sub Total</th>
            <td class="text-center"><input type="number" name='sub_total' placeholder='0.00' class="form-control" id="sub_total" readonly/></td>
          </tr>
          <tr style="display:none;">
            <th class="text-center">Previous Total Amount</th>
            <td class="text-center"><select readonly style="width: 100%;" required="required" class="form-control action2" id="amount" name="amount">
                  <option>Select Amount</option>
                  </select></td>
          </tr>
           <tr>
            <th class="text-center">Previous Balance</th>
            <td class="text-center"><select readonly style="width: 100%;" required="required" class="form-control action2" id="balance" name="balance">
                  <option>Select Amount</option>
                  </select></td>
          </tr>
        <!--  <tr>
            <th class="text-center">Tax</th>
            <td class="text-center"><div class="input-group mb-2 mb-sm-0">
                <input type="number" class="form-control" id="tax" placeholder="0">
                <div class="input-group-addon">%</div>
              </div></td>
          </tr>
          <tr>
            <th class="text-center">Tax Amount</th>
            <td class="text-center"><input type="number" name='tax_amount' id="tax_amount" placeholder='0.00' class="form-control" readonly/></td>
          </tr>-->
          <tr style="display:none;">
            <th class="text-center">New Account Total</th>
            <td class="text-center"><input type="number" name='total_amount' id="total_amount" placeholder='0.00' class="form-control" readonly/></td>
          </tr>
           <tr>
            <!--<th class="text-center">Old Heading New Balance</th>-->
            <th class="text-center">Net Amount</th>
            <td class="text-center"><input type="number" name='balance_total_amount' id="balance_total_amount" placeholder='0.00' class="form-control" readonly/></td>
          </tr>
           <tr style="display:none;">
            <th class="text-center">All qty</th>
            <td class="text-center"><input type="number" name='all_itemqty' placeholder='0' step="0" min="0" class="form-control" id="all_itemqty" readonly/></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
                <!--purchase -->
                
<?php $role = $_SESSION['sess_role']; 
$user = $_SESSION['sess_user']; 
$user_id = $_SESSION['sess_user_id'];
$userbranch =$_SESSION['sess_branch'];
?>          
          
          
         
          
                
                
                

                <div class="row">
                  <div class="col-md-6">
                      <div class="form-group">
                           
                      <div class="form-example-int mg-t-15">
                            <button name="submit" class="btn btn-danger notika-btn-success">Submit</button>
                        </div>
                     
                  </div>
                </div>
                </div>
           </form>
                
                
                
                
                
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <!-- /.col -->
        </div>
        <!-- /.row -->
      </div>
      <!-- /.container-fluid -->
    </section>
    <!-- /.content -->



<script>
  //show a confirmation and redirect to the delete profile script
  function deleteProfile() {
    if (confirm("Do you really want to delete your profile?")) {
        //location.href = '/deleteuser.php';
    }
}
</script>


<script>
    //table row get
    
    
$(document).ready(function(){
$(document).on('change','.actionp',function(){
//    var row = $(this).closest('tr');
  var currow = $(this);
  if($(this).val() != '')
  {
   var actionp = $(this).attr("id");
   var query = $(this).val();
   var result = '';
   if (actionp == "product_name")
   {
      result ='actual_price';
      
   }
   
   $.ajax({
    url:"fetchitemprice.php",
    method:"POST",
    data:{actionp:actionp, query:query},
    success:function(data){
   
    
    
       currow.parent().next().next().next().next().next().children().html(data);
      
    }
   })
   
  

   
   
   
   
   
  }
});

    //vendor measurement
 
$(document).on('change','.actionv',function(){
    var currow2 = $(this);
    if($(this).val() != '')
    {
        var actionv = $(this).attr("id");
        var query = $(this).val();
        var vendor = $("#vendor").val(); // Assuming you have an element with id 'vendor' to get the selected vendor value
        
        $.ajax({
            url:"fetchvmeasurement.php",
            method:"POST",
            data:{actionv:actionv, query:query, vendor:vendor}, // Include the selected vendor
            success:function(data){
                if (actionv == "vendor") {
                    currow2.parent().next().children().html(data);
                } else if (actionv == "vehicle") {
                    currow2.parent().next().next().children().html(data);
                }
            }
        });
    }
});




});
    
    //table row get 
    
    






</script>


<script type="text/javascript">
$(document).ready(function autocal(){
    
    var i=1;
    $("#add_row").click(function(){b=i-1;
        $('#addr'+i).html($('#addr'+b).html()).find('td:first-child').html(i+1);
        $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
        i++; 
    });
    $("#delete_row").click(function(){
      if(i>1){
    $("#addr"+(i-1)).html('');
    i--;
    }
    calc();
  });
  
  $('#tab_logic tbody').on('keyup change',function(){
    calc();
  });
  $('#tax').on('keyup change',function(){
    calc_total();
  });
  

});

function calc()
{
  $('#tab_logic tbody tr').each(function(i, element) {
    var html = $(this).html();
    if(html!='')
    {
      /*var qty = $(this).find('.qty').val();
      var price = $(this).find('.price').val();
      $(this).find('.total').val(qty*price);
      */
      
    /*  var actual_price = $(this).find('.actual_price').val();
      var discount =$(this).find('.discount').val();
      $(this).find('.price').val(actual_price-discount);
      */
      
      
     
      
      //vehicle measurement cal
      var qty = $(this).find('.qty').val();
      var measurements = $(this).find('.vmeasurement').val();
      $(this).find('.totalvmeaurement').val(qty*measurements);
    
    
      //vendor cal
      var rate = $(this).find('.actual_price').val();
      var totalvmeaurements = $(this).find('.totalvmeaurement').val();
       $(this).find('.total').val(rate*totalvmeaurements);
    
    //all cost readonly cal
       var diesels = parseFloat($(this).find(".diesel").val());
       var costs = parseFloat($(this).find(".cost").val());
       var vehm = parseFloat($(this).find(".vehm").val());
       var tax = parseFloat($(this).find(".tax").val());
       var amcost = diesels+costs+vehm+tax;
        $(this).find(".amcost").val(isNaN(amcost) ? "" : amcost);
        
     
    
      calc_total();
    
    }
    });
}

function calc_total()
{
  after_discount_total=0;
  qty =0;
  $('.after_discount_total').each(function() {
        after_discount_total += parseInt($(this).val());
    });
  $('#sub_total').val(after_discount_total.toFixed(2));
  tax_sum=after_discount_total/100*$('#tax').val();
  $('#tax_amount').val(tax_sum.toFixed(2));
  $('#total_amount').val((tax_sum+after_discount_total).toFixed(2));
  
  
 

  
}








</script>


  </div>
  <!-- /.content-wrapper -->


<?php include('common/footer.php'); ?>