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

<?php 
if(isset($_GET['id'])){
    $ids = $_GET['id'];
    
    $statements = $pdo->prepare("SELECT * FROM manifest WHERE id=?");
    $statements->execute(array($_REQUEST['id']));
    $resultss = $statements->fetchAll(PDO::FETCH_ASSOC);
    $totalss = $statements->rowCount();
    
    if($totalss>0){
        $origin_branch = $resultss[0]['origin'];
        $destination_branch = $resultss[0]['destination'];
        $vehicle_no = $resultss[0]['vehicle_no'];
        $driver_name = $resultss[0]['driver_name'];
        $driver_mobile_no = $resultss[0]['driver_mobile_no'];
        $pickup_entry_ids = $resultss[0]['ids'];
        $incoming_ids = $resultss[0]['incoming_ids'] ?? 0;
    }

}

?>



<section class="content-header" style="padding: 8px 15px 8px 15px;">
    <div class='box-body' style="margin: 0px 0px;box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;background-color: white;">
    <div class="row" style="padding-left: 10px;padding-right: 10px;">
    			<div class="col-md-6" id="awb-scan">
    			    <input type="hidden" name="manifest_id" id="manifest_id" value="<?=$ids?>"/>
    			    <div class="search-box">
    			        <label>Scan AWB Number</label>
    				<input placeholder="Scan Awb Number here" type="text" class="form-control" name="awb_scan" id="awb_scan" style="border-radius: 20px;background: cornsilk;"> 
    				<div class="result" style="overflow-y: scroll;max-height: 267px;top: 56%;margin-left: 8%;width: 90%;margin-top:8%;"></div>
    				</div>
    			</div>
    			<div class="col-md-6" style="text-align: right;"> 
        		    <a href="shipment-create.php" class="btn btn-success btn-sm" style="cursor: pointer;"><i class="fa fa-plus"></i> Create Shipment</a>
        		    <a href="booking-list.php" class="btn btn-primary btn-sm"><i class="fa fa-arrow-left"></i> Back to Shipment List</a>
        		</div>
    </div>
    <div class="row" style="padding-left: 10px;padding-right: 10px;margin-top:10px;">
    		<div class="col-md-2">
                <label>Incoming Branch</label>
            		<select class="form-control select2" name="to_branch" id="to_branch">
            	        <?php
            	        $condi='';
            	        
            	        if($session['id']!=1 && $session_branch_ids!='0'){
                            $condi.= " and id IN ($session_branch_ids)";
                        }
                        
                        error_log("SELECT * FROM `tbl_branch` where status='1' and id=$destination_branch $condi");
                        
            			$statement = $pdo->prepare("SELECT * FROM `tbl_branch` where status='1' and id=? $condi");
            			$statement->execute(array($destination_branch));
            			$result = $statement->fetchAll(PDO::FETCH_ASSOC);	
            			foreach ($result as $row) { ?>
            				<option value="<?=$row['id']?>" <?php if($destination_branch==$row['id']){ echo "selected";}?>><?php echo $row['name']; ?></option>
            			<?php } ?>
            	    </select>
			</div>
		
			
			<div class="col-md-2">
                <label>Vehicle No</label>
            		<input type="text" class="form-control" placeholder="Vehicle No" name="vehicle_no" id="vehicle_no" value="<?=$vehicle_no?>" readonly/>
			</div>
			<div class="col-md-2">
                <label>Driver Name</label>
            		<input type="text" class="form-control" placeholder="Driver Name" name="driver_name" id="driver_name" value="<?=$driver_name?>" readonly/>
			</div>
			<div class="col-md-2">
                <label>Mobile No</label>
            		<input type="text" class="form-control" placeholder="Driver Mobile No" name="driver_mobile" id="driver_mobile" value="<?=$driver_mobile_no?>" readonly/>
			</div>
    </div>
   </div> 
    
    
  <div class='box-body' style="margin: 0px 0px;box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;background-color: white;margin: 10px 0px;">  
    <div class="box-body table-responsive">
						<table id="scaned_table_data" class="table table-bordered table-striped" style="font-size: 12px;">
							<thead>
								<tr>
									<th style="text-align: center;">#</th>
									<th style="min-width:100px;">AWB Number</th>
									<th  style="text-align: center;">No.Of Box</th>
									<th>Date Added</th>
									<th>Status</th>
									<th style="text-align: center;">Weight</th>
									<th>Client Name</th>
									<th>Consignor</th>
									<th>Consignee</th>
									<th>Origin (State=>City->Pincode)</th>
									<th>Destination (State=>City->Pincode)</th>
								</tr>
							</thead>
							<tbody id="scaned_table_data_body">
						<?php if(isset($_GET['id'])){
	$statementt = $pdo->prepare("SELECT * FROM pickup_entry where id IN ($incoming_ids)");
	//error_log("SELECT * FROM pickup_entry where id IN ($pickup_entry_ids)");
    $statementt->execute();
    $_datas = $statementt->fetchAll(PDO::FETCH_ASSOC);
    $totalDatas = $statementt->rowCount();
    $conditions="1=1";
    
    
    if($totalDatas>0){
        
        $data='';
        $destin='';   
            foreach($_datas as $d){
                echo "<tr id='pic_".$d['id']."'>
    				    <td class='delete' style='text-align:center;' onclick='remove(".$d['id'].")' ><i class='fa fa-trash'></i></td>
    				    <td><i class='fa fa-barcode' style='font-size:12px;color:blue'></i><b style='font-weight:800;'> ".$d['cscs_awb']."</b></td>
    				    <td><i class='fa fa-dropbox'></i> <span class='no_of_box'>".$d['boxes']."</span></td><td>".date("d-m-Y", strtotime($d['created_at']))."</td>
    				    <td>".strtoupper($d['status'])."</td>
    				    <td><span class='a_wt'>".$d['a_weight']."</a></td>
    				    <td>".$d['client_id']."</td>
    				    <td>".$d['shipper_name']."</td>
    				    <td><b style='font-weight:800;'>".$d['consignee_name']."</b></td>
    				    <td>".$d['shipper_state']." => ".$d['shipper_city']." - ".$d['shipper_pincode'].".</td>
    				    <td>".$d['consignee_state']." => ".$d['consignee_city']." - ".$d['consignee_pincode'].".</td>
    				</tr>";
    					$destin=$d['consignee_city'];
            }
	    }
	}
    ?>   
							</tbody>
						</table>
	</div>
	</div>
	
	
	
	
	<div class='box-body' style="margin: 0px 0px;box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;background-color: white;">  
    <div class="row" style="padding-left: 10px;padding-right: 10px;">
    		<div class="col-md-2">
				     <label>Status Date</label>
			     <input type="date" class="form-control" name="status_date" id="status_date" value="<?=date("Y-m-d")?>" />
			</div>
			<div class="col-md-3">
                <label>Status</label>
            		<select class="form-control select2" name="update_status" id="update_status">
            	        <?php
            			$statement = $pdo->prepare("SELECT * FROM `tbl_status` where status='1'");
            			$statement->execute();
            			$result = $statement->fetchAll(PDO::FETCH_ASSOC);	
            			foreach ($result as $row) { ?>
            				<option value="<?=$row['id']?>" <?= ($row['id']==3) ? "selected":"" ?>><?=$row['name']; ?></option>
            			<?php } ?>
            	    </select>
			</div>
			<div class="col-md-2">
                <label>Status Update Location</label>
            		<select class="form-control select2" name="status_location" id="status_location">
            	        <?php
            			$statement = $pdo->prepare("SELECT * FROM `tbl_branch` where status='1' and id=?");
            			$statement->execute(array($destination_branch));
            			$result = $statement->fetchAll(PDO::FETCH_ASSOC);	
            			foreach ($result as $row) { ?>
            				<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
            			<?php } ?>
            	    </select>
			</div>
			
			<div class="col-md-3">
			    <label>Status Description</label>
			    <select class="form-control select2" name="status_description" id="status_description">
            	        <?php
            			$statement = $pdo->prepare("SELECT * FROM `tbl_reason` where status='1'");
            			$statement->execute();
            			$result = $statement->fetchAll(PDO::FETCH_ASSOC);	
            			foreach ($result as $row) { ?>
            				<option value="<?php echo $row['reason']; ?>" <?= ($row['reason']=="SHIPMENT RECEIVED AT") ? "selected":"" ?>><?php echo $row['reason']; ?></option>
            			<?php } ?>
            	    </select>
			</div>
			<div class="col-md-1">
			    <label>Action</label><br>
					<button id='btn_submit' class="btn btn-success btn-sm"><i id="update_fa" class="fa fa-paper-plane"></i> Update Status</span> </button>
			</div>
    </div>
 </div> 
    
</section>

<div class="modal fade" id="print_confirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <center><h4 class="modal-title" id="success_title">Manifest Created Successfully</h4></center>
            </div>
            <div class="modal-body" id="modal-body">
                <center>
                    <a href="incoming-manifest.php" class="btn btn-warning btn-sm"><i class="fa fa-plus"></i> Create New In Coming Going Manifest</a>
                    <a class="btn btn-success btn-sm" target="_blank" id="btn_print"><i class="fa fa-print"></i> Print Manifest Copy </a>
                    <a href="incoming-manifest-list.php" class="btn btn-primary btn-sm"><i class="fa fa-arrow-left"></i> Back to Manifest List</a>
                </center>
            </div>
        </div>
    </div>
</div>
 <style>
        .modal-dialog {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh; 
        }
    </style>


<?php require_once('footer.php'); ?>

<script>
	$(document).ready(function() { 
	    var sound = document.getElementById("scanned_sound"); 
        sound.play(); 
	});
</script>
<audio id="scanned_sound">
  <source src="sound/sound.mp3" type="audio/mpeg">
</audio>
<audio id="scanned_wrong_sound">
  <source src="sound/wrong-sound.mp3" type="audio/mpeg">
</audio>


<script>
const array = [];
const awb_array = [];
    $(document).ready(function(){
        $('#awb_scan').on("keyup", function(e){
       
        if(e.keyCode!=17 && e.keyCode==13){
                var search_text = $(this).val();
                var resultDropdown = $(this).siblings(".result");
               
                if(search_text.length>1){
                    
                    $.get("custom-api/awb-search-api.php", {search_text: search_text}).done(function(data){
                        resultDropdown.html(data);
                        //console.log('ganesan:'+data);
                        if(data==''){
                            var ds='<div><center style="padding:10px;color:red;"> No Data Found...</center><div>';
                            resultDropdown.html(ds);
                            var sound = document.getElementById("scanned_wrong_sound"); 
                            $('.search-box input[type="text"]').select();
                            sound.play();
                        }else{
                            var numItems = $('.drop-down-awb').length;
                            if(numItems==1 && e.keyCode==13){
                                var ids=parseInt($('.drop-down-awb').attr('awb_id'));
                                if(!array.includes(ids)){
                                    product_selection(ids);
                                }else{
                                    $('.search-box input[type="text"]').focus();
                                    $('.search-box input[type="text"]').select();
                                    var ds='<div><center style="padding:10px;color:black;"> This AWB Number Already <b style="color:yellow"> Added </b></center><div>';
                                    $(".result").html(ds);
                                    var sound = document.getElementById("scanned_wrong_sound"); 
                                    sound.play();
                                }
                            } 
                        }
                    });
                } else{
                    resultDropdown.empty();
                }
    }
        });
        
        
        
        
        
        $('#btn_submit').on("click", function(){
        if(array.length>0){
                $("#form_submit").prop('disabled', true);
                var update_status=$('#update_status').val();
                var update_status_name=$("#update_status option:selected").text();
                var status_location=$('#status_location').val();
                var status_location_name=$("#status_location option:selected").text();
                var status_description=$('#status_description').val();
                var status_date=$('#status_date').val();
                var manifest_id= $('#manifest_id').val();
            
                var vehicle_no=$('#vehicle_no').val();
                var driver_name=$('#driver_name').val();
                var driver_mobile=$('#driver_mobile').val();
                var to_branch_name = $('#to_branch_name').val();
                var to_branch=$('#to_branch').val();/*
                
                var branch_name=$('#branch_name').val();*/
               $.ajax({
                          type:'POST',
                          url:'custom-api/scanning-incoming-manifest-update-api.php',
                          data:{updated_ids:array,type:'scanning_status_update_api',manifest_id:manifest_id,to_branch:to_branch,vehicle_no:vehicle_no,driver_name:driver_name,driver_mobile:driver_mobile,status_location_name:status_location_name,update_status:update_status,update_status_name:update_status_name,status_location:status_location,status_description:status_description,status_date:status_date},
                          dataType: 'json',
                          beforeSend: function() {
    						$('#update_fa').addClass('fa fa-spinner fa-spin');
    					  },
                          success:function(response){
                              $("#form_submit").prop('disabled', false);
                              if(response['error']==false){
                                      $("#update_fa").removeClass("fa fa-spinner fa-spin");
                                      $('#update_fa').addClass('fa fa-paper-plane');
                                      //alert(response['meassge']);
                                       $('#text_update_status').text($("#update_status :selected").text());
                                        $('#scaned_table_data_body').empty();
                                        array.splice(0, array.length);
                                         $("#btn_print").attr('href', 'manifest-print.php?id=' + response['manifest_id']);
                                        
                                        $("#print_confirm").modal('show');
                                      $('#success_title').text(response['meassge']);
                                      $('#modal-body').show();
                                      
                                  }else{
                                       $("#update_fa").removeClass("fa fa-spinner fa-spin");
                                      $('#update_fa').addClass('fa fa-paper-plane');
                                      //alert(response['meassge']);
                                       $("#print_confirm").modal('show');
                                      $('#success_title').text(response['meassge']);
                                      $('#modal-body').hide();
                                  }
                    
                          }
                        }); 
        }else{
            alert('scan min one pickup entry to update status');;
        }
    });
    });
    
    
    
<?php foreach($_datas as $r){ ?>

array.push(<?=$r['id']?>);
  console.log('Ganesan'+array);    
<?php } ?>       



function product_selection(id){
                if(array.includes(id)) {
                    var sound = document.getElementById("scanned_wrong_sound"); 
                    sound.play();
                    var ds='<div><center style="padding:10px;color:black;"> This AWB Number Already <b style="color:yellow"> Added </b></center><div>';
                    $(".result").html(ds);
                }else{
                   /* var update_status=$('#update_status').val();
                    var client_id = $('#client_id').val();
                    var branch_name = $('#branch_name').val();*/
                    $.ajax({
                      type:'POST',
                      url:'custom-api/get-awb-information.php',
                      data:{pickup_entry_id:id,type:'pickup_entry_info'},
                      dataType: 'json',
                      success:function(response){
                          $('#scaned_table_data').prepend(response['data']);
                          array.push(id);
                          var sound = document.getElementById("scanned_sound"); 
                          sound.play(); 
                          $(".result").empty();
                      }
                    });
                }
                $('.search-box input[type="text"]').val('');
                $('.search-box input[type="text"]').focus();
            }
            
function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}          
function remove(id)
{
    if (confirm('Confirm if you want to remove this AWB')){
        $('table#scaned_table_data tr#pic_'+id).remove();
        removeA(array,id);
    }
}
</script>


<style>
    .search-box{
        font-size: 14px;
    }
    .search-box {
        padding: 0px 10px;
        font-size: 14px;
    }
    .result{
        position: absolute;        
        z-index: 999;
        top: 89%;
        left: 0;
    }
    .search-box, .result{
        width: 100%;
        box-sizing: border-box;
    }
    /* Formatting result items */
    .result div{
        margin: 0;
        background: #d4d4d4;
        padding: 1px 5px;
        border: 1px solid #CCCCCC;
        border-top: none;
        cursor: pointer;
        margin-top: 0px;
    }
    .result div:hover{
        background: #00a65a;
        color: white;
        padding:0px;
        font-weight:800;
    }
    .delete:hover{
        background: red;
        color: white;
        padding:5px;
        font-weight:800;
    }
</style>