<?php 
ob_start();
session_start();
include "../inc/config.php";
include "../inc/session.php";


$awb_scan = trim($_POST['awb_scan']);
$type = 'cscs_awb';

// Convert input into an array (handle spaces and commas)
    $awb_numbers = preg_split('/[\s,]+/', $awb_scan);
$awb_numbers = array_map(function($awb) { return "'" . trim($awb) . "'"; }, $awb_numbers);
$awb_string = implode(", ", $awb_numbers);

$statement = $pdo->prepare("SELECT * FROM `pickup_entry` WHERE $type in ($awb_string)");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC); ?>


<div class="row" style="margin: 20px 0px;">
    <?php if($result){ ?>
        	        <?php foreach ($result as $row) { $pick_id = $row['id']; ?>
        	        <form class="form-horizontal" action="" method="post" id="pickupForm" enctype="multipart/form-data">
        	        <div class="row" style="margin: 2px 0px;">
                	        <div class="col-md-12" style="padding: 9px 5px;background: bisque;border-radius: 11px;">
                	            <b>AWB:</b> <b style="color: #fb8230;"><?php echo $row['cscs_awb']; ?>  </b>
                	            <b style="padding-left: 200px;">Status:</b> <span  style="color: #fb8230;" class="status-badge <?php echo strtolower($row['status']); ?>"><?php echo strtoupper($row['status']); ?></span>
                	        </div>
                	        <div class="col-md-6">
         <center><h5><b>Shipment Deatils</b></h5></center>
                                <div class="row">
            <div class="col-md-6">
                            <div class="row form-horizontal" style="margin: 0px 0px;">
                                <div class="form-group">
									<label for="" class="col-sm-6 control-label">Product Description : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
									    <input type="hidden" autocomplete="off" class="form-control input-sm" name="pickup_id" id="pickup_id" value="<?=$row['id']?>">
										<input type="text" autocomplete="off" class="form-control input-sm" name="product_description" id="product_description" value="<?=$row['product_description']?>"> </div>
								</div>
								<div class="form-group">
									<label for="" class="col-sm-6 control-label">Quantity : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="quantity" id="quantity" value="<?=$row['quantity']?>"> </div>
								</div>
								<div class="form-group">
									<label for="" class="col-sm-6 control-label">Taxable Value : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="taxable_value" id="taxable_value" value="<?=$row['taxable_value']?>"> </div>
								</div>
								<div class="form-group">
									<label for="" class="col-sm-6 control-label">Ewaybill : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="ewaybill" id="ewaybill" value="<?=$row['ewaybill']?>"> </div>
								</div>
								<div class="form-group">
									<label for="" class="col-sm-6 control-label">Order Id : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="document_number" id="document_number" value="<?=$row['document_number']?>"> </div>
								</div>
				            </div>				
            </div>
            <div class="col-md-6">
                            <div class="row form-horizontal" style="margin: 0px 0px;">
                                <div class="form-group">
									<label for="" class="col-sm-6 control-label">Total No.Of Boxes : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="boxes" id="boxes" value="<?=$row['boxes']?>" required> </div>
								</div>
								<div class="form-group">
									<label for="" class="col-sm-6 control-label">Actual Weight (Kg) : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="a_weight" id="a_weight" value="<?=$row['a_weight']?>" required> </div>
								</div>
								<div class="form-group">
									<label for="" class="col-sm-6 control-label">Charged Weight (Kg) : <span></span></label>
									<div class="col-sm-6" style="padding-right: 2px;padding-left: 2px;">
										<input type="text" autocomplete="off" class="form-control input-sm" name="c_weight" id="c_weight" value="<?=$row['c_weight']?>" required> </div>
								</div>
								
				            </div>				
            </div>
        </div>                    
                            
                	        </div>
                	        <div class="col-md-6">
                	            <!--<center><h5><b>Volumetrix Weight Deatils</b></h5></center>-->
                	                <table id="customers">
                                      <tbody><tr>
                                        <th>Length *</th>
                                        <th>Width *</th>
                                        <th>Height *</th>
                                        <th>No of Box</th>
                                        <th>Act WT</th>
                                        <th>Volumetric WT</th>
                                        <th></th>
                                      </tr>
                                      </tbody><tbody id="table_body_codition">
                                     <?php 
                                    $statement = $pdo->prepare("SELECT * FROM tbl_volumetrix_weight WHERE pickup_id=?");
                                    $statement->execute([$pick_id]);
                                    $trackingData = $statement->fetchAll(PDO::FETCH_ASSOC);
                                    $i = 1;
                                    foreach ($trackingData as $row) { ?>
                                          <tr class="remove_calculation">
                                            <td>
                                                <div hidden><input type="text" placeholder="Length" name="ids[]" id="ids" class="form-control input-sm ids" value="<?=$row['id']?>" ></div>
                                                <input type="text" placeholder="Length" name="length[]" id="length" class="form-control input-sm length" value="<?=$row['length']?>" onkeypress="return isNumberKey(this, event);" required=""></td>
                                            <td><input type="text" placeholder="Width" name="width[]" id="width" class="form-control input-sm width" value="<?=$row['width']?>" onkeypress="return isNumberKey(this, event);" required=""></td>
                                            <td><input type="text" placeholder="Height" name="height[]" id="height" class="form-control input-sm height" value="<?=$row['height']?>" onkeypress="return isNumberKey(this, event);" required=""></td>
                                            <td><input type="text" placeholder="No Of Box" name="no_of_box[]" id="no_of_box" class="form-control input-sm no_of_box" value="<?=$row['no_of_box']?>" onkeypress="return isNumberKey(this, event);" required=""></td>
                                            <td>
                                                <input type="text" placeholder="Actual Weight" name="actual_weight[]" id="actual_weight" class="form-control input-sm actual_weight" value="<?=$row['actual_weight']?>" onkeypress="return isNumberKey(this, event);">
                                            </td>
                                            <td>
                                                <input type="text" placeholder="Charged Weight" name="charged_weight[]" id="charged_weight" class="form-control input-sm charged_weight" value="<?=$row['charged_weight']?>" onkeypress="return isNumberKey(this, event);">
                                                <input type="hidden" placeholder="Charged Weight" name="final_total_charges[]" id="final_total_charges" class="form-control input-sm final_total_charges" value="<?=$row['fin_charges_weight']?>" onkeypress="return isNumberKey(this, event);">
                                            </td>
                                            <td>&nbsp;</td>
                                         </tr>
                                    <?php  } ?>
                                      
                                          
                                     </tbody>
                                    </table>
                                    <br><center><span id="add_new_volumentary" class="btn btn-warning btn-xs"><i class="fa fa-plus-circle"> Add New Row</i></span></center>
                            </div>
                    </div>
                    <br><center><button type="submit" id="submitBtn" class="btn btn-success btn-sm"><i class="fa fa-edit"></i> Update Volumetrix Details</button></center>
                    </form>
                    <hr style="border-style: dashed;">
                <?php } }else { echo '<center>NO data found..</center>';} ?>
</div>


<style>
#customers {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

 #customers th {
  border: 1px solid #ddd;
  padding: 3px;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {
  /*padding-top: 12px;
  padding-bottom: 12px;*/
  text-align: center;
  background-color: #232384;
  color: white;
}
.form-group {
    margin-bottom: 5px;
}
.length,.width,.height,.no_of_box,.actual_weight,.charged_weight{
        font-size: 14px;
    font-weight: 600;
    text-align: center;
}
</style>

<script>
    $('#add_new_volumentary').on('click', function() {
    html = ` <tr class="remove_calculation">
                <td><input type="text" placeholder="Length" name="length[]" id="length" class="form-control input-sm length" value="0" onkeypress="return isNumberKey(this, event);" required></td>
                <td><input type="text" placeholder="Width" name="width[]" id="width" class="form-control input-sm width" value="0" onkeypress="return isNumberKey(this, event);" required></td>
                <td><input type="text" placeholder="Height" name="height[]" id="height" class="form-control input-sm height" value="0" onkeypress="return isNumberKey(this, event);" required></td>
                <td><input type="text" placeholder="No Of Box" name="no_of_box[]" id="no_of_box" class="form-control input-sm no_of_box" value="1" onkeypress="return isNumberKey(this, event);" required></td>
                <td><input type="text" placeholder="Actual Weight" name="actual_weight[]" id="actual_weight" class="form-control input-sm actual_weight" value="0" onkeypress="return isNumberKey(this, event);"></td>
                <td>
                  <input type="text" placeholder="Charged Weight" name="charged_weight[]" id="charged_weight" class="form-control input-sm charged_weight" value="0" onkeypress="return isNumberKey(this, event);">
                  <input type="hidden" placeholder="Charged Weight" name="final_total_charges[]" id="final_total_charges" class="form-control input-sm final_total_charges" value="0" onkeypress="return isNumberKey(this, event);">
                </td>
                <td><center><span class="btn btn-danger btn-xs remove_product"><i class="bi bi-trash3"></i></span></center></td>
          </tr>`;
    $('#table_body_codition').append(html);
});



$(document).ready(function(){
        $('table#customers tbody').on('change keyup', 'tr.remove_calculation', function() {
            
            var tr = $(this).closest('tr');
            
            var entry_source = $('#pincode_mode').val();
            var surface_cal =$('#surface_cal').val()|| 5000;
            var air_cal = $('#air_cal').val()|| 5000;
            
            
           
        var length = tr.find('.length').val() || 0;
        var width = tr.find('.width').val() || 0;
        var height = tr.find('.height').val() || 0;
        var no_of_box = tr.find('.no_of_box').val() || 0;
        var actual_weight = tr.find('.actual_weight').val() || 0;
        
        if(entry_source == 'air'){
          var tot_lhw  = length*width*height*no_of_box;
          var charged_weight =   tot_lhw/air_cal || 0;
          
          if(actual_weight >charged_weight){
              
              var final_charged_weight  = actual_weight;
          }else{
              var final_charged_weight =   tot_lhw/air_cal;
          }
          tr.find('.charged_weight').val(charged_weight.toFixed(2));
          tr.find('.final_total_charges').val(final_charged_weight);
          
        }else{
          var tot_lhw  = length*width*height*no_of_box;
          var charged_weight =   tot_lhw/surface_cal;
          
          if(actual_weight >charged_weight){
              
              var final_charged_weight  = actual_weight;
          }else{
              var final_charged_weight =   tot_lhw/surface_cal;
          }
          
          tr.find('.charged_weight').val(charged_weight.toFixed(2));
          tr.find('.final_total_charges').val(final_charged_weight);
        }            final_calculation();
        });
    
 });
 
 
 function calculate_volu(){
    $('table#customers tbody tr').each(function() {
         var tr = $(this).closest('tr');
            
            var entry_source = $('#pincode_mode').val();
            var surface_cal =$('#surface_cal').val()|| 5000;
            var air_cal = $('#air_cal').val()|| 5000;
            
            
           
        var length = tr.find('.length').val() || 0;
        var width = tr.find('.width').val() || 0;
        var height = tr.find('.height').val() || 0;
        var no_of_box = tr.find('.no_of_box').val() || 0;
        var actual_weight = tr.find('.actual_weight').val() || 0;
        
        if(entry_source == 'air'){
          var tot_lhw  = length*width*height*no_of_box;
          var charged_weight =   tot_lhw/air_cal || 0;
          
          if(actual_weight >charged_weight){
              
              var final_charged_weight  = actual_weight;
          }else{
              var final_charged_weight =   tot_lhw/air_cal;
          }
          tr.find('.charged_weight').val(charged_weight.toFixed(2));
          tr.find('.final_total_charges').val(final_charged_weight);
          
        }else{
          var tot_lhw  = length*width*height*no_of_box;
          var charged_weight =   tot_lhw/surface_cal;
          
          if(actual_weight >charged_weight){
              
              var final_charged_weight  = actual_weight;
          }else{
              var final_charged_weight =   tot_lhw/surface_cal;
          }
          
          tr.find('.charged_weight').val(charged_weight.toFixed(2));
          tr.find('.final_total_charges').val(final_charged_weight);
        }         final_calculation();
    });
}
 
 
 function final_calculation(){
         var sum = 0;
         var sum1 = 0;
         var sum3 = 0;
            $(".final_total_charges").each(function(){
                sum += +$(this).val();
            });
            $(".actual_weight").each(function(){
                sum1 += +$(this).val();
            });
            $(".no_of_box").each(function(){
                sum3 += +$(this).val();
            });
            
            $("#c_weight").val(sum.toFixed(2));
            $("#a_weight").val(sum1.toFixed(2));
            $("#boxes").val(sum3);

}
$(document).on('click', '.remove_product', function() {
        $(this).closest('.remove_calculation').remove();
        final_calculation();
});




$(document).ready(function () {
    $("#pickupForm").on("submit", function (e) {
        e.preventDefault(); // Prevent default form submission
        
        let formData = new FormData(this);

        // Collect Volumetrix Data as an Array
        let volumetrixData = [];
        $(".remove_calculation").each(function () {
            let row = {
                ids: $(this).find(".ids").val() || 0,
                length: $(this).find(".length").val(),
                width: $(this).find(".width").val(),
                height: $(this).find(".height").val(),
                no_of_box: $(this).find(".no_of_box").val(),
                actual_weight: $(this).find(".actual_weight").val(),
                charged_weight: $(this).find(".charged_weight").val(),
                final_total_charges: $(this).find(".final_total_charges").val()
            };
            volumetrixData.push(row);
        });
        console.log(volumetrixData);
        // Append JSON-encoded Volumetrix Data
        formData.append("volumetrix_data", JSON.stringify(volumetrixData));

        $.ajax({
            url: "custom-api/volumetrix-update.php",  // Change to your actual API URL
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function () {
                $("#submitBtn").prop("disabled", true).text("Submitting...");
            },
            success: function (response) {
                let res = JSON.parse(response);
                if (res.status === "success") {
                    alert("Data updated successfully!");
                    location.reload(); // Reload page after success
                } else {
                    alert("Error: " + res.message);
                }
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error:", error);
                alert("Something went wrong. Please try again.");
            },
            complete: function () {
                $("#submitBtn").prop("disabled", false).text("Submit");
            }
        });
    });
});
</script>

