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

$from = $_REQUEST['from'];

$rr_query = mysqli_query($conn, "SELECT IFNULL(MAX(invoice_number), 0) + 1 AS new_invoice_number FROM sales_invoices");

$rr_row = mysqli_fetch_assoc($rr_query);
$invoice_number = str_pad($rr_row['new_invoice_number'], 4, '1000', STR_PAD_LEFT);
 
//$created_by = Admin::getAdminsById($_SESSION['user_id']);
$invoice_date = date("d-m-Y"); 

$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"));
    
    $invoice_number 		    = $_REQUEST['invoice_number']; 
    $order_number 				= $_REQUEST['order_number']; 
	$invoice_date 				= utility::setFormatedDate($_REQUEST['invoice_date']); 
	$delivery_date 				= utility::setFormatedDate($_REQUEST['delivery_date']); 
	$delivery_add_id 			= $_REQUEST['delivery_add_id']; 
    $customer_id 				= $_REQUEST['customer_id'];
	$delivery_note_no 				= $_REQUEST['delivery_note_no'];
    $ship_id 		         	= $_REQUEST['ship_id'];
	$vendor_id 					= $_REQUEST['vendor_id']; 
	$delivery_address_1			= $_REQUEST['delivery_address_1'];
	$delivery_address_2			= $_REQUEST['delivery_address_2'];
	$delivery_address_3			= $_REQUEST['delivery_address_3'];
	$delivery_add_postcode		= $_REQUEST['delivery_add_postcode'];
	$invoice_address_1			= $_REQUEST['invoice_address_1'];	
	$invoice_address_2			= $_REQUEST['invoice_address_2'];	
	$invoice_address_3			= $_REQUEST['invoice_address_3'];
	$invoice_add_postcode		= $_REQUEST['invoice_add_postcode'];
     
	$created_by				= $_SESSION['user_id'];
	$created_on				= date("Y-m-d H:i:s");
	$updated_by				= $_SESSION['user_id'];
    
	$sql = "invoice_number = '".$invoice_number."',invoice_date = '".$invoice_date."',delivery_note_no = '".$delivery_note_no."',delivery_date = '".$delivery_date."',order_number = '".$order_number."',customer_id = '".$customer_id."',ship_id = '".$ship_id."',vendor_id = '".$vendor_id."',invoice_address_1 = '".$invoice_address_1."',invoice_address_2 = '".$invoice_address_2."',invoice_address_3 = '".$invoice_address_3."', invoice_add_postcode = '".$invoice_add_postcode."', delivery_address_1 = '".$delivery_address_1."',delivery_address_2 = '".$delivery_address_2."',delivery_address_3 = '".$delivery_address_3."', delivery_add_postcode = '".$delivery_add_postcode."',  delivery_add_id = '".$delivery_add_id."',created_by = '".$created_by."',created_on = '".$created_on."', updated_by = '".$updated_by."'";
	$sql= "INSERT INTO $table_name SET ".$sql;

	mysqli_query($conn,$sql);
	$sales_id = mysqli_insert_id($conn);
	
	if(count($_REQUEST['quantity'])>0){
		foreach($_REQUEST['quantity'] as $key => $quantity){	
			$ordering		 = $_REQUEST['ordering'][$key];	
			$order_number_mpp= $_REQUEST['order_number_mpp'][$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];
			
			
            if($quantity!="" ){				
				$sql1 = "sales_id = '".$sales_id."',quantity = '".$quantity."',ordering = '".$ordering."',order_number_mpp = '".$order_number_mpp."',part_number = '".$part_number."',description = '".$description."',issue = '".$issue."',unit_price = '".$unit_price."',total = '".$total."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
				 $sql1= "INSERT INTO sales_invoice_mapping SET ".$sql1;
		
				mysqli_query($conn,$sql1);
			}
		}
	}	

	$_SESSION['info_message'] = "Sales Invoice 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 Sales Invoice";
	$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'];
	$vendor_id 					= $row_edit['vendor_id']; 
    $invoice_number 			  = $row_edit['invoice_number'];  
	$invoice_date 			     = $row_edit['invoice_date']; 
	$delivery_date 			     = $row_edit['delivery_date']; 
    $order_number 			     = $row_edit['order_number'];  
	$delivery_note_no 			     = $row_edit['delivery_note_no']; 
    $delivery_add_id 			     = $row_edit['delivery_add_id']; 
    $customer_id 			     = $row_edit['customer_id'];
	$delivery_address_1			= $row_edit['delivery_address_1'];
	$delivery_address_2			= $row_edit['delivery_address_2'];
	$delivery_address_3			= $row_edit['delivery_address_3'];
	$delivery_add_postcode		= $row_edit['delivery_add_postcode'];
	$invoice_address_1			= $row_edit['invoice_address_1'];	
	$invoice_address_2			= $row_edit['invoice_address_2'];	
	$invoice_address_3			= $row_edit['invoice_address_3'];
	$invoice_add_postcode		= $row_edit['invoice_add_postcode'];
	
	//$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","sales_invoice_mapping_id"));
	$id							= $_REQUEST['id'];
	$invoice_number 		    = $_REQUEST['invoice_number']; 
    $order_number 				= $_REQUEST['order_number']; 
	$invoice_date 				= utility::setFormatedDate($_REQUEST['invoice_date']); 
	$delivery_date 				= utility::setFormatedDate($_REQUEST['delivery_date']); 
	$delivery_add_id 			= $_REQUEST['delivery_add_id']; 
    $customer_id 				= $_REQUEST['customer_id'];    
	$delivery_note_no 				= $_REQUEST['delivery_note_no'];
    $ship_id 		         	= $_REQUEST['ship_id'];
	$vendor_id 					= $_REQUEST['vendor_id']; 
	$delivery_address_1			= $_REQUEST['delivery_address_1'];
	$delivery_address_2			= $_REQUEST['delivery_address_2'];
	$delivery_address_3			= $_REQUEST['delivery_address_3'];
	$delivery_add_postcode		= $_REQUEST['delivery_add_postcode'];
	$invoice_address_1			= $_REQUEST['invoice_address_1'];	
	$invoice_address_2			= $_REQUEST['invoice_address_2'];	
	$invoice_address_3			= $_REQUEST['invoice_address_3'];
	$invoice_add_postcode		= $_REQUEST['invoice_add_postcode'];
	$updated_by				= $_SESSION['user_id'];
	
	$sql = "invoice_number = '".$invoice_number."',invoice_date = '".$invoice_date."',delivery_date = '".$delivery_date."',delivery_note_no = '".$delivery_note_no."',order_number = '".$order_number."',customer_id = '".$customer_id."',ship_id = '".$ship_id."',vendor_id = '".$vendor_id."',invoice_address_1 = '".$invoice_address_1."',invoice_address_2 = '".$invoice_address_2."',invoice_address_3 = '".$invoice_address_3."', invoice_add_postcode = '".$invoice_add_postcode."', delivery_address_1 = '".$delivery_address_1."',delivery_address_2 = '".$delivery_address_2."',delivery_address_3 = '".$delivery_address_3."', delivery_add_postcode = '".$delivery_add_postcode."',  delivery_add_id = '".$delivery_add_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_mpp= $_REQUEST['order_number_mpp'][$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];
			$sales_invoice_mapping_id			 = $_REQUEST['sales_invoice_mapping_id'][$key];
			
            if($quantity!="" ){	
			
                if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM sales_invoice_mapping WHERE id = '$sales_invoice_mapping_id' ")) > 0){
					 $sql2= "UPDATE sales_invoice_mapping SET quantity = '".$quantity."', ordering = '".$ordering."', order_number_mpp = '".$order_number_mpp."',part_number = '".$part_number."',description = '".$description."', unit_price = '".$unit_price."',issue = '".$issue."',total = '".$total."',updated_by = '$updated_by' WHERE id = '$sales_invoice_mapping_id' ";
					mysqli_query($conn,$sql2);
				}else{
					 $sql1 = "sales_id = '".$id."',quantity = '".$quantity."',ordering = '".$ordering."',order_number_mpp = '".$order_number_mpp."',part_number = '".$part_number."',description = '".$description."',issue = '".$issue."',unit_price = '".$unit_price."',total = '".$total."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
					$sql1= "INSERT INTO sales_invoice_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'] = "Sales Invoice 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_sales_invoice_div_to_clone" style="display:none;">
		<div class="row">
			<div class="col-sm-1 hide"> 
				 <label class="control-label" for="Item No.">&nbsp;<em></em></label> 
				 <input type="text" id="ordering" name="ordering[]" class="form-control" value="" placeholder="Item No.">
			</div>
			
			<div class="col-sm-2"> 
				<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-2"> 
				<div>
					<label class="control-label" for="order_number_mpp">&nbsp;<em></em></label> 
					<? $gsi->getSalesRefCodeListNew("order_number_mpp[]","","100%",false,"form-control order_number_mppclone order_number_mpp ","");?>	
				</div>
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Issue">&nbsp;<em></em></label> 
				  <input type="text" id="issue" name="issue[]" class="form-control" value="" placeholder="Issue"> 
			</div>
			<div class="col-sm-2"> 
				 <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"> 
				 <label class="control-label" for="Unit Price">&nbsp;<em></em></label> 
				 <div class=""> 
					<input type="text" id="unit_price" name="unit_price[]" class="form-control unit_price check_number_value only_num" value="" placeholder="Unit Price">
				</div>
			</div>
			<div class="col-sm-1"> 
				 <label class="control-label" for="Total Price">&nbsp;<em></em></label> 
				 <div class=""> 
					<input type="text" id="total" name="total[]" class="form-control total" value="" placeholder="Total Price" readonly>
				</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_sales_invoice_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_sales_invoice_details"){
				$query_string = str_ireplace("page=add", "page=view_sales_invoice_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-3 col-sm-12">
					<div class="form-group"> 
						<label class="control-label" for="Invoice Number">Invoice Number <em>*</em></label> 
						<div class="">
							<input type="text" id="invoice_number" name="invoice_number" class="form-control" value="<?php echo $invoice_number;?>" placeholder="Invoice Number" readonly>
						</div> 
					</div>
					
					<div class="form-group hide"> 
						<label class="control-label" for="Order Status">Order Number<em>*</em></label> 
						<div class=""> 
							<? $gsi->getSalesRefCodeListNew("order_number",$order_number,"100%",false,"form-control select2",""); ?>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Order Status">Delivery Note Number<em></em></label> 
						<div class=""> 
							<? echo $gsi->getDeliveryNoteNoListNew("delivery_note_no",$delivery_note_no,"100%",false,"form-control select2",""); ?>
						</div> 
					</div>
					</div>
					<div class="col-lg-3 col-sm-12">
					<div class="form-group"> 
						<label class="control-label" for="Invoice Number">Invoice Date <em>*</em></label> 
						<div>
						<input type="text" class="form-control datepicker invoice_date" id="invoice_date" name="invoice_date" value="<?php echo (isset($invoice_date) && ($invoice_date) !="") ? utility::getFormatedDate($invoice_date) : "";?>" placeholder="DD-MM-YYYY"  autocomplete="off" required> 
					   </div>	
					</div>
					
					
					<div class="form-group"> 
						<label class="control-label" for="Order Status">Customer<em></em></label> 
						<div class=""> 
							<? echo $gsi->getCustomerListNew("customer_id",$customer_id,"100%",false,"form-control select2",""); ?>
						</div> 
					</div>
					
					</div>
					<div class="col-lg-3 col-sm-12">
					  <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 class="form-group"> 
						<label class="control-label" for="Order Status">Delivery Address <em></em></label> 
						<div class=""> 
							<? $gsi->getAddressDropList("delivery_add_id",$delivery_add_id,"100%",false,"form-control select2",""); ?>
						</div> 
					</div>
					</div>
					<div class="col-lg-3 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="Customer">Vendor ID<em></em></label> 
							<div class=""> 
								<input type="text" id="vendor_id" name="vendor_id" value="<?php echo $vendor_id;?>" class="form-control" placeholder="Vendor ID" >
							</div> 
						</div>
				   </div>
				   
				   <div class="container-fluid">
					<!-- Delivery Address Section -->
					<div class="delivery-address-section">
						<h4 class="section-title">Delivery Address</h4>
						<div class="row">
							<div class="col-lg-3 col-sm-12">
								<label for="delivery_address_1" class="control-label">Delivery Address 1</label>
								<input type="text" id="delivery_address_1" name="delivery_address_1" value="<?php echo $delivery_address_1;?>" class="form-control" placeholder="Delivery Address 1">
							</div>
							<div class="col-lg-3 col-sm-12">
								<label for="delivery_address_2" class="control-label">Delivery Address 2</label>
								<input type="text" id="delivery_address_2" name="delivery_address_2" value="<?php echo $delivery_address_2;?>" class="form-control" placeholder="Delivery Address 2">
							</div>
							<div class="col-lg-3 col-sm-12">
								<label for="delivery_address_3" class="control-label">Delivery Address 3</label>
								<input type="text" id="delivery_address_3" name="delivery_address_3" value="<?php echo $delivery_address_3;?>" class="form-control" placeholder="Delivery Address 3">
							</div>
							<div class="col-lg-3 col-sm-12">
								<label for="delivery_add_postcode" class="control-label">Postcode</label>
								<input type="text" id="delivery_add_postcode" name="delivery_add_postcode" value="<?php echo $delivery_add_postcode;?>" class="form-control" placeholder="Postcode">
							</div>
						</div>
					</div>
                        <div class="">
							
						<?php if (isset($_REQUEST['action']) && $_REQUEST['action'] = 'edit') { 
						 $hide="hide";
						 } ?>
						<div class="form-group <?php echo $hide; ?>" style="display: flex; align-items: center; gap: 10px;" >
							<label class="control-label" for="is_same_as_delivery_add" style="margin: 0;">
								&nbsp; Same as Delivery Address 1<em></em>
							</label>
							<input type="checkbox" class="flat-red" id="is_same_as_delivery_add" name="is_same_as_delivery_add" value="1"  
								   <?php echo ($is_same_as_delivery_add == 1) ? 'checked' : ''; ?>>
						</div>
						</div>
					<!-- Invoice Address Section -->
					<div class="invoice-address-section mt-4">
						<h4 class="section-title">Invoice Address</h4>
						<div class="row">
							<div class="col-lg-3 col-sm-12">
								<label for="invoice_address_1" class="control-label">Invoice Address 1</label>
								<input type="text" id="invoice_address_1" name="invoice_address_1" value="<?php echo $invoice_address_1;?>" class="form-control" placeholder="Invoice Address 1">
							</div>
							<div class="col-lg-3 col-sm-12">
								<label for="invoice_address_2" class="control-label">Invoice Address 2</label>
								<input type="text" id="invoice_address_2" name="invoice_address_2" value="<?php echo $invoice_address_2;?>" class="form-control" placeholder="Invoice Address 2">
							</div>
							<div class="col-lg-3 col-sm-12">
								<label for="invoice_address_3" class="control-label">Invoice Address 3</label>
								<input type="text" id="invoice_address_3" name="invoice_address_3" value="<?php echo $invoice_address_3;?>" class="form-control" placeholder="Invoice Address 3">
							</div>
							<div class="col-lg-3 col-sm-12">
								<label for="invoice_add_postcode" class="control-label">Postcode</label>
								<input type="text" id="invoice_add_postcode" name="invoice_add_postcode" value="<?php echo $invoice_add_postcode;?>" class="form-control" placeholder="Postcode">
							</div>
						</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> Invoice Items<hr style='height:2px;color:black; background-color: #a423a4;'></h5>
				</div>
				<?		$final_total=0;
						
						$po_item_mapping_query = "SELECT * FROM sales_invoice_mapping WHERE sales_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-1 hide"> 
					 <label class="control-label" for="Item No.">Item No.<em></em></label> 
					  <input type="text" id="ordering" name="ordering[<?=$i;?>]" class="form-control" value="<?php echo $row_po_item_mapping['ordering'];?>" placeholder="Item No.">
				</div>
				
				<div class="col-sm-2"> 
						<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-2"> 
						<label class="control-label" for="Item Type">Order Number<em></em></label>
					<div> 
						<? $gsi->getSalesRefCodeListNew("order_number_mpp[$i]",$row_po_item_mapping['order_number_mpp'],"100%",false,"form-control select2 order_number_mpp","","");?>	
					</div>
					 <i class="fas fa-sync-alt fa-spin" style="display:none;font-size:12px;" id="description_load"></i>					
				</div>
				<div class="col-sm-2"> 
					 <label class="control-label" for="issue">Issue<em></em></label> 
					  <input type="text" id="issue" name="issue[<?=$i;?>]" class="form-control issue" value="<?php echo $row_po_item_mapping['issue'];?>" placeholder="Issue">
				</div>
				<div class="col-sm-2"> 
					 <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"> 
					 <label class="control-label" for="Unit Price">Unit Price<em></em></label> 
					 <div class=""> 
						<input type="text" id="unit_price" name="unit_price[<?=$i;?>]" class="form-control unit_price check_number_value only_num" value="<?php echo $row_po_item_mapping['unit_price'];?>" placeholder="Unit Price">
					</div>
				</div>
				<div class="col-sm-1"> 
					 <label class="control-label" for="Total Sale">Total Price<em></em></label> 
					 <div class=""> 
						<input type="text" id="total" name="total[<?=$i;?>]" class="form-control total" value="<?php echo $total;?>" placeholder="Total Price" readonly>
					</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="sales_invoice_mapping_id[<?=$i;?>]" value="<?php echo $row_po_item_mapping['id'];?>">
						
						<span class="fa fa-trash delete_sales_invoice_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-1 hide"> 
						 <label class="control-label" for="Item No.">Item No.<em></em></label> 
						 <input type="text" id="ordering" name="ordering[]" class="form-control" value="1" placeholder="Item.No.">
					</div>
					<div class="col-sm-2"> 
						<label class="control-label" for="Part Number"style="font-size:12px;">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-2"> 
						<label class="control-label" for="Item Type">Order Number<em></em></label> 
							<div> 
							   <? $gsi->getSalesRefCodeListNew("order_number_mpp[]","","100%",false,"form-control select2 order_number_mpp",""); ?>
							</div>
					</div>
					
					
					<div class="col-sm-2"> 
						 <label class="control-label" for="Issue">Issue<em></em></label> 
						  <input type="text" id="issue" name="issue[]" class="form-control" value="" placeholder="Issue"> 
					</div>
					<div class="col-sm-2"> 
						 <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 class="col-sm-1"> 
						 <label class="control-label" for="Unit Price">Unit Price<em></em></label> 
						 <div class=""> 
							<input type="text" id="unit_price" name="unit_price[]" class="form-control unit_price check_number_value only_num" value="" placeholder="Unit Price">
						</div>
					</div>
					<div class="col-sm-1"> 
						 <label class="control-label" for="Total Price">Total Price<em></em></label> 
						 <div class=""> 
							<input type="text" id="total" name="total[]" class="form-control total" value="" placeholder="Total Price" readonly>
						</div>
					</div>

				</div>
			</div>
			<?}?>
					<div class="form-group col-sm-12 new_sales_invoice_div_to_append">	
						<label class="add_one_more_new_sales_invoice" 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_sales_invoice').click(function() {		
		$('#new_sales_invoice_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_sales_invoice_div_to_clone').clone().addClass("initial_row_for_po_items").attr("id","new_po"+div_count).attr("data-po_count",div_count);		
		$('.new_sales_invoice_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_sales_invoice_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_number_mppclone").attr("id","order_number_mpp"+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/sales_invoice/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_sales_invoice_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/sales_invoice/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/sales_invoice/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/sales_invoice/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/sales_invoice/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>