<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$form_action	= "insert";
$button_value 	= "Add";
$table_name 	= "delivery_notes";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Add Delivery Note";

$from = $_REQUEST['from'];

$rr_query = mysqli_query(
    $conn,
    "SELECT 
        CASE 
            WHEN MAX(note_number) < 60000 OR MAX(note_number) IS NULL 
            THEN 60000 
            ELSE MAX(note_number) + 1 
        END AS new_note_number
     FROM delivery_notes"
);

$rr_row = mysqli_fetch_assoc($rr_query);
$note_number = (int)$rr_row['new_note_number'];



 
//$created_by = Admin::getAdminsById($_SESSION['user_id']);


$next_page_condition 	= "";

if($_REQUEST['hide_top']){
	$next_page_condition.="&hide_top=1";
}
if($_REQUEST['hide_left']){
	$next_page_condition.="&hide_left=1";
}

$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
	$next_page_condition.="&start=$start";
}
$deliver_to ="Thermotec Plastics Ltd Electra Park Industrial Estate Electric Avenue Witton Birminggham B6 7EB";
############################## START INSERT #################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string","quantity"));
    
    $note_number 		        = $_REQUEST['note_number'];   
	$delivery_date 				= utility::setFormatedDate($_REQUEST['delivery_date']); 
    $customer_id 				= $_REQUEST['customer_id'];
    $ship_id 		         	= $_REQUEST['ship_id']; 
	$delivery_note 		        = $_REQUEST['delivery_note']; 
     
	$created_by				= $_SESSION['user_id'];
	$created_on				= date("Y-m-d H:i:s");
	$updated_on				= date("Y-m-d H:i:s");
	$updated_by				= $_SESSION['user_id'];
    
	$sql = "note_number = '".$note_number."',delivery_date = '".$delivery_date."',customer_id = '".$customer_id."',ship_id = '".$ship_id."',delivery_note = '".$delivery_note."',created_by = '".$created_by."',created_on = '".$created_on."', updated_by = '".$updated_by."'";
	$sql= "INSERT INTO $table_name SET ".$sql;

	mysqli_query($conn,$sql);
	$delivery_note_id = mysqli_insert_id($conn);
	
	if(count($_REQUEST['quantity'])>0){
		foreach($_REQUEST['quantity'] as $key => $quantity){
			$order_number= $_REQUEST['order_number'][$key];
			$part_number	 = $_REQUEST['part_number'][$key];	
			$description	 = $_REQUEST['description'][$key];
			
			
            if($quantity!="" ){				
				$sql1 = "delivery_note_id = '".$delivery_note_id."',quantity = '".$quantity."',order_number = '".$order_number."',part_number = '".$part_number."',description = '".$description."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
				 $sql1= "INSERT INTO delivery_note_mapping SET ".$sql1;
		
				mysqli_query($conn,$sql1);
			}
		}
	}	
	foreach ($_REQUEST['quantity'] as $key => $deliveredQty) {
    $deliveredQty = (float)$deliveredQty;
    if (empty($deliveredQty) || $deliveredQty <= 0) continue;

    $partId   = (int)    $_REQUEST['part_number'][$key];  // numeric ID


    // UPDATE INVENTORY
    mysqli_query($conn, "
        UPDATE inventory 
        SET quantity_in_stock = quantity_in_stock - $deliveredQty
        WHERE item_id = '$partId'
    ");
	
	
    $partCode = mysqli_real_escape_string($conn, $_REQUEST['part_number'][$key]); // raw value
    $orderId  = (int)    $_REQUEST['order_number'][$key];

    if ($orderId <= 0) continue;

    $RefSalesCode = $gsi->getSalesRefCodeById($orderId);
    if ($RefSalesCode == '') continue;
    $RefSalesCode = mysqli_real_escape_string($conn, $RefSalesCode);

    $remainingQty = $deliveredQty;

  $query = "
    SELECT id, part_id, req_qty, shipped_qty
    FROM production_planning
    WHERE part_id = $partId
    AND RefSalesCode = '$RefSalesCode'
    AND is_shipped IN (0, 2)
    ORDER BY req_date ASC, id ASC
";

    $result = mysqli_query($conn, $query);
    if (!$result) continue;

    while ($row = mysqli_fetch_assoc($result)) {
        if ($remainingQty <= 0) break;

        $planId     = (int)   $row['id'];
        $pendingQty = (float) $row['req_qty']; // req_qty is the remaining balance

        if ($pendingQty <= 0) continue;

        if ($remainingQty >= $pendingQty) {
            // FULLY SHIPPED
            $remainingQty -= $pendingQty;
            mysqli_query($conn, "
                UPDATE production_planning
                SET shipped_qty = shipped_qty + $pendingQty,
                    req_qty     = 0,
                    is_shipped  = 1,
                    updated_on  = '$updated_on'
                WHERE id = $planId
            ");
        } else {
            // PARTIALLY SHIPPED
            mysqli_query($conn, "
                UPDATE production_planning
                SET shipped_qty = shipped_qty + $remainingQty,
                    req_qty     = req_qty - $remainingQty,
                    is_shipped  = 2,
                    updated_on  = '$updated_on'
                WHERE id = $planId
            ");
            $remainingQty = 0;
            break;
        }
    }
}



	$_SESSION['info_message'] = "Deliver Note added successfully";	
	header("Location: $file_name");
    exit();
}
########################################## END INSERT ##########################################

########################################## START EDIT ##########################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];
	$po_id = utility::app_crypt($_REQUEST['po_id'],'d');
	if($id != $po_id){
		die("Invaild URL");
	}
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Delivery Note";
	$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);
	$row_edit = utility::validate_crypt_data($row_edit);
	
    $ship_id 		         	= $row_edit['ship_id'];
    $note_number 			    = $row_edit['note_number'];  
	$delivery_date 			     = $row_edit['delivery_date'];
    $delivery_note 			     = $row_edit['delivery_note']; 
    $customer_id 			     = $row_edit['customer_id'];
	
	
	//$created_by = Admin::getAdminsById($row_edit['created_by']);
	//$created_on = date('d-m-Y',strtotime($row_edit['created_on']));	
}
########################################### END EDIT ###########################################


######################################## START UPDATE ######################################### 
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){    
	utility::addslashesOnAllInput(array("query_string","delivery_note_mapping_id"));
	$id						= $_REQUEST['id'];
	$note_number 		    = $_REQUEST['note_number']; 
	$delivery_date 			= utility::setFormatedDate($_REQUEST['delivery_date']); 
	$delivery_note 			= $_REQUEST['delivery_note']; 
    $customer_id 			= $_REQUEST['customer_id'];
    $ship_id 		        = $_REQUEST['ship_id'];
	$updated_by				= $_SESSION['user_id'];
	
	$sql = "note_number = '".$note_number."',delivery_date = '".$delivery_date."',delivery_note = '".$delivery_note."',customer_id = '".$customer_id."',ship_id = '".$ship_id."', updated_by = '".$updated_by."'";
	$sql= "UPDATE $table_name SET ".$sql." WHERE id = '".$id."'";

    mysqli_query($conn,$sql);
	
	
	 if(count($_REQUEST['quantity'])>0){
		foreach($_REQUEST['quantity'] as $key => $quantity){
			$ordering		 = $_REQUEST['ordering'][$key];	
			$order_number= $_REQUEST['order_number'][$key];
			$part_number	 = $_REQUEST['part_number'][$key];	
			$issue	 		 = $_REQUEST['issue'][$key];	
			$description	 = $_REQUEST['description'][$key];	
			$unit_price		 = $_REQUEST['unit_price'][$key];
			$total	 		 = $_REQUEST['total'][$key];
			$delivery_note_mapping_id			 = $_REQUEST['delivery_note_mapping_id'][$key];
			
            if($quantity!="" ){	
			
                if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM delivery_note_mapping WHERE id = '$delivery_note_mapping_id' ")) > 0){
					 $sql2= "UPDATE delivery_note_mapping SET quantity = '".$quantity."', order_number = '".$order_number."', part_number = '".$part_number."', description = '".$description."', updated_by = '$updated_by' WHERE id = '$delivery_note_mapping_id' ";
					mysqli_query($conn,$sql2);
				}else{
					 $sql1 = "delivery_note_id = '".$id."',quantity = '".$quantity."',order_number = '".$order_number."',part_number = '".$part_number."',description = '".$description."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
					$sql1= "INSERT INTO delivery_note_mapping SET ".$sql1;
					mysqli_query($conn,$sql1);
				}
			}
		}
	} 
	
	
	
	
	$query_string = (isset($_REQUEST['query_string']) && !empty($_REQUEST['query_string'])) ? $_REQUEST['query_string'] : "";
  	$query_string = str_ireplace("page=add", "page=view", $query_string);
	$query_string = "&".$query_string;
	
	$po_id = urlencode(utility::app_crypt($id,'e'));
	$_SESSION['info_message'] = "Delivery Note updated successfully";
	
    header("Location: $file_name$query_string");
    exit();
}
################################# END UPDATE ######################################## 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
<? if(isset($from) && ($from == "view_jobs_details" || $from == "view_equipment_details11")){?>
.content-wrapper{
	margin-left: 0 !important;
}
.headings{
	display:none;
}
<?}?>
input[type="radio"],input[type="checkbox"]{
	top:4px;
	position:relative;
}
</style>
<div class="col-sm-12 col-lg-12 col-12" id="new_delivery_note_div_to_clone" style="display:none;">
		<div class="row">
			
			<div class="col-sm-3"> 
				<div>
					<label class="control-label" for="order_number">&nbsp;<em></em></label> 
					<? $gsi->getSalesRefCodeListNew("order_number[]","","100%",false,"form-control order_numberclone order_number ","");?>	
				</div>
			</div>
			<div class="col-sm-3"> 
				<label class="control-label" for="Part Number" style="font-size:12px;">&nbsp;<em></em></label> 
				<? $gsi->getPartNumberListNew("part_number[]", "", "100%", false, "form-control part_numberclone part_number part_number", "required"); ?>
				<i class="fas fa-sync-alt fa-spin" style="display:none;font-size:12px;" id="description_load"></i>
			</div>
			
			<div class="col-sm-3"> 
				 <label class="control-label" for="Description">&nbsp;<em></em></label> 
				  <input type="text" id="description" name="description[]" class="form-control" value="" placeholder="Description"> 
			</div>
			<div class="col-sm-1">
				<div class="">			
					<label class="control-label" for="QTY">&nbsp;<em></em></label> 
					<input type="Number" class="form-control quantity check_number_value only_num" id="quantity" name="quantity[]" value="" placeholder="QTY" autocomplete="off" required min="0">  
				</div>
			</div>
			
			
			<div class="col-sm-1 "style="margin-top:35px;"> 
				<div class="custom-trash ">
					<label class="control-label" style="font-color:red;"></label> 
					<span class="fa fa-trash delete_delivery_note_item" alt="" style="cursor:pointer; color: red;"></span>
					<input type="hidden" id="" class="each_row_total" value="" >
					<input type="hidden" id="" class="each_sale_row_total" value="" >
				</div>
			</div>
		</div>
</div>
<section class="content-header headings">
	<div class="container-fluid">
		<div class="row mb-2">
			<div class="col-sm-6">
				<h1>
					<?=$page_name;?>
				</h1>
			</div>
			<div class="col-sm-6">
			<?
			$query_string 	=  (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
			if(isset($from) && $from == "view_delivery_note_details"){
				$query_string = str_ireplace("page=add", "page=view_delivery_note_details", $query_string);
			}else {
				$query_string = str_ireplace("page=add", "page=view", $query_string);
			}
				
			?>
			<button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-success" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>
<section class="content">
	<div class="row">
		<div class="col-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? } ?>
			<!----------------------- End Message ------------------------------->
			<!-- general form elements -->
              <div class="card">
                <form class="" method="post" name="form1" id="form1" action="index?page=add&action=<? echo $form_action; ?>" onsubmit="return validateForm(this)" enctype="multipart/form-data">
                  <div class="card-body">
				  <div class="row">
				<div class="col-lg-6 col-sm-12">
					<div class="form-group"> 
						<label class="control-label" for="Delivery Number">Delivery Number <em>*</em></label> 
						<div class="">
							<input type="text" id="note_number" name="note_number" class="form-control" value="<?php echo $note_number;?>" placeholder="Delivery Number" readonly>
						</div> 
					</div>
					
					<div class="form-group"> 
						<label class="control-label" for="Order Status">Customer<em></em></label> 
						<div class=""> 
							<? $gsi->getCustomerList("customer_id",$customer_id,"100%",false,"form-control select2",""); ?>
						</div> 
					</div>
					</div>
					<div class="col-lg-6 col-sm-12">
					
					<div class="form-group"> 
							<label class="control-label" for="Customer">Ship Method<em>*</em></label> 
							<div class=""> 
								<? $gsi->getShipStatusList("ship_id",$ship_id,"100%",false,"form-control select2","required","",""); ?>
							</div> 
						</div>
						<div class="form-group">
						   <label class="control-label" for="Invoice Number">Delivery Date <em></em></label> 
							<div>
							<input type="text" class="form-control datepicker delivery_date" id="delivery_date" name="delivery_date" value="<?php echo (isset($delivery_date) && ($delivery_date) !="") ? utility::getFormatedDate($delivery_date) : "";?>" placeholder="DD-MM-YYYY"  autocomplete="off" > 
						   </div>	
					   </div>
					</div>
					<div class="col-lg-6 col-sm-12">
						<div class="form-group"> 
							<label class="control-label" for="Delivery Note">Delivery Note<em></em></label> 
							<div class=""> 
								<textarea id="delivery_note" name="delivery_note" class="form-control" rows="2"
						          placeholder="Delivery Note"><?php echo stripslashes($delivery_note);?></textarea>
							</div> 
						</div>
				   </div>
				

<style>
.container {
    margin-top: 20px;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    border-bottom: 2px solid #ddd;
    padding-bottom: 5px;
}

.delivery-address-section,
.invoice-address-section {
    border: 1px solid #ddd;
    padding: 15px;
    border-radius: 5px;
    background-color: #f9f9f9;
}

.row {
    margin-bottom: 15px;
}
</style>

				<div class="col-lg-12 col-sm-12 text-primary" style="margin-top:20px;">
					<h5>Line Items<hr style='height:2px;color:black; background-color: #a423a4;'></h5>
				</div>
				<?		$final_total=0;
						
						$po_item_mapping_query = "SELECT * FROM delivery_note_mapping WHERE delivery_note_id='".$id."'ORDER BY id ASC";
						$po_item_mapping_sql=mysqli_query($conn,$po_item_mapping_query);
						$po_item_mapping_count=mysqli_num_rows($po_item_mapping_sql);
						if($po_item_mapping_count>0){
							$i = 0;
							$j = 0;
							$ordering = 1;
							while($row_po_item_mapping = mysqli_fetch_array($po_item_mapping_sql)){
								
								//$unit_price = $row_po_item_mapping['unit_price'];
								//$total = $unit_price * $row_po_item_mapping['quantity'];
								
								
					?>
		<div class="col-sm-12 col-lg-12 col-12 initial_row_for_po_items" id="new_po<?=$row_po_item_mapping['id'];?>" data-po_count="<?=$row_po_item_mapping['id'];?>" alt="<?=$row_po_item_mapping['id'];?>">
			<div class="row">
				
				<div class="col-sm-3"> 
						<label class="control-label" for="Item Type">Order Number<em></em></label>
					<div> 
						<? $gsi->getSalesRefCodeListNew("order_number[$i]",$row_po_item_mapping['order_number'],"100%",false,"form-control select2 order_number","","");?>	
					</div>
					 <i class="fas fa-sync-alt fa-spin" style="display:none;font-size:12px;" id="description_load"></i>					
				</div>
				<div class="col-sm-3"> 
						<label class="control-label" for="Part Number" style="font-size:12px;">Part Number<em></em></label>
					<div> 
						<? $gsi->getPartNumberListNew("part_number[$i]",$row_po_item_mapping['part_number'],"100%",false,"form-control select2 part_number","","");?>	
					</div>					
				</div>
				<div class="col-sm-3"> 
					 <label class="control-label" for="Description">Description<em></em></label> 
					  <input type="text" id="description" name="description[<?=$i;?>]" class="form-control description" value="<?php echo $row_po_item_mapping['description'];?>" placeholder="Description">
				</div>
				<div class="col-sm-1">
					<div class="">			
						<label class="control-label" for="Quantity">QTY<em>*</em></label> 
						<input type="number" id="quantity" name="quantity[<?=$i;?>]" class="form-control quantity check_number_value only_num" value="<?php echo $row_po_item_mapping['quantity'];?>" placeholder="QTY" required min="0">
					</div>
				</div>
				
				<div class="col-sm-1" style="margin-top:35px;"> 
					<div class="custom-trash">
						<label class="control-label" style="font-color:red;"></label>
						<input type="hidden" name="delivery_note_mapping_id[<?=$i;?>]" value="<?php echo $row_po_item_mapping['id'];?>">
						
						<!--<span class="fa fa-trash delete_delivery_note_item" style="cursor:pointer; color: red;" alt="<?php echo $row_po_item_mapping['id'];?>" data-item_amount="<?php echo $row_po_item_mapping['total'];?>" data-t_sale_item_amount="<?php echo $total;?>"></span>-->
						
						<i class="fas fa-sync-alt fa-spin" id="load_new_po_item_<?=$row_po_item_mapping['id'];?>" style="font-size: 20px;display:none;"></i>
						<i class="fa fa-check" id="po_item_delete_done_<?=$row_po_item_mapping['id'];?>" style="color:#bad23a;font-size: 20px;display:none;"></i>
					</div>
				</div>
			</div>
		</div>
	
			<? $i++;
				$j++;
				$ordering++;
				//$total = $row_po_item_mapping["quantity"] * $row_po_item_mapping["unit_price"];
				
				//$final_total = $final_total + $total;
				
				 
				
			}}else{?>
			<div class="col-sm-12 col-lg-12 col-12 initial_row_for_po_items" id="new_po0" data-po_count="0" alt="0">
				<div class="row">
					
					<div class="col-sm-3"> 
						<label class="control-label" for="Item Type">Order Number<em></em></label> 
							<div> 
							   <? $gsi->getSalesRefCodeListNew("order_number[]","","100%",false,"form-control select2 order_number",""); ?>
							</div>
					</div>
					<div class="col-sm-3"> 
						<label class="control-label" for="Part Number"style="">Part Number<em></em></label> 
							<div>
							   <? $gsi->getPartNumberListNew("part_number[]","","100%",false,"form-control select2 part_number","required"); ?>
								<i class="fas fa-sync-alt fa-spin" style="display:none;font-size:12px;" id="description_load"></i>
							</div>
					</div>
					<div class="col-sm-3"> 
						 <label class="control-label" for="Description">Description<em></em></label> 
						  <input type="text" id="description" name="description[]" class="form-control" value="" placeholder="Description"> 
					</div>
					<div class="col-sm-1"> 
						 <label class="control-label" for="QTY">QTY<em></em></label> 
						  <input type="number" id="quantity" name="quantity[]" class="form-control quantity" value="" placeholder="QTY" min="0"> 
					</div>
					
				</div>
			</div>
			<?}?>
					<div class="form-group col-sm-12 new_delivery_note_div_to_append">	
						<label class="add_one_more_new_delivery_note" style="margin-left:0%;cursor:pointer;color: #a423a4; "><span class="fa fa-plus"></span>Add More</label>
					</div>
					<!--<div class="form-group col-sm-12 ">	
						<label class="" style="margin-top:6px;float: right;">Total Price: <span id="final_total">&pound;<?=number_format($final_total,2);?></span></label>
						
						<input type="hidden" class="final_total_remove" value="<?php //echo $final_total;?>">
					</div>-->
					
					<!--<div class="form-group col-sm-12 ">	
						<label class="" style="margin-top:6px;float: right;">Grand Total Sale: <span id="grand_total">&pound;<?=number_format($grand_total,2);?></span></label>
						<input type="hidden" class="final_sale_total_remove" value="<?php echo $grand_total;?>">
				</div>-->					

			</div><!-- /.box-body -->
                  <div class="card-footer">
					<input type="hidden" id="id" name="id" value="<?php echo $id;?>">
					<input type="hidden" id="from" name="from" value="<?php echo $from;?>">
					<input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string;?>">
                    <button type="submit" id="submit" name="submit" value="<?php echo $button_value;?>" class="btn btn-primary">Submit
						<i class="fas fa-sync-alt fa-spin" style="display:none;" id="page_load_div"></i>
					</button>
                  </div>
                </form>
              </div><!-- /.box -->
		</div>
	</div>
</section>
<script type="text/javascript">
$(function(){
	$('#form1').submit(function(){
		//$(this).addClass('disabled');
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
	});
	$('.add_one_more_new_delivery_note').click(function() {		
		$('#new_delivery_note_div_to_clone').show();		
		var div_count = $('.initial_row_for_po_items').last().attr("data-po_count");
		
		div_count++;
		var ordering_count = $('.initial_row_for_po_items').find("#ordering").last().attr("value")
		ordering_count++;
		var cloned_div = $('#new_delivery_note_div_to_clone').clone().addClass("initial_row_for_po_items").attr("id","new_po"+div_count).attr("data-po_count",div_count);		
		$('.new_delivery_note_div_to_append').before(cloned_div);	
		$('#new_po'+div_count).children().find(".datepicker").datepicker({
			changeMonth: true,
			changeYear: true,
			todayHighlight:true,
			format: "dd-mm-yyyy",
			autoclose: true
		});	
		$('#new_delivery_note_div_to_clone').hide();	

		$('#new_po'+div_count).attr("alt",div_count);
		$('#new_po'+div_count).children().find("#ordering").attr("value",ordering_count);
		$('#new_po'+div_count).children().find(".part_numberclone").attr("id","part_number"+div_count).attr("alt",div_count).select2();
		$('#new_po'+div_count).children().find(".order_numberclone").attr("id","order_number"+div_count).attr("alt",div_count).select2();
	});
	
	$("#form1").on("change",".part_number",function(){
		var div_no = $(this).closest("[alt]").attr("alt");
		//alert(div_no);
		var part_number = $(this).val();
		if(part_number != ""){
			$('#new_po'+div_no).find("#description_load").show();
			var form_data   = {'part_number':part_number};
			$.ajax({
				async: true,
				type: "POST",
				url: site_url+"/modules/delivery_note/index.php?page=ajax_actions&action=get_part_description_by_part_number",
				data: form_data,
				success: function(result){  
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == "success"){
						$('#new_po'+div_no).find("#description").val(resultObj.product_description);
						
						$('#new_po'+div_no).find("#description_load").hide();
					}
				}
			});
		}
	});

		
	$("#form1").on("keyup change", ".quantity, .unit_price", function () {
		
		var div_no = $(this).closest("[data-po_count]").attr("data-po_count");
		var qty = parseFloat($('#new_po'+div_no).find(".quantity").val());
		var unit_price = parseFloat($('#new_po'+div_no).find(".unit_price").val());

		if (!isNaN(qty) && !isNaN(unit_price)) {
			var total = qty * unit_price;
			$('#new_po'+div_no).find(".total").val(total);
		} else {
			$('#new_po'+div_no).find(".total").val(""); 
		}
		
		
	    var final_total = 0;
		
		$('.initial_row_for_po_items').each(function(){
			var div_no = $(this).attr("data-po_count");
			
			var qty = $('#new_po'+div_no).find(".quantity").val();
			var unit_price = $('#new_po'+div_no).find(".unit_price").val();
			var vat = $('#new_po'+div_no).find(".vat").val();
			total = parseFloat(qty * unit_price);
			final_total = final_total+total;
			
		});
		if(!isNaN(final_total)){
			$('#final_total').html("&pound;"+final_total.toFixed(2));
			$('.final_total_remove').val(final_total);
		} 	
	});
	$('.only_num').keydown(function(event) {
		if (event.key !== "Backspace" && isNaN(parseInt(event.key)) && event.key !== ".") {
		  event.preventDefault();
		}
		if (event.key === "." && $(this).val().indexOf('.') !== -1) {
		  event.preventDefault();
		}
	});


	$("#form1").on("click", ".delete_delivery_note_item",function() {
		var grand_total = 0;
		var vat_amount = 0;
		var final_total_remove = $(".final_total_remove").val();
		var final_sale_total_remove = $(".final_sale_total_remove").val();
			if(confirm('Are you sure you want to delete?')){		
				if($(this).attr("alt") != ""){
				var si_item_mapping_id = $(this).attr("alt");
				var one_item_amount = $(this).attr("data-item_amount");
				var one_sale_item_amount = $(this).attr("data-t_sale_item_amount");
				//var final_total_remove = $(".final_total_remove").val();
				$('#load_new_po_item_'+si_item_mapping_id).show();
				var form_data   = {'si_item_mapping_id':si_item_mapping_id};       
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/delivery_note/index.php?page=ajax_actions&action=delete_SI_item",
					data: form_data,
					success: function(result){    
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$('#po_item_delete_done_'+si_item_mapping_id).show();
							$('#load_new_po_item_'+si_item_mapping_id).hide();
							
							final_total = final_total_remove - one_item_amount;
							$('#final_total').html("&pound;"+final_total.toFixed(2));
							$('.final_total_remove').val(final_total);
							
							setTimeout(function() {
								$('#po_item_delete_done_'+si_item_mapping_id).hide();
								$('#new_po'+si_item_mapping_id).remove();
								location.reload();
							},500);
						}
					}
				});
			}else{
				var each_row_total = $(this).closest(".row").find(".each_row_total").val();

				
				final_total = final_total_remove - each_row_total;
				
				$('#final_total').html("&pound;"+final_total.toFixed(2));
				$('.final_total_remove').val(final_total);
				
				var each_sale_row_total = $(this).parent().find(".each_sale_row_total").val();
				
				final_sale_total = final_sale_total_remove - each_sale_row_total;
				
				$('#grand_total').html("&pound;"+final_sale_total.toFixed(2));
				$('.final_sale_total_remove').val(final_sale_total);
				$(this).closest(".row").remove();
				setTimeout(function() {
						location.reload();
					},500);
			}
		}
	});
	$('#is_same_as_delivery_add').on('change', function () {
    const isChecked = $(this).is(':checked');
    const deliveryAddress1 = $('#delivery_address_1').val();
    const deliveryAddress2 = $('#delivery_address_2').val();
    const deliveryAddress3 = $('#delivery_address_3').val();
    const deliveryPostcode = $('#delivery_add_postcode').val();

    const invoiceAddress1 = $('#invoice_address_1');
    const invoiceAddress2 = $('#invoice_address_2');
    const invoiceAddress3 = $('#invoice_address_3');
    const invoicePostcode = $('#invoice_add_postcode');

     // This will show the correct value after it's captured

    if (isChecked) {
        invoiceAddress1.val(deliveryAddress1);
        invoiceAddress2.val(deliveryAddress2);
        invoiceAddress3.val(deliveryAddress3);
        invoicePostcode.val(deliveryPostcode);
    } else {
        invoiceAddress1.val('');
        invoiceAddress2.val('');
        invoiceAddress3.val('');
        invoicePostcode.val('');
    }
});



   $(document).ready(function() {
		var urlParams = new URLSearchParams(window.location.search);
		var cust_id = urlParams.get('cust_id');

		if (cust_id) {
			$("#customer_id").val(cust_id);
			setTimeout(function() {
				$("#customer_id").trigger("change");
			}, 500); 
		}
		
		$("#order_number").on("change", function() {
			var order_id = $(this).val();
			var form_data = {
				'order_id': order_id
			};
			////////////////////// For fetching cuatomer dropdown /////////////////////////
			if (order_id != "") {
				$.ajax({
					async: true,
					type: "POST",
					url: site_url + "/modules/delivery_note/index.php?page=ajax_actions&action=get_customer_drodown",
					data: form_data,
					success: function(result) {
						var resultObj = jQuery.parseJSON(result);
						if (resultObj.status == 1) {
							$(".enq_show").show();
							$("#customer_id").empty();
							for (i = 0; i < resultObj.customer_id.length; i++) {
								$("#customer_id").append(new Option(resultObj.customer_id[i].customer_name, resultObj.customer_id[i].id, false, false));
							}
							$("#customer_id").trigger("change");
						} else {
							$("#customer_id").empty();
							$("#delivery_add_id").empty();
							$("#delivery_address_1").val('');
							$("#delivery_address_2").val('');
							$("#delivery_address_3").val('');
							$("#delivery_add_postcode").val('');
							$("#invoice_address_1").val('');
							$("#invoice_address_2").val('');
							$("#invoice_address_3").val('');
							$("#invoice_add_postcode").val('');
						
							/* 
							$("#lift_id_serach").empty();
							$("#lift_id_serach").append(new Option("No Site This Client", "", true, true)); */
						}
					}
				});
			} else {
				$("#customer_id").empty();
							$("#delivery_add_id").empty();
							$("#delivery_address_1").val('');
							$("#delivery_address_2").val('');
							$("#delivery_address_3").val('');
							$("#delivery_add_postcode").val('');
							$("#invoice_address_1").val('');
							$("#invoice_address_2").val('');
							$("#invoice_address_3").val('');
							$("#invoice_add_postcode").val('');
			}
		});
		/////////////// Fetch customer adress dropdowbn   //////////////
		$("#form1").on("change", "#customer_id", function() {
			var customer_id = $(this).val();
			if (customer_id != "") {
				$('#zone_checking').show();
				var form_data = { 'customer_id': customer_id };       
				
				////////////////////// For fetching address /////////////////////////
				$.ajax({
					async: true,
					type: "POST",
					url: site_url + "/modules/delivery_note/index.php?page=ajax_actions&action=get_address_dropdown",
					data: form_data,
					success: function(result) {  
						var resultObj = jQuery.parseJSON(result); 
						if (resultObj.status == 1) {
							$(".enq_show").show();
							$("#delivery_add_id").empty();
							for (i = 0; i < resultObj.delivery_add_id.length; i++) {
								$("#delivery_add_id").append(new Option(resultObj.delivery_add_id[i].delivery_address_1, resultObj.delivery_add_id[i].id, false, false));
							}
							$("#delivery_add_id").trigger("change");
						} else {
							//$(".lift_show").hide();
							  $("#delivery_add_id").empty();
							//$("#lift_id_serach").append(new Option("No Site This Client", "", true, true));
						}
					}
				});
				////////////////////// End For fetching address /////////////////////////
			}else{
			 $("#delivery_add_id").empty();
			}
		});
		$("#form1").on("change", "#delivery_add_id", function() {
			var delivery_add_id = $(this).val();
			if (delivery_add_id != "") {
				$('#zone_checking').show();
				var form_data = { 'delivery_add_id': delivery_add_id };       
				
				////////////////////// For fetching address /////////////////////////
				$.ajax({
					async: true,
					type: "POST",
					url: site_url + "/modules/delivery_note/index.php?page=ajax_actions&action=get_customer_id_address",
					data: form_data,
					success: function(result) {  
						var resultObj = jQuery.parseJSON(result); 
						if (resultObj.status == 1) {
							$('#zone_checking').hide();
							$("#delivery_address_1").val(resultObj.delivery_address_1);
							$("#delivery_address_2").val(resultObj.delivery_address_2);
							$("#delivery_address_3").val(resultObj.delivery_address_3);
							$("#delivery_add_postcode").val(resultObj.delivery_add_postcode);
							$("#invoice_address_1").val(resultObj.invoice_address_1);
							$("#invoice_address_2").val(resultObj.invoice_address_2);
							$("#invoice_address_3").val(resultObj.invoice_address_3);
							$("#invoice_add_postcode").val(resultObj.invoice_add_postcode);
						}
					}
				});
				////////////////////// End For fetching address /////////////////////////
			}
		});
	});

});
</script>