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

$from = $_REQUEST['from'];
$return_ref_array = $gsi->getReturnRefMax();
$return_ref = $return_ref_array["new_return_ref"];
$return_integer_ref = $return_ref_array["new_return_int_ref"];

/* $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","stock_ref","supplier_ref","description","unit_price","total","is_returned"));
	
	$return_ref_array = $gsi->getReturnRefMax();
    $return_ref = ($return_ref_array["new_return_ref"] == $_REQUEST['return_ref']) ? $_REQUEST['return_ref'] : $return_ref_array["new_return_ref"];
	$return_integer_ref = ($return_ref_array["new_return_ref"] == $_REQUEST['return_ref']) ? $_REQUEST['return_integer_ref'] : $return_ref_array["new_invoice_int_ref"];
    
    $org_id 						= $_REQUEST['org_id']; 
    $job_no_id 						= $_REQUEST['job_no_id']; 
    $supplier_id 					= $_REQUEST['supplier_id']; 
    $purchase_order_no 				= $_REQUEST['purchase_order_no']; 
    $liability 						= $_REQUEST['liability']; 
    $is_supplier_notified 			= $_REQUEST['is_supplier_notified']; 
    $is_collection_arranged 		= $_REQUEST['is_collection_arranged']; 
    $collection_due_date 			= utility::setFormatedDate($_REQUEST['collection_due_date']); 
    $return_status 					= $_REQUEST['return_status']; 
    $credit_note_details 			= $_REQUEST['credit_note_details']; 
    $date 							= utility::setFormatedDate($_REQUEST['date']); 
    $number 						= $_REQUEST['number']; 
    $amount 						= $_REQUEST['amount']; 
	$created_by						= $_SESSION['user_id'];
	$created_on						= date("Y-m-d H:i:s");
	$updated_by						= $_SESSION['user_id'];
    
	$sql = "return_ref = '".$return_ref."',return_integer_ref = '".$return_integer_ref."',org_id = '".$org_id."',job_no_id = '".$job_no_id."',supplier_id = '".$supplier_id."',purchase_order_no = '".$purchase_order_no."',liability = '".$liability."',is_supplier_notified = '".$is_supplier_notified."',is_collection_arranged = '".$is_collection_arranged."',collection_due_date = '".$collection_due_date."',return_status = '".$return_status."',credit_note_details = '".$credit_note_details."',date = '".$date."',number = '".$number."',amount = '".$amount."',created_by = '".$created_by."',created_on = '".$created_on."', updated_by = '".$updated_by."'";
	$sql= "INSERT INTO $table_name SET ".$sql;

	mysqli_query($conn,$sql);
	$return_id = mysqli_insert_id($conn);
	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];	
			//$quantity			= $_REQUEST['quantity'][$key];
			$unit_price			= $_REQUEST['unit_price'][$key];
			$total				= $_REQUEST['total'][$key];
			$is_returned		= $_REQUEST['is_returned'][$key];
			
            if($quantity!="" ){				
				$sql1 = "return_id = '".$return_id."',quantity = '".$quantity."',stock_ref = '".$stock_ref."',supplier_ref = '".$supplier_ref."',description = '".$description."',unit_price = '".$unit_price."',total = '".$total."',is_returned = '".$is_returned."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
				$sql1= "INSERT INTO returns_items_mapping SET ".$sql1;
				
				mysqli_query($conn,$sql1);
			}
		}
	}	
	
	$_SESSION['info_message'] = "Return added sucessfully";
	header("Location: $file_name");
    exit();
}
########################################## END INSERT ##########################################

########################################## START EDIT ##########################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){	
	$id = $_REQUEST['id'];
	$return_id = utility::app_crypt($_REQUEST['return_id'],'d');
	if($id != $return_id){
		die("Invaild URL");
	}
	$form_action 	= "update";
	$button_value 	= "Update";
	$page_name      = "Edit Return";
	$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);

    $return_ref					= $row_edit['return_ref'];
    $return_integer_ref			= $row_edit['return_integer_ref'];
    $org_id						= $row_edit['org_id'];
    $job_no_id					= $row_edit['job_no_id'];
    $supplier_id				= $row_edit['supplier_id'];
    $purchase_order_no			= $row_edit['purchase_order_no'];
    $liability					= $row_edit['liability'];
    $is_supplier_notified		= $row_edit['is_supplier_notified'];
    $is_collection_arranged		= $row_edit['is_collection_arranged'];
    $collection_due_date		= $row_edit['collection_due_date'];
    $return_status				= $row_edit['return_status'];
    $credit_note_details		= $row_edit['credit_note_details'];
    $date						= $row_edit['date'];
    $number						= $row_edit['number'];
    $amount						= $row_edit['amount'];
   
   
    
	
	$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","stock_ref","supplier_ref","description","unit_price","total","is_returned","returns_mapping_id"));
	$id							= $_REQUEST['id'];
	$return_ref 				= $_REQUEST['return_ref']; 
    $return_integer_ref 		= $_REQUEST['return_integer_ref']; 
    $org_id 					= $_REQUEST['org_id']; 
    $job_no_id 					= $_REQUEST['job_no_id']; 
    $supplier_id 				= $_REQUEST['supplier_id']; 
    $purchase_order_no 			= $_REQUEST['purchase_order_no']; 
    $liability 					= $_REQUEST['liability']; 
    $is_supplier_notified 		= $_REQUEST['is_supplier_notified']; 
    $is_collection_arranged 	= $_REQUEST['is_collection_arranged']; 
    $collection_due_date 		= utility::setFormatedDate($_REQUEST['collection_due_date']); 
    $return_status 				= $_REQUEST['return_status']; 
    $credit_note_details 		= $_REQUEST['credit_note_details']; 
    $date 						= utility::setFormatedDate($_REQUEST['date']); 
    $number 					= $_REQUEST['number']; 
    $amount 					= $_REQUEST['amount']; 
	
	$updated_by					= $_SESSION['user_id'];
	
	
	$sql = "return_ref = '".$return_ref."',return_integer_ref = '".$return_integer_ref."',org_id = '".$org_id."',job_no_id = '".$job_no_id."',supplier_id = '".$supplier_id."',purchase_order_no = '".$purchase_order_no."',liability = '".$liability."',is_supplier_notified = '".$is_supplier_notified."',is_collection_arranged = '".$is_collection_arranged."',collection_due_date = '".$collection_due_date."',return_status = '".$return_status."',credit_note_details = '".$credit_note_details."',date = '".$date."',number = '".$number."',amount = '".$amount."',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];
			$unit_price			= $_REQUEST['unit_price'][$key];
			$returns_mapping_id	= $_REQUEST['returns_mapping_id'][$key];
			$total				= $_REQUEST['total'][$key];
			$is_returned		= $_REQUEST['is_returned'][$key];
			
            if($quantity!="" ){	
                if(mysqli_num_rows(mysqli_query($conn,"SELECT * FROM returns_items_mapping WHERE id = '$returns_mapping_id' ")) > 0){
					$sql2= "UPDATE returns_items_mapping SET quantity = '".$quantity."', stock_ref = '".$stock_ref."', supplier_ref = '".$supplier_ref."',description = '".$description."',unit_price = '".$unit_price."',total = '".$total."',is_returned = '".$is_returned."',updated_by = '$updated_by' WHERE id = '$returns_mapping_id' ";
					mysqli_query($conn,$sql2);
				}else{
					$sql1 = "return_id = '".$id."',quantity = '".$quantity."',stock_ref = '".$stock_ref."',supplier_ref = '".$supplier_ref."',description = '".$description."',unit_price = '".$unit_price."',total = '".$total."',is_returned = '".$is_returned."',created_by = '".$created_by."', created_on = '".$created_on."', updated_by = '".$updated_by."' ";
					 $sql1= "INSERT INTO returns_items_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;
	
	$return_id = urlencode(utility::app_crypt($id,'e'));
	$_SESSION['info_message'] = "Return updated sucessfully";
	
    header("Location: $file_name$query_string");
    exit();
}
################################# END UPDATE ######################################## 
?>
<style>
em{color:red;font-size: 20px;position: absolute;}
</style>
<div class="col-sm-12 col-lg-12 col-12" id="new_returns_div_to_clone" style="display:none;">
		<div class="row">
			<div class="col-sm-1"> 
				 <label class="control-label" for="Quantity">&nbsp;<em></em></label> 
				 <input type="number" class="form-control quantity" id="quantity" name="quantity[]" value="" placeholder="Quantity" autocomplete="off" >  
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Stock Ref">&nbsp;<em></em></label> 
				 <input type="text" id="stock_ref" name="stock_ref[]" class="form-control" value="" placeholder="Stock Ref">
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Suplier Ref">&nbsp;<em></em></label> 
				  <input type="text" id="supplier_ref" name="supplier_ref[]" class="form-control" value="" placeholder="Suplier Ref"> 
			</div>
			<div class="col-sm-2"> 
				 <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="Unit price">&nbsp;<em></em></label> 
				 <div class=""> 
					<input type="text" id="unit_price" name="unit_price[]" class="form-control unit_price" 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-2"> 
				 <label class="control-label" for="is_returned">&nbsp;<em></em></label>
				 <div class=""> 
					<input type="checkbox" class="flat-red is_returned" id="is_returned" name="is_returned[]" value="1">
				</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_return_item" alt="" style="cursor:pointer;"></span>
					<input type="hidden" id="" class="each_row_total" value="" >
				</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_return_details"){
				$query_string = str_ireplace("page=add", "page=view_return_details", $query_string);
			}else {
				$query_string = str_ireplace("page=add", "page=view", $query_string);
			}
				
			?>
			<button type="button" id="back" name="back" value="back"  style="float:right;margin-right:5px;margin-bottom:8px;" class="btn btn-success" onclick="window.location.href = 'index?<?=$query_string;?>'">Back</button>
			</div>
		</div>
	</div>
</section>
<section class="content">
	<div class="row">
		<div class="col-12">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? } ?>
			<!----------------------- End Message ------------------------------->
			<!-- general form elements -->
              <div class="card">
                <form class="" method="post" name="form1" id="form1" action="index?page=add&action=<? echo $form_action; ?>" onsubmit="return validateForm(this)" enctype="multipart/form-data">
                  <div class="card-body">
				  <div class="row">
				  <div class="col-lg-6 col-sm-12">
					<div class="form-group"> 
						<label class="control-label" for="Return Ref">Return Ref <em></em></label> 
						<div class=""> 
							<input type="text" id="return_ref" name="return_ref" class="form-control" value="<?php echo $return_ref;?>" placeholder="Return Ref" readonly>
							<input type="hidden" id="return_integer_ref" name="return_integer_ref" value="<?php echo $return_integer_ref;?>">
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Client">Client<em>*</em></label>
						<div class=""> 
							<? $gsi->getOrganisationList("org_id",$org_id,"100%",false,"form-control select2","required"); ?>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Job No">Job No<em></em></label> 
						<div class=""> 
						<?$gsi->getAroliteJobsList("job_no_id",$job_no_id,"100%",false,"form-control select2","");?>				
						</div>
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Supplier">Supplier<em></em></label> 
						<div class=""> 
							<? $gsi->getSupplierList("supplier_id",$supplier_id,"100%",false,"form-control select2","","1"); ?>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Purchase Order No">Purchase Order No<em></em></label> 
						<div class=""> 
							<? $gsi->getPurchaseOrderList("purchase_order_no",$purchase_order_no,"100%",false,"form-control select2",""); ?>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Liability">Liability<em></em></label> 
						<div class=""> 
							<? $gsi->getLiabilityList("liability",$liability,"100%",false,"form-control","","1"); ?>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Supplier Notified">Supplier Notified<em></em></label> 
						<div class=""> 
							<input type="checkbox" class="flat-red" id="is_supplier_notified" name="is_supplier_notified" value="1" <? echo ($is_supplier_notified == 1) ? "checked" : ""; ?>>
						</div> 
					</div>
				</div>
				<div class="col-lg-6 col-sm-12">
					<div class="form-group"> 
						<label class="control-label" for="Collection Arranged">Collection Arranged<em></em></label> 
						<div class=""> 
							<input type="checkbox" class="flat-red" id="is_collection_arranged" name="is_collection_arranged" value="1" <? echo ($is_collection_arranged == 1) ? "checked" : ""; ?>>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Collection Due Date">Collection Due Date<em></em></label>
						<div class=""> 
							<input type="text" class="form-control datepicker" id="collection_due_date" name="collection_due_date" value="<?php echo (isset($collection_due_date) && $collection_due_date !="") ? utility::getFormatedDate($collection_due_date) : "";?>" placeholder="DD-MM-YYYY" autocomplete="off">
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Return Status">Return Status<em></em></label> 
						<div class=""> 
							<? $gsi->getReturnStatusList("return_status",$return_status,"100%",false,"form-control","","1"); ?>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Credit Note Details">Credit Note Details<em></em></label> 
						<div class=""> 
							<textarea id="credit_note_details" name="credit_note_details" class="form-control" placeholder="Credit Note Details"><?php echo stripslashes($credit_note_details);?></textarea>
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Date">Date<em></em></label>
						<div class=""> 
							<input type="text" class="form-control datepicker" id="date" name="date" value="<?php echo (isset($date) && $date !="") ? utility::getFormatedDate($date) : "";?>" placeholder="DD-MM-YYYY" autocomplete="off">
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Number">Number<em></em></label>
						<div class=""> 
							<input type="text" id="number" name="number" class="form-control check_number_value" value="<?php echo $number;?>" placeholder="Number">
						</div> 
					</div>
					<div class="form-group"> 
						<label class="control-label" for="Amount">Amount<em></em></label>
						<div class=""> 
							<input type="text" id="amount" name="amount" class="form-control check_number_value" value="<?php echo $amount;?>" placeholder="Amount">
						</div> 
					</div>
				</div>
					
				<div class="col-lg-12 col-sm-12 text-primary" style="margin-top:20px;">
					<h5>Return Items<hr style='height:2px;color:black; background-color:black;'></h5>
				</div>
<?		$final_total=0;
		$po_item_mapping_query = "SELECT * FROM returns_items_mapping WHERE return_id='".$id."'";
		$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;
			while($row_po_item_mapping = mysqli_fetch_array($po_item_mapping_sql)){
	?>
	<div class="col-sm-12 col-lg-12 col-12 initial_row_for_return_items" id="new_po<?=$row_po_item_mapping['id'];?>" data-po_count="<?=$row_po_item_mapping['id'];?>" alt="<?=$j;?>">
		<div class="row">
			<div class="col-sm-1"> 
				 <label class="control-label" for="Quantity">Quantity<em></em></label> 
				 <input type="text" id="quantity" name="quantity[<?=$i;?>]" class="form-control quantity" value="<?php echo $row_po_item_mapping['quantity'];?>" placeholder="Quantity">
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Stock Ref">Stock Ref<em></em></label> 
				  <input type="text" id="stock_ref" name="stock_ref[<?=$i;?>]" class="form-control" value="<?php echo $row_po_item_mapping['stock_ref'];?>" placeholder="Stock Ref"> 
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Supplier Ref">Supplier Ref<em></em></label> 
				  <input type="text" id="supplier_ref" name="supplier_ref[<?=$i;?>]" class="form-control" value="<?php echo $row_po_item_mapping['supplier_ref'];?>" placeholder="Supplier Ref"> 
			</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"> 
				 <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" 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-2"> 
				 <label class="control-label" for="Returned">Returned<em></em></label> 
				 <div class=""> 
					<input type="checkbox" id="is_returned" name="is_returned[<?=$i;?>]" class="flat-red is_returned" value="1" <? echo ($row_po_item_mapping['is_returned'] == 1) ? "checked" : ""; ?>>
				</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="returns_mapping_id[<?=$i;?>]" value="<?php echo $row_po_item_mapping['id'];?>">
					<span class="fa fa-trash delete_return_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_item_<?=$row_po_item_mapping['id'];?>" style="font-size: 20px;display:none;"></i>
					<i class="fa fa-check" id="return_item_delete_done_<?=$row_po_item_mapping['id'];?>" style="color:#bad23a;font-size: 20px;display:none;"></i>
				</div>
			</div>
		</div>
	</div>
	
	<? $i++;
		$j++;
		$total = $row_po_item_mapping["quantity"] * $row_po_item_mapping["unit_price"];
		$vat_amount = ($total * 20 /100);
		$final_total = $final_total + $total;
		$total_amount_with_vat = $vat_amount + $total;
		$grand_total = $total_amount_with_vat+$grand_total; 
		
	}}else{?>
	<div class="col-sm-12 col-lg-12 col-12 initial_row_for_return_items" id="new_po0" data-po_count="0" alt="0">
		<div class="row">
			<div class="col-sm-1"> 
				 <label class="control-label" for="Quantity">Quantity<em></em></label> 
				 <input type="number" class="form-control quantity" id="quantity" name="quantity[]" value="" placeholder="Quantity" autocomplete="off" >  
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Stock Ref">Stock Ref<em></em></label> 
				  <input type="text" id="stock_ref" name="stock_ref[]" class="form-control" value="" placeholder="Stock Ref"> 
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Supplier Ref">Supplier Ref<em></em></label> 
				  <input type="text" id="supplier_ref" name="supplier_ref[]" class="form-control" value="" placeholder="Supplier Ref"> 
			</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="Unit Price">Unit Price<em></em></label> 
				 <div class=""> 
					<input type="text" id="unit_price" name="unit_price[]" class="form-control unit_price" value="" 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[]" class="form-control total" value="" placeholder="Total" readonly>
				</div>
			</div>
			<div class="col-sm-2"> 
				 <label class="control-label" for="Returned">Returned<em></em></label> 
				 <div class=""> 
					<input type="checkbox" id="is_returned" name="is_returned[]" class="flat-red is_returned" value="1">
				</div>
			</div>
		</div>
	</div>
	<?}?>
					<div class="form-group col-sm-12 new_return_div_to_append">	
						<label class="add_one_more_new_return" style="margin-left:0%;cursor:pointer"><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 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 class="form-group col-sm-12 ">	
						<label class="" style="margin-top:6px;float: right;">Total Including Vat 20%: <span id="grand_total">&pound;<?=number_format($grand_total,2);?></span></label>
					</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(){
	$('#form1').submit(function(){
		//$(this).addClass('disabled');
		$("#submit").attr("disabled", true);
		$('#page_load_div').show();
	});
	
	$('.add_one_more_new_return').click(function() {		
		$('#new_returns_div_to_clone').show();		
		var div_count = $('.initial_row_for_return_items').last().attr("data-po_count");
		
		div_count++;
		var cloned_div = $('#new_returns_div_to_clone').clone().addClass("initial_row_for_return_items").attr("id","new_po"+div_count).attr("data-po_count",div_count);		
		$('.new_return_div_to_append').before(cloned_div);	
		$('#new_returns_div_to_clone').hide();	
		$('#new_po'+div_count).children().find("#is_returned").attr("name","is_returned["+div_count+"]")		
		
	});
	$("#form1").on("keyup",".quantity,.unit_price,.vat",function(){
		if ($(this).val() <= "0") { // check if value changed
			alert('Quantity/UnitPrice Cant be zero');
			$(this).val("");
			return false;
		}	
		var div_no = $(this).parent().parent().parent().parent().attr("data-po_count");
		var qty = $('#new_po'+div_no).find(".quantity").val();
		 
		var unit_price = $('#new_po'+div_no).find(".unit_price").val();
		total = parseFloat(qty * unit_price);
		
		if(!isNaN(total)){
			total = total.toFixed(2);
			//$('#total'+div_no).html("&pound;"+total);
			$('#new_po'+div_no).find(".total").val(total);
		}
	    var final_total = 0;
	    var grand_total = 0;
	    var vat_amount = 0;
		$('.initial_row_for_return_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();
			var total_amount_with_vat = $('#new_po'+div_no).find(".total_amount").val();
			total = parseFloat(qty * unit_price);
			vat_amount = parseFloat(total * 20 /100); 
			final_total = final_total+total;
			total_amount_with_vat = vat_amount + total;
			grand_total = total_amount_with_vat+grand_total;
			/* if(!isNaN(vat_amount)){
			vat_amount = vat_amount.toFixed(2);
			$('#new_po'+div_no).find(".vat_amount").val(vat_amount);
		    }
			if(!isNaN(total_amount_with_vat)){
			total_amount_with_vat = total_amount_with_vat.toFixed(2);
			$('#new_po'+div_no).find(".total_amount").val(total_amount_with_vat);
		    } */
			
			if(!isNaN(total)){
			total = total.toFixed(2);
			$('#new_po'+div_no).find(".total").val(total);
			$('#new_po'+div_no).find(".each_row_total").val(total);
		    }
		});
		if(!isNaN(final_total)){
			$('#final_total').html("&pound;"+final_total.toFixed(2));
			$('.final_total_remove').val(final_total);
		} 
		if(!isNaN(grand_total)){
			$('#grand_total').html("&pound;"+grand_total.toFixed(2));
		}
	});

	$("#form1").on("click", ".delete_return_item",function() {
	    if(confirm('Are you sure! You want to delete')){
			var grand_total = 0;
			var vat_amount = 0;
			var final_total_remove = $(".final_total_remove").val();
			if($(this).attr("alt") != ""){
				
				var return_item_mapping_id = $(this).attr("alt");
				var one_item_amount = $(this).attr("data-item_amount");
				$('#load_new_po_item_'+return_item_mapping_id).show();
				var form_data   = {'return_item_mapping_id':return_item_mapping_id};       
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/returns/index.php?page=ajax_actions&action=delete_return_item",
					data: form_data,
					success: function(result){    
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$('#return_item_delete_done_'+return_item_mapping_id).show();
							$('#load_new_po_item_'+return_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);
							
							vat_amount = parseFloat(final_total * 20 /100); 
							total_amount_with_vat = vat_amount + final_total;
							grand_total = total_amount_with_vat+grand_total;
							
							$('#grand_total').html("&pound;"+grand_total.toFixed(2));
							
							
							
							setTimeout(function() {
								$('#return_item_delete_done_'+return_item_mapping_id).hide();
								$('#new_po'+return_item_mapping_id).remove();
								//location.reload();
							},1000);
						}
					}
				});
			}else{
				var each_row_total = $(this).parent().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);
				
				vat_amount = parseFloat(final_total * 20 /100); 
				total_amount_with_vat = vat_amount + final_total;
				grand_total = total_amount_with_vat+grand_total;
				
				$('#grand_total').html("&pound;"+grand_total.toFixed(2));
				$(this).parent().parent().parent().parent().remove();
			}
		}
	});
});
</script>