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

$from = $_REQUEST['from'];

$rr_query = mysqli_query($conn, "
    SELECT MAX(order_ref) AS max_po
    FROM purchase_order
    WHERE order_ref LIKE '04%'
");

$rr_row = mysqli_fetch_assoc($rr_query);

if (!empty($rr_row['max_po'])) {
    $next_po = intval($rr_row['max_po']) + 1;
} else {
    $next_po = 40001; // produces 040001
}

$order_ref = str_pad($next_po, 6, '0', STR_PAD_LEFT);
$created_on = 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";


function saveFreeTextPartNumber($conn, $po_item_id, $part_number, $user_id) {
    $po_item_id  = intval($po_item_id);
    $part_number = mysqli_real_escape_string($conn, $part_number);
    $user_id     = intval($user_id);
    $now         = date("Y-m-d H:i:s");

    $exists = mysqli_num_rows(
        mysqli_query($conn, "SELECT id FROM purchase_order_freetext_parts WHERE po_item_id = $po_item_id")
    );

    if ($exists) {
        mysqli_query($conn,
            "UPDATE purchase_order_freetext_parts
             SET part_number = '$part_number', updated_by = $user_id, updated_at = '$now'
             WHERE po_item_id = $po_item_id"
        );
    } else {
        mysqli_query($conn,
            "INSERT INTO purchase_order_freetext_parts
             (po_item_id, part_number, created_by, created_on, updated_by, updated_at)
             VALUES ($po_item_id, '$part_number', $user_id, '$now', $user_id, '$now')"
        );
    }
}

function deleteFreeTextPartNumber($conn, $po_item_id) {
    $po_item_id = intval($po_item_id);
    mysqli_query($conn, "DELETE FROM purchase_order_freetext_parts WHERE po_item_id = $po_item_id");
}

############################## START INSERT #################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string","quantity"));
    
    $order_ref    = $_REQUEST['order_ref'];  
	$supplier_id  = $_REQUEST['supplier_id']; 
    $order_status = $_REQUEST['order_status']; 
    $deliver_to   = $_REQUEST['deliver_to'];
	$order_notes  = $_REQUEST['order_notes']; 
     
	$created_by = $_SESSION['user_id'];
	$created_on = date("Y-m-d H:i:s");
	$updated_by = $_SESSION['user_id'];
    
	$sql = "order_ref = '".$order_ref."', supplier_id = '".$supplier_id."', order_status = '".$order_status."',
	        deliver_to = '".$deliver_to."', order_notes = '".$order_notes."',
	        created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."'";
	mysqli_query($conn, "INSERT INTO $table_name SET ".$sql);
	$po_id = mysqli_insert_id($conn);
	
	if(count($_REQUEST['quantity']) > 0){
		foreach($_REQUEST['quantity'] as $key => $quantity){
			$ordering      = $_REQUEST['ordering'][$key];	
			$item_type     = $_REQUEST['item_type'][$key];
			$nominal_code  = $_REQUEST['nominal_code'][$key];
			$description   = $_REQUEST['description'][$key];	
			$unit_price    = $_REQUEST['unit_price'][$key];
			$expected_date = utility::setFormatedDate($_REQUEST['expected_date'][$key]);
			$total         = $_REQUEST['total'][$key];
			$received      = $_REQUEST['received'][$key];
			$status        = $_REQUEST['status'][$key];

			if($item_type == 6){
				$part_number_display  = $_REQUEST['part_number_freetext'][$key];
				$part_number_to_store = 0;
			} else {
				$part_number_display  = $_REQUEST['part_number'][$key];
				$part_number_to_store = $part_number_display;
			}
			
            if($quantity != ""){
			$sql1 = "po_id = '".$po_id."', quantity = '".$quantity."', ordering = '".$ordering."',
         item_type = '".$item_type."', nominal_code = '".$nominal_code."', part_number = '".$part_number_to_store."',
				         description = '".$description."', unit_price = '".$unit_price."',
				         expected_date = '".$expected_date."', received = '".$received."',
				         status = '".$status."', total = '".$total."',
				         created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."'";
				mysqli_query($conn, "INSERT INTO purchase_order_items_mapping SET ".$sql1);
				$new_po_item_id = mysqli_insert_id($conn);

				if($item_type == 6 && $part_number_display != ''){
					saveFreeTextPartNumber($conn, $new_po_item_id, $part_number_display, $created_by);
				}
				
				if($item_type != 6 && in_array($status, [3, 4, 5]) && !is_null($received)){
					mysqli_query($conn,
						"UPDATE inventory SET quantity_in_stock = quantity_in_stock + $received,
						 updated_by = '$updated_by' WHERE item_id = '$part_number_to_store'"
					);
				}
			}
		}
	}	

	$_SESSION['info_message'] = "Purchase Order 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 Purchase Order";
	$query_string = (isset($_POST['query_string'])) ? $_POST['query_string'] : $_SERVER['QUERY_STRING'];
	
    $result_edit = mysqli_query($conn, "SELECT * FROM $table_name WHERE id = $id");
    $row_edit    = mysqli_fetch_array($result_edit);
	$row_edit    = utility::validate_crypt_data($row_edit);
	
    $order_ref    = $row_edit['order_ref'];  
	$supplier_id  = $row_edit['supplier_id']; 
    $order_status = $row_edit['order_status']; 
    $deliver_to   = $row_edit['deliver_to'];
	$order_notes  = $row_edit['order_notes'];
	$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","purchase_order_mapping_id"));
	$id           = $_REQUEST['id'];
	$order_ref    = $_REQUEST['order_ref'];  
	$supplier_id  = $_REQUEST['supplier_id']; 
    $order_status = $_REQUEST['order_status']; 
    $deliver_to   = $_REQUEST['deliver_to'];
	$order_notes  = $_REQUEST['order_notes'];
	$updated_by   = $_SESSION['user_id'];
	
	$sql = "order_ref = '".$order_ref."', supplier_id = '".$supplier_id."', order_status = '".$order_status."',
	        deliver_to = '".$deliver_to."', order_notes = '".$order_notes."', updated_by = '".$updated_by."'";
    mysqli_query($conn, "UPDATE $table_name SET ".$sql." WHERE id = '".$id."'");
	
	if(count($_REQUEST['quantity']) > 0){
		foreach($_REQUEST['quantity'] as $key => $quantity){
			$ordering                  = $_REQUEST['ordering'][$key];	
			$item_type                 = $_REQUEST['item_type'][$key];
			$nominal_code              = $_REQUEST['nominal_code'][$key];
			$description               = $_REQUEST['description'][$key];	
			$unit_price                = $_REQUEST['unit_price'][$key];
			$expected_date             = utility::setFormatedDate($_REQUEST['expected_date'][$key]);
			$received                  = $_REQUEST['received'][$key];
			$total                     = $_REQUEST['total'][$key];
			$status                    = $_REQUEST['status'][$key];
			$purchase_order_mapping_id = $_REQUEST['purchase_order_mapping_id'][$key];

			if($item_type == 6){
				$part_number_display  = $_REQUEST['part_number_freetext'][$key];
				$part_number_to_store = 0;
			} else {
				$part_number_display  = $_REQUEST['part_number'][$key];
				$part_number_to_store = $part_number_display;
			}
			
            if($quantity != ""){
            
                $existing = mysqli_num_rows(
                	mysqli_query($conn,
                		"SELECT id FROM purchase_order_items_mapping WHERE id = '$purchase_order_mapping_id'"
                	)
                );

                if($existing > 0){
					$sql2 = "quantity = '".$quantity."', ordering = '".$ordering."',
					         item_type = '".$item_type."', nominal_code = '".$nominal_code."', part_number = '".$part_number_to_store."',
					         description = '".$description."', unit_price = '".$unit_price."',
					         expected_date = '".$expected_date."', received = '".$received."',
					         total = '".$total."', status = '".$status."', updated_by = '$updated_by'";
					mysqli_query($conn,
						"UPDATE purchase_order_items_mapping SET ".$sql2." WHERE id = '$purchase_order_mapping_id'"
					);

					if($item_type == 6 && $part_number_display != ''){
						saveFreeTextPartNumber($conn, $purchase_order_mapping_id, $part_number_display, $updated_by);
					} else {
						deleteFreeTextPartNumber($conn, $purchase_order_mapping_id);
					}

					if($item_type != 6 && in_array($status, [3, 4, 5]) && !is_null($received)){
						mysqli_query($conn,
							"UPDATE inventory SET quantity_in_stock = quantity_in_stock + $received,
							 updated_by = '$updated_by' WHERE item_id = '$part_number_to_store'"
						);
					}

				} else {
					$sql1 = "po_id = '".$id."', quantity = '".$quantity."', ordering = '".$ordering."',
					         item_type = '".$item_type."', part_number = '".$part_number_to_store."',
					         description = '".$description."', unit_price = '".$unit_price."',
					         expected_date = '".$expected_date."', received = '".$received."',
					         status = '".$status."', total = '".$total."',
					         created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."'";
					mysqli_query($conn, "INSERT INTO purchase_order_items_mapping SET ".$sql1);
					$new_po_item_id = mysqli_insert_id($conn);

					if($item_type == 6 && $part_number_display != ''){
						saveFreeTextPartNumber($conn, $new_po_item_id, $part_number_display, $updated_by);
					}

					if($item_type != 6 && in_array($status, [3, 4, 5]) && !is_null($received)){
						mysqli_query($conn,
							"UPDATE inventory SET quantity_in_stock = quantity_in_stock + $received,
							 updated_by = '$updated_by' WHERE item_id = '$part_number_to_store'"
						);
					}
				}
			}
		}
	}

	$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;
	
	$_SESSION['info_message'] = "Purchase Order 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>

<!-- ============================================================
     CLONE TEMPLATE
     ============================================================ -->
<div class="col-sm-12 col-lg-12 col-12" id="new_purchase_order_div_to_clone" style="display:none;">
	<div class="row">
		<div class="col-sm-1"> 
			<label class="control-label">&nbsp;<em></em></label> 
			<input type="text" name="ordering[]" class="form-control" value="" placeholder="Item No." readonly>
		</div>
		<div class="col-sm-1"> 
			<div>
				<label class="control-label">&nbsp;<em></em></label> 
				<? $gsi->getItemTypeList("item_type[]","","100%",false,"form-control item_typeclone item_type","");?>	
			</div>
		</div>
		<div class="col-sm-2"> 
			<div>
				<label class="control-label">&nbsp;<em></em></label> 
				<? $gsi->getNominalCodeList("nominal_code[]","","100%",false,"form-control nominal_codeclone nominal_code","required");?>	
			</div>
		</div>
		<div class="col-sm-2"> 
			<label class="control-label">&nbsp;<em></em></label>
			<!-- Dropdown for normal item types -->
			<div class="part_number_select2_wrap">
				<? $gsi->getPartNumberList("part_number[]","","100%",false,"form-control part_numberclone part_number",""); ?>
			</div>
			<!-- Freetext input for item_type == 6, hidden by default -->
			<input type="text" name="part_number_freetext[]" class="form-control part_number_text" placeholder="Part Number" style="display:none;">
			<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">&nbsp;<em></em></label> 
			<input type="text" name="description[]" class="form-control description" value="" placeholder="Description"> 
		</div>
		<div class="col-sm-1">
			<label class="control-label">&nbsp;<em></em></label> 
			<input type="number" class="form-control quantity check_number_value only_num" name="quantity[]" value="" placeholder="QTY" autocomplete="off" required min="0">  
		</div>
		<div class="col-sm-1"> 
			<label class="control-label">&nbsp;<em></em></label> 
			<input type="text" name="unit_price[]" class="form-control unit_price check_number_value only_num" value="" placeholder="Unit Price" required>
		</div>
		<div class="col-sm-1"> 
			<label class="control-label">&nbsp;<em></em></label> 
			<input type="text" name="total[]" class="form-control total" value="" placeholder="Total Price" readonly>
		</div>
		<div class="col-sm-1"> 
			<label class="control-label">&nbsp;<em></em></label> 
			<input type="text" class="form-control datepicker expected_date" name="expected_date[]" value="" placeholder="DD-MM-YYYY" autocomplete="off" required>  
		</div>
		<div class="col-sm-1 hide"> 
			<label class="control-label">&nbsp;<em></em></label> 
			<input type="text" name="received[]" class="form-control received check_number_value only_num" value="" placeholder="Received">
		</div>
		<div class="col-sm-1 hide"> 
			<div>
				<label class="control-label">&nbsp;<em></em></label> 
				<? $gsi->getPurchaseStatusList("status[]","","100%",false,"form-control","",""); ?>
			</div>
		</div>
		<div class="col-sm-1" style="margin-top:35px;"> 
			<div class="custom-trash">
				<span class="fa fa-trash delete_purchase_order_item" alt="" style="cursor:pointer;color:red;"></span>
				<input type="hidden" class="each_row_total" value="">
				<input type="hidden" 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_purchase_order_details"){
				$query_string = str_ireplace("page=add", "page=view_purchase_order_details", $query_string);
			} else {
				$query_string = str_ireplace("page=add", "page=view", $query_string);
			}
			?>
			<button type="button" 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">
			<? 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>
			<? } ?>

			<div class="card">
				<form 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">Order Ref <em></em></label> 
							<input type="text" id="order_ref" name="order_ref" class="form-control"
							       value="<?php echo $order_ref;?>" placeholder="Order Ref" readonly>
						</div>
						<div class="form-group"> 
							<label class="control-label">Order Status<em></em></label> 
							<? $gsi->getPurchaseItemStatusList("order_status",$order_status,"100%",false,"form-control select2",""); ?>
						</div>
					  </div>
					  <div class="col-lg-6 col-sm-12">
						<div class="form-group"> 
							<label class="control-label">Supplier<em>*</em></label> 
							<? $gsi->getSuppliersListNew("supplier_id",$supplier_id,"100%",false,"form-control select2","required","",""); ?>
						</div>
						<div class="form-group"> 
							<label class="control-label">Deliver To Address<em></em></label> 
							<textarea id="deliver_to" name="deliver_to" class="form-control" rows="1"
							          placeholder="Deliver To Address" readonly><?php echo stripslashes($deliver_to);?></textarea>
						</div>
					  </div>
					  <div class="form-group col-lg-6 col-sm-12"> 
						<label class="control-label">ORDER NOTES<em></em></label> 
						<textarea id="order_notes" name="order_notes" class="form-control" rows="2"
						          placeholder="ORDER NOTES"><?php echo stripslashes($order_notes);?></textarea>
					  </div>
					</div>

					<div class="col-lg-12 col-sm-12 text-primary" style="margin-top:20px;">
						<h5>Purchase Order Items<hr style="height:2px;color:black;background-color:#a423a4;"></h5>
					</div>

<?php
	$final_total = 0;
	$po_item_mapping_query = "
		SELECT m.*,
		       CASE
		           WHEN m.item_type = 6 THEN IFNULL(fp.part_number, '')
		           ELSE m.part_number
		       END AS resolved_part_number
		FROM purchase_order_items_mapping m
		LEFT JOIN purchase_order_freetext_parts fp ON fp.po_item_id = m.id
		WHERE m.po_id = '".intval($id)."'
		ORDER BY m.ordering
	";
	$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;
		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'];
			$is_type6         = ($row_po_item_mapping['item_type'] == 6);
			$resolved_part_no = $row_po_item_mapping['resolved_part_number'];
?>
	<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"> 
				<label class="control-label">Item No.<em></em></label> 
				<input type="text" name="ordering[<?=$i;?>]" class="form-control"
				       value="<?php echo $row_po_item_mapping['ordering'];?>" placeholder="Item No." readonly>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Item Type<em></em></label>
				<? $gsi->getItemTypeList("item_type[$i]",$row_po_item_mapping['item_type'],"100%",false,"form-control select2 item_type","","");?>	
			</div>
			<div class="col-sm-2"> 
				<label class="control-label">Nominal Code<em>*</em></label>
				<? $gsi->getNominalCodeList("nominal_code[$i]",$row_po_item_mapping['nominal_code'],"100%",false,"form-control select2 nominal_code","required","");?>	
			</div>
			<div class="col-sm-2"> 
				<label class="control-label">Part Number<em></em></label>
				<!-- Normal dropdown (hidden for type 6) -->
				<div class="part_number_select2_wrap" <?= $is_type6 ? 'style="display:none;"' : '' ?>>
					<? $gsi->getPartNumberList(
						"part_number[$i]",
						$is_type6 ? '' : $resolved_part_no,
						"100%", false, "form-control select2 part_number", "", ""
					); ?>
				</div>
			
				<input type="text"
				       name="part_number_freetext[<?=$i;?>]"
				       class="form-control part_number_text"
				       placeholder="Part Number"
				       value="<?= $is_type6 ? htmlspecialchars($resolved_part_no) : '' ?>"
				       style="<?= $is_type6 ? 'display:block;' : 'display:none;' ?>">
			</div>
			<div class="col-sm-2"> 
				<label class="control-label">Description<em></em></label> 
				<input type="text" name="description[<?=$i;?>]" class="form-control description"
				       value="<?php echo $row_po_item_mapping['description'];?>" placeholder="Description">
			</div>
			<div class="col-sm-1">
				<label class="control-label">QTY<em>*</em></label> 
				<input type="number" 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 class="col-sm-1"> 
				<label class="control-label">Unit Price<em>*</em></label> 
				<input type="text" 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" required>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Total Price<em></em></label> 
				<input type="text" name="total[<?=$i;?>]" class="form-control total"
				       value="<?php echo $total;?>" placeholder="Total Price" readonly>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Expected Date<em></em></label>
				<input type="text" class="form-control datepicker expected_date"
				       name="expected_date[<?=$i;?>]"
				       value="<?php echo (isset($row_po_item_mapping['expected_date']) && $row_po_item_mapping['expected_date'] != "") ? utility::getFormatedDate($row_po_item_mapping['expected_date']) : ""; ?>"
				       placeholder="DD-MM-YYYY" autocomplete="off" required> 
			</div>
			<div class="col-sm-1 hide"> 
				<label class="control-label">Received<em></em></label> 
				<input type="text" name="received[<?=$i;?>]" class="form-control"
				       value="<?php echo $row_po_item_mapping['received'];?>" placeholder="Supplier Ref"> 
			</div>
			<div class="col-sm-1 hide"> 
				<label class="control-label">Status<em></em></label>
				<? $gsi->getPurchaseStatusList("status[$i]",$row_po_item_mapping['status'],"100%",false,"form-control","","");?>	
			</div>	
			<div class="col-sm-1" style="margin-top:35px;"> 
				<div class="custom-trash">
					<input type="hidden" name="purchase_order_mapping_id[<?=$i;?>]" value="<?php echo $row_po_item_mapping['id'];?>">
					<span class="fa fa-trash delete_purchase_order_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>

<?php
		$i++;
		$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"> 
				<label class="control-label">Item No.<em></em></label> 
				<input type="text" name="ordering[]" class="form-control" value="1" placeholder="Item No." readonly>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Item Type<em></em></label> 
				<? $gsi->getItemTypeList("item_type[]","","100%",false,"form-control select2 item_type",""); ?>
			</div>
			<div class="col-sm-2"> 
				<label class="control-label">Nominal Code<em>*</em></label> 
				<? $gsi->getNominalCodeList("nominal_code[]","","100%",false,"form-control select2 nominal_code","required"); ?>
			</div>
			
			<div class="col-sm-2"> 
				<label class="control-label">Part Number<em>*</em></label>
				<div class="part_number_select2_wrap">
					<? $gsi->getPartNumberList("part_number[]","","100%",false,"form-control select2 part_number","required"); ?>
				</div>
				<input type="text" name="part_number_freetext[]" class="form-control part_number_text"
				       placeholder="Part Number" style="display:none;">
				<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">Description<em></em></label> 
				<input type="text" name="description[]" class="form-control description" value="" placeholder="Description"> 
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">QTY<em>*</em></label> 
				<input type="number" name="quantity[]" class="form-control quantity" value="" placeholder="QTY" min="0" required> 
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Unit Price<em>*</em></label> 
				<input type="text" name="unit_price[]" class="form-control unit_price check_number_value only_num"
				       value="" placeholder="Unit Price" required>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Total Price<em></em></label> 
				<input type="text" name="total[]" class="form-control total" value="" placeholder="Total Price" readonly>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label">Expected Date<em>*</em></label> 
				<input type="text" class="form-control datepicker expected_date" name="expected_date[]"
				       value="" placeholder="DD-MM-YYYY" autocomplete="off" required>  
			</div>
			<div class="col-sm-1 hide"> 
				<label class="control-label">Received<em></em></label> 
				<input type="text" name="received[]" class="form-control received" value="" placeholder="Received">
			</div>
			<div class="col-sm-1 hide"> 
				<label class="control-label">Status<em></em></label> 
				<? $gsi->getPurchaseStatusList("status[]","","100%",false,"form-control","",""); ?>
			</div>
		</div>
	</div>

	<?php } ?>

				<div class="form-group col-sm-12 new_purchase_order_div_to_append">	
					<label class="add_one_more_new_purchase_order" 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 style="margin-top:6px;float:right;">
						Total Excluding Vat: <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><!-- /.card-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><!-- /.card -->
		</div>
	</div>
</section>
<script>
$(function(){

    $('#form1').submit(function(){
        $("#submit").attr("disabled", true);
        $('#page_load_div').show();
    });

    function applyItemTypeToggle($row, selectedVal) {
        var $selectWrap = $row.find('.part_number_select2_wrap');
        var $textInput  = $row.find('.part_number_text');
        var $selectEl   = $selectWrap.find('select');

        if (selectedVal == '6') {
            $selectWrap.hide();
            $selectEl.prop('disabled', true).prop('required', false);
            $textInput.show().prop('required', true);
        } else {
            $textInput.hide().prop('required', false);
            $selectEl.prop('disabled', false).prop('required', true);
            $selectWrap.show();
        }
    }

    $('.initial_row_for_po_items').each(function(){
        applyItemTypeToggle($(this), $(this).find('.item_type').val());
    });

    $("#form1").on("change", ".item_type", function(){
        applyItemTypeToggle($(this).closest('.initial_row_for_po_items'), $(this).val());
    });

$('.add_one_more_new_purchase_order').click(function(){
    var div_count      = parseInt($('.initial_row_for_po_items').last().attr("data-po_count")) + 1;
    var ordering_count = parseInt($('.initial_row_for_po_items').find("[name^='ordering']").last().val()) + 1;

    var $cloned = $('#new_purchase_order_div_to_clone')
        .clone(false)
        .addClass("initial_row_for_po_items")
        .attr("id", "new_po" + div_count)
        .attr("data-po_count", div_count)
        .attr("alt", div_count)
        .show();

    // Re-index all [] name attributes to [div_count]
    $cloned.find('[name]').each(function(){
        var oldName = $(this).attr('name');
        var newName = oldName.replace('[]', '[' + div_count + ']');
        $(this).attr('name', newName);
    });

    $cloned.find("[name='ordering[" + div_count + "]']").val(ordering_count);
    $cloned.find('.part_number_text').val('');

    // Remove any existing select2 markup on cloned selects before init
    $cloned.find('select').each(function(){
        $(this).removeClass('item_typeclone part_numberclone nominal_codeclone select2-hidden-accessible');
        $(this).removeAttr('data-select2-id');
    });

    // Remove stale select2 containers inside clone
    $cloned.find('.select2-container').remove();

    $('.new_purchase_order_div_to_append').before($cloned);

    // Now init Select2 and datepicker on the live DOM element
    var $live = $('#new_po' + div_count);

    $live.find('.part_number').attr("id", "part_number" + div_count).select2();
    $live.find('.item_type').attr("id", "item_type" + div_count).select2();
    $live.find('.nominal_code').attr("id", "nominal_code" + div_count).select2();

    $live.find(".datepicker").datepicker({
        changeMonth: true, changeYear: true,
        todayHighlight: true, format: "dd-mm-yyyy", autoclose: true
    });

    applyItemTypeToggle($live, $live.find('.item_type').val());

    // Also add a hidden purchase_order_mapping_id for new rows (value = empty = new insert)
    $live.find('.custom-trash').append(
        '<input type="hidden" name="purchase_order_mapping_id[' + div_count + ']" value="">'
    );
});

    $("#form1").on("change", ".part_number", function(){
        var $select     = $(this);
        var $row        = $select.closest('.initial_row_for_po_items');
        if (!$row.length) return;
        if ($row.find('.item_type').val() == '6') return;

        var part_number = $select.val();
        if (part_number == "") return;

        $.ajax({
            type: "POST",
            url: site_url + "/modules/purchase_order/index.php?page=ajax_actions&action=get_part_description_by_part_number",
            data: {'part_number': part_number},
            success: function(result){
                var r = jQuery.parseJSON(result);
                if (r.status == "success") {
                    $row.find(".description").val(r.product_description);
                }
            }
        });

        $.ajax({
            type: "POST",
            url: site_url + "/modules/purchase_order/index.php?page=ajax_actions&action=get_nominal_by_part_number",
            data: {'part_number': part_number},
            success: function(result){
                var r = jQuery.parseJSON(result);
                if (r.status == "success") {
                    $row.find('.nominal_code').val(r.nominal_code).trigger('change').trigger('select2:select');
                }
            }
        });
    });

    $("#form1").on("keyup change", ".quantity, .unit_price", function(){
        var $row       = $(this).closest('.initial_row_for_po_items');
        var qty        = parseFloat($row.find(".quantity").val());
        var unit_price = parseFloat($row.find(".unit_price").val());
        $row.find(".total").val((!isNaN(qty) && !isNaN(unit_price)) ? qty * unit_price : "");
        updateFinalTotal();
    });

    $(document).on('keydown', '.only_num', 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_purchase_order_item", function(){
        if (!confirm('Are you sure you want to delete?')) return;
        var po_item_mapping_id = $(this).attr("alt");

        if (po_item_mapping_id) {
            $('#load_new_po_item_' + po_item_mapping_id).show();
            $.ajax({
                type: "POST",
                url: site_url + "/modules/purchase_order/index.php?page=ajax_actions&action=delete_po_item",
                data: {'po_item_mapping_id': po_item_mapping_id},
                success: function(result){
                    var r = jQuery.parseJSON(result);
                    if (r.status === "success") {
                        $('#po_item_delete_done_' + po_item_mapping_id).show();
                        $('#load_new_po_item_' + po_item_mapping_id).hide();
                        $('#new_po' + po_item_mapping_id).remove();
                        updateFinalTotal();
                    }
                }
            });
        } else {
            $(this).closest(".initial_row_for_po_items").remove();
            updateFinalTotal();
        }
    });

    function updateFinalTotal(){
        var total = 0;
        $('.initial_row_for_po_items').each(function(){
            total += (parseFloat($(this).find(".quantity").val()) || 0)
                   * (parseFloat($(this).find(".unit_price").val()) || 0);
        });
        $('#final_total').html("&pound;" + total.toFixed(2));
        $('.final_total_remove').val(total);
    }

});
</script>