<?php 
include("includes/FCKeditor/fckeditor.php");
$file_name		= "index?page=view";
$form_action	= "insert";
$button_value 	= "Add";
$table_name 	= "po_invoices";
$id	 = "";
$vat = "";
$query_string = "";
$page_name      = "Add PO Invoices";
$invoice_date = date('d-m-Y');
/* $created_by = Admin::getAdminsById($_SESSION['user_id']);
$created_on = date("d-m-Y");  */
############################## START INSERT #################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){	
	utility::addslashesOnAllInput(array("query_string","quantity","status","stock_ref","supplier_ref","description","vat_value","unit_price","total","nominal_code","purchase_order_mapping_id"));
    
    $arolite_job_id 				= $_REQUEST['arolite_job_id']; 
    $purchase_order_id 				= $_REQUEST['purchase_order_id']; 
    $invoice_number 				= $_REQUEST['invoice_number']; 
	$invoice_date 		        	= utility::setFormatedDate($_REQUEST['invoice_date']);
	$due_date 		        	    = utility::setFormatedDate($_REQUEST['due_date']); 
    $total_inc_vat 			        = $_REQUEST['total_inc_vat']; 
    $is_inv_item_status		        = $_REQUEST['is_inv_item_status']; 
    $discrepancy_details		        = $_REQUEST['discrepancy_details']; 
    $discrepancy		        = $_REQUEST['discrepancy']; 
    
	$created_by						= $_SESSION['user_id'];
	$created_on						= date("Y-m-d H:i:s");
	$updated_by						= $_SESSION['user_id'];
    
	$sql = "arolite_job_id = '".$arolite_job_id."',purchase_order_id = '".$purchase_order_id."',discrepancy = '".$discrepancy."',discrepancy_details = '".$discrepancy_details."',invoice_number = '".$invoice_number."',invoice_date = '".$invoice_date."',due_date = '".$due_date."',total_inc_vat = '".$total_inc_vat."',is_inv_item_status = '".$is_inv_item_status."',created_by = '".$created_by."',created_on = '".$created_on."', updated_by = '".$updated_by."'";
	$sql= "INSERT INTO $table_name SET ".$sql;
	
    mysqli_query($conn,$sql);
	$po_invoices_id = mysqli_insert_id($conn);
	
	if(isset($_FILES['document_upload']['name']) && $_FILES['document_upload']['name'] !=""){
		$path = $_FILES['document_upload']['name'];
		$ext = pathinfo($path, PATHINFO_EXTENSION);
		if($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "JPG" || $ext == "JPEG" || $ext == "PNG" || $ext == "pdf" || $ext == "docx"){
			$digits = 5;
			$random_number = rand(pow(10, $digits-1), pow(10, $digits)-1);
			$uploaddir = 'po_invoices_documents/';
			$old_document	=	$uploaddir.$hidden_document_upload;	
			if(file_exists($old_document)){
				unlink($old_document);
			}
			$document_upload_array = explode(".",$_FILES['document_upload']['name']);
			$docu_ext = array_pop($document_upload_array);
			$doc_name = implode('.', $document_upload_array);
			//$document_upload = $id."_".$document_upload_array[0]."_".$random_number.".".$document_upload_array[1];
			$document_upload = $po_invoices_id."_".$doc_name."_".$random_number.".".$docu_ext;
			$document_upload = str_replace(" ","_",$document_upload);
			$uploadfile = $uploaddir . $document_upload;
			move_uploaded_file($_FILES['document_upload']['tmp_name'], $uploadfile);
			$sql= "UPDATE $table_name SET document_upload = '$document_upload' WHERE id = '$po_invoices_id' ";
			mysqli_query($conn,$sql);
			
			$_SESSION['info_message'] = "file added sucessfully";
		}else{
			$document_upload = $hidden_document_upload;
			$_SESSION['message'] = "Please upload only pdf/docx/jpg/jpeg/png";
		}
    }
	
	
	
	
	if(count($_REQUEST['quantity'])>0){
		foreach($_REQUEST['quantity'] as $key => $quantity){	
			$stock_ref	        = $_REQUEST['stock_ref'][$key];	
			$supplier_ref		 = $_REQUEST['supplier_ref'][$key];	
			$description	 	= $_REQUEST['description'][$key];
			$vat_value	     	= $_REQUEST['vat_value'][$key];	
			$unit_price			= $_REQUEST['unit_price'][$key];
			$total				= $_REQUEST['total'][$key];
			$status		        = $_REQUEST['status'][$key];
			$nominal_code		= $_REQUEST['nominal_code'][$key];
			$purchase_order_mapping_id		= $_REQUEST['purchase_order_mapping_id'][$key];
			
            if($quantity!="" ){				
				$sql1 = "po_invoices_id = '".$po_invoices_id."',purchase_order_id = '".$purchase_order_id."',purchase_order_mapping_id = '".$purchase_order_mapping_id."',quantity = '".$quantity."',description = '".$description."',vat_value = '".$vat_value."',unit_price = '".$unit_price."',total = '".$total."',nominal_code = '".$nominal_code."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
				$sql1= "INSERT INTO po_invoices_items_mapping SET ".$sql1;
				mysqli_query($conn,$sql1);
				
				/* $sql2= "UPDATE purchase_order_items_mapping SET status = '".$status."' WHERE id = '$purchase_order_mapping_id'AND status != '".$status."'";
					
				mysqli_query($conn,$sql2); */
				
			}
		}
	}	
	
	if($is_inv_item_status ==1){
	/////////////////// Job Finance Tab //////////////////////	
	$total = 0;
	$grand_total_wo_vat = 0;
	$sql_for_po_inv_mapping = "SELECT id,quantity,total FROM po_invoices_items_mapping WHERE po_invoices_id = '$po_invoices_id' ";
	$result_for_po_inv_mapping = mysqli_query($conn,$sql_for_po_inv_mapping);
	if(mysqli_num_rows($result_for_po_inv_mapping)){
		while($row_for_PO_inv_mapping = mysqli_fetch_array($result_for_po_inv_mapping)){
			$total = $total + $row_for_PO_inv_mapping["total"];
		}
		$grand_total_wo_vat = $total+$grand_total_wo_vat; 
	}
	
	/* $check_finance_qry = "SELECT * FROM arolite_job_finance WHERE arolite_job_id = '".$arolite_job_id."' ";
	$check_finance_sql = mysqli_query($conn,$check_finance_qry);
	if(mysqli_num_rows($check_finance_sql) > 0){
		
		$finance_row = mysqli_fetch_array($check_finance_sql);
		$finance_id = $finance_row['id'];
		
		$update_finance_sql= "UPDATE arolite_job_finance SET costs_parts = '".$grand_total_wo_vat."', updated_by = '".$updated_by."' WHERE id = '".$finance_id."'";	
		mysqli_query($conn,$update_finance_sql);
	
	}else{
		if($arolite_job_id !=""){
			$sql_insert = "arolite_job_id = '".$arolite_job_id."', costs_parts = '".$grand_total_wo_vat."',created_by = '".$created_by."',created_on = '".$created_on."', updated_by = '".$updated_by."'";
			$sql_insert= "INSERT INTO arolite_job_finance SET ".$sql_insert;
			mysqli_query($conn,$sql_insert);
		}
	} */
	/////////////////// Job Finance Tab //////////////////////
	}
	
	$_SESSION['info_message'] = "PO Invoices added sucessfully";
	header("Location: $file_name");
    exit();
}
########################################## END INSERT ##########################################

########################################## START EDIT ##########################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];
	$po_invoices_id = utility::app_crypt($_REQUEST['po_invoices_id'],'d');
	if($id != $po_invoices_id){
		die("Invaild URL");
	}
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit PO Invoices";
	$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);
	
    $arolite_job_id					= $row_edit['arolite_job_id'];
    $purchase_order_id				= $row_edit['purchase_order_id'];
    $invoice_number			        = $row_edit['invoice_number'];
    $invoice_date					= $row_edit['invoice_date']; 
	$due_date						= $row_edit['due_date'];
    $total_inc_vat					= $row_edit['total_inc_vat'];
    $is_inv_item_status				= $row_edit['is_inv_item_status'];
	$document_upload		    	= $row_edit['document_upload']; 
    $discrepancy_details		        = $row_edit['discrepancy_details']; 
    $discrepancy		        = $row_edit['discrepancy']; 
	
	$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","quantity","status","stock_ref","supplier_ref","description","vat_value","unit_price","total","nominal_code","po_invoices_mapping_id","purchase_order_mapping_id"));
	$id							= $_REQUEST['id'];
	$arolite_job_id 			= $_REQUEST['arolite_job_id']; 
	$purchase_order_id 			= $_REQUEST['purchase_order_id']; 
    $invoice_number 		    = $_REQUEST['invoice_number']; 
	$invoice_date 	        	= utility::setFormatedDate($_REQUEST['invoice_date']);
	$due_date 	   		     	= utility::setFormatedDate($_REQUEST['due_date']); 
    $total_inc_vat 				= $_REQUEST['total_inc_vat']; 
    $is_inv_item_status			= $_REQUEST['is_inv_item_status'];
    $discrepancy		        = $_REQUEST['discrepancy']; 
    $discrepancy_details		        = $_REQUEST['discrepancy_details']; 	
	
	$updated_by					= $_SESSION['user_id'];
	$hidden_document_upload 	= $_REQUEST['hidden_document_upload'];
	if(isset($_FILES['document_upload']['name']) && $_FILES['document_upload']['name'] !=""){
		$path = $_FILES['document_upload']['name'];
		$ext = pathinfo($path, PATHINFO_EXTENSION);
		if($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "JPG" || $ext == "JPEG" || $ext == "PNG" || $ext == "pdf" || $ext == "docx"){
			$digits = 5;
			$random_number = rand(pow(10, $digits-1), pow(10, $digits)-1);
			$uploaddir = 'po_invoices_documents/';
			$old_document	=	$uploaddir.$hidden_document_upload;	
			if(file_exists($old_document)){
				unlink($old_document);
			}
			$document_upload_array = explode(".",$_FILES['document_upload']['name']);
			$docu_ext = array_pop($document_upload_array);
			$doc_name = implode('.', $document_upload_array);
			//$document_upload = $id."_".$document_upload_array[0]."_".$random_number.".".$document_upload_array[1];
			$document_upload = $id."_".$doc_name."_".$random_number.".".$docu_ext;
			$document_upload = str_replace(" ","_",$document_upload);
			$uploadfile = $uploaddir . $document_upload;
			move_uploaded_file($_FILES['document_upload']['tmp_name'], $uploadfile);
			
			$_SESSION['info_message'] = "file updated sucessfully";
		}else{
			$document_upload = $hidden_document_upload;
			$_SESSION['message'] = "Please upload only pdf/docx/jpg/jpeg/png";
		}
    }else{
		$_SESSION['info_message'] = "file updated sucessfully";
		$document_upload = $hidden_document_upload;
	}
	
	$sql = "arolite_job_id = '".$arolite_job_id."',purchase_order_id = '".$purchase_order_id."',discrepancy = '".$discrepancy."',discrepancy_details = '".$discrepancy_details."',invoice_number = '".$invoice_number."',invoice_date = '".$invoice_date."',due_date = '".$due_date."',total_inc_vat = '".$total_inc_vat."',is_inv_item_status = '".$is_inv_item_status."',document_upload = '".$document_upload."',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){
			$quantity			= $_REQUEST['quantity'][$key];	
			$stock_ref			= $_REQUEST['stock_ref'][$key];	
			$supplier_ref		= $_REQUEST['supplier_ref'][$key];	
			$description	 	= $_REQUEST['description'][$key];	
			$vat_value	 	    = $_REQUEST['vat_value'][$key];
			$unit_price			= $_REQUEST['unit_price'][$key];
			$po_invoices_mapping_id	= $_REQUEST['po_invoices_mapping_id'][$key];
			$total				= $_REQUEST['total'][$key];
			$status		        = $_REQUEST['status'][$key];
			$nominal_code       = $_REQUEST['nominal_code'][$key];
			
            if($quantity!="" ){	
                if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM po_invoices_items_mapping WHERE id = '$po_invoices_mapping_id' ")) > 0){
					$sql2= "UPDATE po_invoices_items_mapping SET quantity = '".$quantity."',description = '".$description."',vat_value = '".$vat_value."',unit_price = '".$unit_price."',total = '".$total."',status = '".$status."',updated_by = '$updated_by' WHERE id = '$po_invoices_mapping_id' ";
					mysqli_query($conn,$sql2);
					
					/* $sql_po_item = "UPDATE purchase_order_items_mapping SET status = '".$status."' WHERE id = '$purchase_order_mapping_id' AND status != '".$status."'";
					
				    mysqli_query($conn,$sql_po_item); */
				}else{
					$created_by = $_SESSION['user_id'];
					$created_on = date("Y-m-d H:i:s");
					
					$sql1 = "po_invoices_id = '".$id."',purchase_order_id = '".$purchase_order_id."',purchase_order_mapping_id = '".$purchase_order_mapping_id."',quantity = '".$quantity."',description = '".$description."',vat_value = '".$vat_value."',unit_price = '".$unit_price."',total = '".$total."',nominal_code = '".$nominal_code."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
					$sql1= "INSERT INTO po_invoices_items_mapping SET ".$sql1;
					
					mysqli_query($conn,$sql1);
				}
			}
		}
	} 
/*	if($is_inv_item_status ==1){
	/////////////////// Job Finance Tab //////////////////////
	$po_inv_id = $id;
	$total = 0;
	$grand_total_wo_vat = 0;
	$sql_for_po_inv_mapping = "SELECT id,quantity,total FROM po_invoices_items_mapping WHERE po_invoices_id = '$po_inv_id' ";
	$result_for_po_inv_mapping = mysqli_query($conn,$sql_for_po_inv_mapping);
	if(mysqli_num_rows($result_for_po_inv_mapping)){
		while($row_for_PO_inv_mapping = mysqli_fetch_array($result_for_po_inv_mapping)){
			$total = $total + $row_for_PO_inv_mapping["total"];
		}
		$grand_total_wo_vat = $total+$grand_total_wo_vat; 
	}
	
	$check_finance_qry = "SELECT * FROM arolite_job_finance WHERE arolite_job_id = '".$arolite_job_id."' ";
	$check_finance_sql = mysqli_query($conn,$check_finance_qry);
	if(mysqli_num_rows($check_finance_sql) > 0){
		
		$finance_row = mysqli_fetch_array($check_finance_sql);
		$finance_id = $finance_row['id'];
		
		$update_finance_sql= "UPDATE arolite_job_finance SET costs_parts = '".$grand_total_wo_vat."', updated_by = '".$updated_by."' WHERE id = '".$finance_id."'";	
		mysqli_query($conn,$update_finance_sql);
	
	}else{
		if($arolite_job_id !=""){
			$sql_insert = "arolite_job_id = '".$arolite_job_id."', costs_parts = '".$grand_total_wo_vat."',created_by = '".$created_by."',created_on = '".$created_on."', updated_by = '".$updated_by."'";
			$sql_insert= "INSERT INTO arolite_job_finance SET ".$sql_insert;
			mysqli_query($conn,$sql_insert);
		}
	}
	/////////////////// Job Finance Tab //////////////////////
	}*/
	
	$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_invoices_id = urlencode(utility::app_crypt($id,'e'));
	$_SESSION['info_message'] = "PO Invoices updated sucessfully";
	
    header("Location: $file_name$query_string");
    exit();
}
################################# END UPDATE ######################################## 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}

input[type="radio"]{
	top:4px;
	position:relative;
}
.custom-trash{
	float: right;
    position: absolute;
    right: 21px;
    top: 40px;
}
.nominal_code{
	width: 54%;
}
</style>
<div class="col-sm-12 col-lg-12 col-12" id="new_po_invoices_item_div_to_clone" style="display:none;">
	<div class="row">
		<div class="col-sm-1"> 
		
		</div>
		<div class="col-sm-1"> 
		
		</div>
		<div class="col-sm-1"> 
		
		</div>
		<div class="col-sm-1"> 
		
		</div>
		<div class="col-sm-1" style="border-right:3px solid black;"> 
		
		</div>
		<div class="col-sm-1"> 
			<label class="control-label" for="Ordering">&nbsp;<em></em></label> 
			<input type="text" class="form-control ordering" id="ordering" name="ordering[]" value="" placeholder="Ordering" autocomplete="off" readonly>  
		</div>
		
		<div class="col-sm-1"> 
			<label class="control-label" for="Description">&nbsp;<em></em></label> 
			<input type="text" id="comments" name="description[]" class="form-control" value="" placeholder="Description"> 
		</div>
		<div class="col-sm-1"> 
			<label class="control-label" for="Quantity">&nbsp;<em></em></label> 
			<input type="number" class="form-control quantity check_number_value check_negative_value" id="quantity" name="quantity[]" value="" placeholder="Quantity" autocomplete="off" >  
		</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 check_negative_value" value="" placeholder="Unit Price">
			</div>
		</div>
		<div class="col-sm-1"> 
		<label class="control-label" for="Total">&nbsp;<em></em></label> 
			<div class=""> 
				<input type="text" id="total" name="total[]" class="form-control total" value="" placeholder="Total" readonly>
			</div>
		</div>
		<div class="col-sm-1"> 
			 <label class="control-label" for="VAT Value">&nbsp;<em></em></label> 
			 <input type="text" id="vat_value" name="vat_value[]" class="form-control vat_value check_number_value check_negative_value" value="" placeholder="VAT Value"> 
		</div>
		<div class="col-sm-1"> 
			 <label class="control-label" for="Nominal Code">&nbsp;<em></em></label> 
			 <input type="text" id="nominal_code" name="nominal_code[]" class="form-control nominal_code" value="5000" placeholder="Nominal Code"> 
			 <div class="custom-trash ">
				<label class="control-label" style="font-color:red;"></label> 
				<span class="fa fa-trash delete_po_invoices_item" alt="" style="cursor:pointer;"></span>
			</div>
		</div>
	</div>
</div>
<section class="content-header">
	<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_po_invoices_details"){
				$query_string = str_ireplace("page=add", "page=view_po_invoices_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-12 col-sm-12">
				    <div class="form-group">
						<div class="row" style="padding: 0;">
						<div class="col-6">	
							<label class="control-label" for="Purchase Order No">Purchase Order Ref<em></em></label> 
							<div class="po_div"> 
								<?php 
									$gsi->getPurchaseOrderList("purchase_order_id",$purchase_order_id,"100%",false,"form-control select2",""); 
								?>	
								
							</div> 
						</div>
				    <div class="col-6">	
						<label class="control-label" for="Invoice Date">Invoice Date<em></em></label> 
						<div class=""> 
							<input type="text" class="form-control datepicker" id="invoice_date" name="invoice_date" value="<?php echo (isset($invoice_date) && $invoice_date !="") ? utility::getFormatedDate($invoice_date) : "";?>" placeholder="DD-MM-YYYY" autocomplete="off">
						</div> 
					</div>
					 
					
					</div>
					</div>
					<div class="form-group">
					<div class="row" style="padding: 0;">
					<div class="col-6">
						<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">
						</div>	
					</div>
					<div class="col-6">	
						<label class="control-label" for="Due Date">Due Date<em></em></label> 
						<div class=""> 
							<input type="text" class="form-control datepicker" id="due_date" name="due_date" value="<?php echo (isset($due_date) && $due_date !="") ? utility::getFormatedDate($due_date) : "";?>" placeholder="DD-MM-YYYY" autocomplete="off">
						</div> 
					</div>
					<div class="col-6">	
						<label class="control-label" for="Total Inc VAT">Total Inc VAT<em></em></label> 
						<div class=""> 
							<input type="number" id="total_inc_vat" name="total_inc_vat" class="form-control" value="<?php echo $total_inc_vat;?>" placeholder="Total Inc VAT">
						</div> 
					</div>
					<div class="col-6 ">	
						<label for="File Upload" class="control-label">File Upload<em></em></label><br/>
							<span style="font-weight:bold;color:#ff0000;">(Please upload only pdf/docx/jpg/jpeg/png)</span><br/>
							<input type="file" name="document_upload" id="document_upload"/>
							<div style="">
							<?
							$dir = "po_invoices_documents/";
							if(isset($_REQUEST['action']) && $_REQUEST['action']=='edit'){
							 if (is_file($dir.$document_upload)) {
									//$image_path ='<img style="width:100px;border:1px solid #777" src="../'.$dir.$document_upload.'">';
									//<br><a id="delete_image" href="">Delete</a>
									$ext = pathinfo($document_upload, PATHINFO_EXTENSION);
									if($ext == "jpg" || $ext == "jpeg" || $ext == "png"){
										$image_path ='<a href="../'.$dir.$document_upload.'" target="_blank"><img style="width:100px;border:1px solid #777" src="../'.$dir.$document_upload.'"></a>';
									}else if($ext == "pdf"){
										$image_path ='<a href="../'.$dir.$document_upload.'" target="_blank"><span title="'.$document_upload.'">'.utility::ellipsis($document_upload,20).'</span></a>';
									}else if($ext == "doc" || $ext == "docx" || $ext == "eml"){
										$image_path = '<a href="index?page=file_download&po_invoices_id='.$id.'" target="_blank">'.$document_upload.'</a>';
									}
								}else{
									$image_path ='<img style="width:100px;border:1px solid #777" src="../'.$dir.'no-image.gif">';	
								}
								echo $image_path;
							}?>
							<input type="hidden" name="hidden_document_upload" value="<? echo $document_upload;?>">
							</div>
					</div>
					</div>
					</div>
				</div>	
				<div class="col-lg-12 col-sm-12 text-primary" style="margin-top:20px;">
					<div class="row">
						<div class="col-sm-5">
							<h5>PO Items</h5>
						</div>
						
						<div class="col-sm-7">
							<h5>Invoice Items</h5>
						</div>
					</div>
					<hr style='height:2px;color:black; background-color:black;'>
				</div>
<?		$final_total=0;$total_vats_value=0;
		$po_inv_item_mapping_query = "SELECT * FROM po_invoices_items_mapping WHERE po_invoices_id='".$id."'";
		$po_inv_item_mapping_sql=mysqli_query($conn,$po_inv_item_mapping_query);
		$po_item_mapping_count=mysqli_num_rows($po_inv_item_mapping_sql);
		if($po_item_mapping_count>0){
			$i = 0;
			$j = 0;
			while($row_po_item_mapping = mysqli_fetch_array($po_inv_item_mapping_sql)){
				
				
			$po_item_mapping_query = "SELECT * FROM purchase_order_items_mapping WHERE po_id='".$purchase_order_id."' AND id='".$row_po_item_mapping['purchase_order_mapping_id']."' ORDER BY ordering ASC";
			$po_item_mapping_sql=mysqli_query($conn,$po_item_mapping_query);
			$po_item_mapping_result=mysqli_num_rows($po_item_mapping_sql);
			if($po_item_mapping_result>0){
				$po_item_data = mysqli_fetch_array($po_item_mapping_sql);
				$po_item_description = $po_item_data['description'];
				$po_item_quantity = $po_item_data['quantity'];
				$po_item_unit_price = $po_item_data['unit_price'];
				$po_item_total = $po_item_data['total'];
				$item_div_hide = "";
			}else{
				$po_item_description = "";
				$po_item_quantity = "";
				$po_item_unit_price = "";
				$po_item_total = "";
				$item_div_hide = "hide";
			}
	?>
	<div class="col-sm-12 col-lg-12 col-12 initial_row_for_po_invoices_items" id="new_po_inv_item_<?=$row_po_item_mapping['id'];?>" data-po_inv_item_count="<?=$row_po_item_mapping['id'];?>" alt="<?=$j;?>">
		<div class="row">
			<div class="col-sm-1"> 
				<label class="control-label <?=$item_div_hide;?>" for="Ordering">Sr No.<em></em></label><br/>
				<div class=" <?=$item_div_hide;?>"> 
					<?php echo $j+1;?>
				</div>
			</div>
			
			<div class="col-sm-1"> 
				<label class="control-label <?=$item_div_hide;?>" for="Description">Description<em></em></label> <br/>
				<?php echo $po_item_description;?>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label <?=$item_div_hide;?>" for="Quantity">Quantity<em></em></label> <br/>
				<?php echo $po_item_quantity;?>
			</div>
			<div class="col-sm-1"> 
				<label class="control-label <?=$item_div_hide;?>" for="Unit Price">Unit Price<em></em></label> <br/>
				<div class=" <?=$item_div_hide;?>"> 
					<?php echo $po_item_unit_price;?>
				</div>
			</div>
			<div class="col-sm-1" style="border-right:3px solid black;"> 
				<label class="control-label <?=$item_div_hide;?>" for="Total">Total<em></em></label> 
				<div class=" <?=$item_div_hide;?>"> 
					<?php echo $po_item_total;?>
				</div>
			</div>
			<div class="col-sm-1"> 
				 <label class="control-label" for="Ordering">Sr No.<em></em></label> 
				 <input type="text" id="ordering" name="ordering[<?=$i;?>]" class="form-control ordering" value="<?php echo $j+1;?>" placeholder="Sr No." readonly>
			</div>
			
			<div class="col-sm-1"> 
				 <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"> 
				<label class="control-label" for="Quantity">Quantity<em></em></label> 
				<div class=""> 
					<input type="text" id="quantity" name="quantity[<?=$i;?>]" class="form-control quantity check_number_value check_negative_value" value="<?php echo $row_po_item_mapping['quantity'];?>" placeholder="Quantity">
				</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 check_negative_value" 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">Total<em></em></label> 
				 <div class=""> 
					<input type="text" id="total" name="total[<?=$i;?>]" class="form-control total" value="<?php echo $row_po_item_mapping['total'];?>" placeholder="Total" readonly>
				</div>
			</div>
			<div class="col-sm-1"> 
				 <label class="control-label" for="VAT Value">VAT Value<em></em></label> 
				 <input type="text" id="vat_value" name="vat_value[<?=$i;?>]" class="form-control vat_value check_number_value check_negative_value" value="<?php echo $row_po_item_mapping['vat_value'];?>" placeholder="VAT Value">
			</div>
			<div class="col-sm-1 hide"> 
				 <label class="control-label" for="Nominal Code">Nominal Code<em></em></label> 
				 <input type="text" id="nominal_code" name="nominal_code[<?=$i;?>]" class="form-control nominal_code" value="<?php echo $row_po_item_mapping['nominal_code'];?>" placeholder="Nominal Code">
				 
				 <div class="custom-trash">
					<label class="control-label" style="font-color:red;"></label>
					<input type="hidden" name="po_invoices_mapping_id[<?=$i;?>]" value="<?php echo $row_po_item_mapping['id'];?>">
					<span class="fa fa-trash delete_po_invoices_item" style="cursor:pointer;" alt="<?php echo $row_po_item_mapping['id'];?>" data-item_amount="<?php echo $row_po_item_mapping['total'];?>"></span>
					<i class="fas fa-sync-alt fa-spin" id="load_new_po_inv_item_<?=$row_po_item_mapping['id'];?>" style="font-size: 20px;display:none;"></i>
					<i class="fa fa-check" id="po_invoices_item_delete_done_<?=$row_po_item_mapping['id'];?>" style="color:#bad23a;font-size: 20px;display:none;"></i>
				</div>
			</div>
		</div>
	</div>
	
	
	<?php
				$i++;
				$j++;

				$item_total = $row_po_item_mapping["quantity"] * $row_po_item_mapping["unit_price"];

				$total += $item_total;
				$item_vat_amount = ($item_total * 20 / 100);
				$final_total = $total ;
				$total_vats_value += $item_vat_amount;
				$grand_total = $total + $total_vats_value;
				?>


		<?}}else{?>
	<div id="po_time_fetch_div" class="col-sm-12 col-lg-12 col-12">
	
		<div class='col-lg-10 text-center' style='padding: 7px 0px;font-style:italic;color: #F44336;'><b>Please Select Purchase Order.</b></div>
	</div>
	<?}?>
			<div class="col-sm-6 new_po_invoice_item_div_to_append hide">	
		<label class="add_one_more_new_po_invoice_item text-primary" style="margin-left:0%;cursor:pointer;float:right;"><span class="fa fa-plus text-primary"></span>Add More</label>
	</div>
	
			
					<div class="col-sm-12">	
						<label class="" style="margin-top:6px;float: right;">Final Total: <span id="final_total">&pound;<?=number_format($final_total,2);?></span></label>
						
					</div>
					<div class="col-sm-12">	
						<label class="" style="margin-top:6px;float: right;">VAT Total: <span id="total_vat_value">&pound;<?=number_format($total_vats_value,2);?></span></label>
						
					</div>
					<div class="col-sm-12">	
						<label class="" style="margin-top:6px;float: right;">Grand Total: <span id="grand_total">&pound;<?=number_format($grand_total,2);?></span></label>
						
						<input type="hidden" class="grand_total_remove" value="<?php echo $grand_total;?>">
					</div>
					
					<div class="col-lg-12 col-sm-12">
						<div class="form-group"> 
							<label class="control-label" for="">&nbsp;<em></em></label> 
							<div class="row" style="padding: 0;"> 
								<div class="col-12">
									<label class="control-label" for="">All Items Matching</label>&nbsp;&nbsp;
									<input type="radio" class="All_Items_Matching" id="is_inv_item_status" name="is_inv_item_status" value="1"  <?php echo ($is_inv_item_status ==1) ? 'checked':''; ?>>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
									
									<label class="control-label" for="">Items Not Matching</label> 
									&nbsp;<input type="radio" class="Items_Not_Matching" id="is_inv_item_status" name="is_inv_item_status" value="2"  <?php echo ($is_inv_item_status ==2) ? 'checked':''; ?>>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
									
									<label class="control-label" for="">Not All Items Received</label> 
									&nbsp;<input type="radio" class="Not_All_Items_Received" id="is_inv_item_status" name="is_inv_item_status" value="3"  <?php echo ($is_inv_item_status ==3) ? 'checked':''; ?>>
								</div>
							</div>
						</div>
						<!-- Discrepancy Selection -->
						<div id="discrepancy_section" class="row" style="display: none; margin-top: 10px;">
							<div class="col-12">
								<label>Discrepancy:</label>
								<label class="ms-2">
									&nbsp;Yes <input type="radio" name="discrepancy" value="1" id="discrepancy_yes"> 
								</label>
								<label class="ms-4">
									&nbsp; No <input type="radio" name="discrepancy" value="2" id="discrepancy_no">
								</label>
							</div>

							<!-- Reason Input -->
							<div class="col-6" id="reason_box" style="display: none;">
							<label class="control-label" for="">Reason</label> 
								<textarea id="discrepancy_details" name="discrepancy_details" class="form-control" value="" rows="2" placeholder="Reason " ><?php echo stripslashes($discrepancy_details);?></textarea>
							</div>
						</div>

					</div>
					

				</div><!-- /.row -->
			</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(){
	        var savedDiscrepancy = "<?php echo $discrepancy; ?>"; // 1 for Yes, 2 for No
			var savedReason = "<?php echo stripslashes($discrepancy_details); ?>";

			// Pre-select radio button and show/hide reason box based on database values
			if (savedDiscrepancy === "1") {
				$("#discrepancy_section").show();
				$("#discrepancy_yes").prop("checked", true);
				$("#reason_box").show();
			} else if (savedDiscrepancy === "2") {
				$("#discrepancy_section").hide();
				$("#discrepancy_no").prop("checked", true);
				$("#reason_box").hide();
			}
	$('#form1').submit(function(){
		var total_inc_vat = $("#total_inc_vat").val();
		var grand_total = $(".grand_total_remove").val();
		if(total_inc_vat != grand_total){
			alert("Total Inc VAT and Item Totals are not matching. Please review.");
			return false;
		}
		//$(this).addClass('disabled');
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
	});
	
	
	$("#form1").on("change","#arolite_job_id",function(){
		var arolite_job_id = $(this).val();
		if(arolite_job_id != ""){
			$("#po_dropdown_load").show();
			var form_data   = {'arolite_job_id':arolite_job_id};
			$.ajax({
				async: true,
				type: "POST",
				url: site_url+"/modules/po_invoices/index.php?page=ajax_actions&action=get_PO_by_arolite_job_id",
				data: form_data,
				success: function(result){  
					if(result){
						$(".po_div").html(result);
						$(".po_div  .select2").select2();
						
						$("#po_dropdown_load").hide();
					}
				}
			});
		}else{
			$(".po_div").html("Please Select Call No.");
		}
	});
	
	$('.add_one_more_new_po_invoice_item').click(function() {		
		$('#new_po_invoices_item_div_to_clone').show();		
		var div_count = $('.initial_row_for_po_invoices_items').last().attr("data-po_inv_item_count");
		div_count++;
		
		var alt_count = $('.initial_row_for_po_invoices_items').last().attr("alt");
		alt_count++;
		
		var ordering_count = $('.initial_row_for_po_invoices_items').find("#ordering").last().attr("value")
		ordering_count++;
		var cloned_div = $('#new_po_invoices_item_div_to_clone').clone().addClass("initial_row_for_po_invoices_items").attr("id","new_po_inv_item_"+div_count).attr("data-po_inv_item_count",div_count);		
		$('.new_po_invoice_item_div_to_append').before(cloned_div);	
		$('#new_po_invoices_item_div_to_clone').hide();	

		$('#new_po_inv_item_'+div_count).attr("alt",alt_count);
		$('#new_po_inv_item_'+div_count).children().find("#ordering").attr("value",ordering_count);
	});
	
	
	$("#form1").on("keyup change", ".quantity, .unit_price, .vat_value", function () {
			var div_no = $(this).closest("[data-po_inv_item_count]").attr("data-po_inv_item_count");
                    
			var qty = $('#new_po_inv_item_' + div_no).find(".quantity").val();
			var po_item_quantity_hidden = $('#new_po_inv_item_' + div_no).find(".po_item_quantity_hidden").val();

			var unit_price = $('#new_po_inv_item_' + div_no).find(".unit_price").val();
			var po_item_up_hidden = $('#new_po_inv_item_' + div_no).find(".po_item_up_hidden").val();

			if (qty == po_item_quantity_hidden && unit_price == po_item_up_hidden) {
				$(".All_Items_Matching").prop('checked', true);
				$("#discrepancy_section").hide(); // Hide discrepancy section
			} else {
				$(".Items_Not_Matching").prop('checked', true);
				$("#discrepancy_section").show(); // Show discrepancy section
				$("#discrepancy_yes").prop("checked", true);
				$("#reason_box").show();
			}

			// Assuming qty and unit_price are already defined
				var total = parseFloat(qty * unit_price);

				if (!isNaN(total) && total > 0) {
					var vat = total * 0.2; // Calculate 20% VAT
					$('#new_po_inv_item_' + div_no).find(".vat_value").val(vat); // Set the VAT value in the box
				} else {
					$('#new_po_inv_item_' + div_no).find(".vat_value").val(0); // Set VAT to 0 if total is invalid
				}

			if (!isNaN(total)) {
				total = total.toFixed(2);
				$('#new_po_inv_item_' + div_no).find(".total").val(total);
			}

			var final_total = 0;
			$('.total').each(function () {
				var total = $(this).val();
				if (!isNaN(total) && total !== "") {
					final_total += parseFloat(total);
				}
			});

			$('#final_total').html("&pound;" + final_total.toFixed(2));

			var total_vat_value = 0;
			$('.vat_value').each(function () {
				var vat = $(this).val();
				if (!isNaN(vat) && vat !== "") {
					total_vat_value +=parseFloat(vat);
				}
			});

			$('#total_vat_value').html("&pound;" + total_vat_value.toFixed(2));

			var total_vat_plus_total = final_total + total_vat_value;

			if (!isNaN(total_vat_plus_total)) {
				$('#grand_total').html("&pound;" + total_vat_plus_total.toFixed(2));
				$('#total_inc_vat').val(total_vat_plus_total);
				$('.grand_total_remove').val(total_vat_plus_total);
			}
		});

		$("#discrepancy_section").on("change", "input[name='discrepancy']", function () {
			if ($(this).val() === "1") {
				$("#reason_box").show(); // Show input box
			} else {
				$("#reason_box").hide(); // Hide input box
			}
		});


	$("#form1").on("click", ".delete_po_invoices_item",function() {
	    if(confirm('Are you sure! You want to delete')){
			var grand_total = 0;
			var vat_amount = 0;
			if($(this).attr("alt") != ""){
				
				var po_invoices_items_mapping_id = $(this).attr("alt");
				var one_item_amount = $(this).attr("data-item_amount");
				$('#load_new_po_inv_item_'+po_invoices_items_mapping_id).show();
				var form_data   = {'po_invoices_items_mapping_id':po_invoices_items_mapping_id};       
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/po_invoices/index.php?page=ajax_actions&action=delete_po_invoices_item",
					data: form_data,
					success: function(result){    
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$('#po_invoices_item_delete_done_'+po_invoices_items_mapping_id).show();
							$('#load_new_po_inv_item_'+po_invoices_items_mapping_id).hide();
							
							
							
							
							setTimeout(function() {
								$('#po_invoices_item_delete_done_'+po_invoices_items_mapping_id).hide();
								$('#new_po_inv_item_'+po_invoices_items_mapping_id).remove();
								//location.reload();
								
								
								var total_vat_value = 0;
								$('.vat_value').each(function(){
									var vat_value = $(this).val();
									if(!isNaN(vat_value) && vat_value != ""){
										total_vat_value = parseFloat(total_vat_value) + parseFloat(vat_value);
										$('#total_vat_value').html("&pound;"+total_vat_value.toFixed(2));
									}
								});
								
								var final_total = 0;
								$('.total').each(function(){
									var total = $(this).val();
									if(!isNaN(total) && total != ""){
										final_total = parseFloat(final_total) + parseFloat(total);
										$('#final_total').html("&pound;"+final_total.toFixed(2));
									}
								});
								
								total_vat_plus_total  = final_total + total_vat_value;
								if(!isNaN(total_vat_plus_total) && total_vat_plus_total != ""){
									$('#grand_total').html("&pound;"+total_vat_plus_total.toFixed(2));
									$('#total_inc_vat').val(total_vat_plus_total.toFixed(2));
									$('.grand_total_remove').val(total_vat_plus_total);
								}
								
							},1000);
						}
					}
				});
			}else{
				
				
				$(this).parent().parent().parent().parent().remove();
				
				var total_vat_value = 0;
				$('.vat_value').each(function(){
					var vat_value = $(this).val();
					if(!isNaN(vat_value) && vat_value != ""){
						total_vat_value = parseFloat(total_vat_value) + parseFloat(vat_value);
						$('#total_vat_value').html("&pound;"+total_vat_value.toFixed(2));
					}
				});
				
				var final_total = 0;
				$('.total').each(function(){
					var total = $(this).val();
					if(!isNaN(total) && total != ""){
						final_total = parseFloat(final_total) + parseFloat(total);
						$('#final_total').html("&pound;"+final_total.toFixed(2));
					}
				});
				
				total_vat_plus_total  = final_total + total_vat_value;
				if(!isNaN(total_vat_plus_total) && total_vat_plus_total != ""){
					$('#grand_total').html("&pound;"+total_vat_plus_total.toFixed(2));
					$('.grand_total_remove').val(total_vat_plus_total);
				}
			}
		}
	});
	
	
	
	$("#form1").on("change","#purchase_order_id",function(){
		var purchase_order_id = $(this).val();
		var arolite_job_id = $("#arolite_job_id").val();
		if(purchase_order_id != ""){
		$("#po_item_load").show();
			var form_data   = {'purchase_order_id':purchase_order_id,'arolite_job_id':arolite_job_id};
			$.ajax({
				async: true,
				type: "POST",
				url: site_url+"/modules/po_invoices/index.php?page=ajax_actions&action=get_po_item_by_po_id",
				data: form_data,
				success: function(result){  
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == "success"){
						$("#po_time_fetch_div").html(resultObj.divSection);
						
						
						$('#final_total').html("&pound;"+resultObj.final_total.toFixed(2));
						
						$('#grand_total').html("&pound;"+resultObj.grand_total.toFixed(2));
						
						$("#po_item_load").hide();
					}else{
						$("#po_time_fetch_div").html(resultObj.divSection);
						$("#po_item_load").hide();
					}
					
				}
			});
		}else{
			$("#po_time_fetch_div").html("<div class='col-lg-10 text-center' style='padding: 7px 0px;font-style:italic;color: #F44336;'><b>Please Select Purchase Order.</b></div>");
		}
	});
});
</script>