<?php 

if(($Load_details[0]['Is_Load'] !=  2 && $Load_details[0]['Is_Load'] !=  3 )) {?>
<div class="alert alert-danger" role="alert">
	<button class="close" data-dismiss="alert"></button>
	<strong><?php print CommonLanguage::getMessage('danger');?>: </strong> <?php print CommonLanguage::getMessage('confirm_load_first');?><a href="<?php echo SITE_LINK; ?>Inventory/ViewLoadingOrder/<?php echo $Load_ID; ?>"><?php print CommonLanguage::getMessage('confirm_load');?></a>
</div>
<?php die();} //else if($Load_details[0]['Is_Load'] ==  3) {$EditMode = false;}?>
<style type="text/css">
	.ValSpan{
		opacity:0;
	}
	.line{
		border:2px solid #4c0870 ;
	}
	.bg-master-lighter {
		border: none;
		background-color: #fff;
		border-top: 1px solid #ddd;
	}
	.ReturnQuantityVal,.DamagedQuantity    {
		border: none;
		background-color: #eee;
		text-align: center;
		opacity: 0.5;
	}
	.EditRow{
		opacity: 1;
		transform: scale(1.1)
	}
</style>
<script src="<?php echo VIEWS; ?>files/towords.js"></script>
<form method="POST" action="" onsubmit="return false" id="ReturnDamagedItemForm">
	<div class="container-fluid container-fixed-lg">
		<div class="panel invoice">
			<div class="panel-body">
				<div id="ReturnItemSuccess" class="alert alert-success hidden"></div>
				<div class="row">
					<div class="col-xs-3">
						<div class="invoice-logo">
							<img src="<?= upload_url;?>org_logo/invoice_logo.jpg" alt=""style="max-width:250px"/>
						</div>
					</div>
					<div class="col-xs-2">
					</div>
					<div class="col-xs-7">
						<h1><?php print CommonLanguage::getMessage('loading_order_return');?></h1>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-4">
						<label><span class="bold"><?php print CommonLanguage::getMessage('Name');?> 	  :</span></label><?php echo $org_details[0][ "Organization_Name"]; ?><br/>
						<label><span class="bold"><?php print CommonLanguage::getMessage('address');?> :</span></label><?php echo $org_details[0][ "Country_Name"] .'-'. $org_details[0]["Name"].'-'. $org_details[0][ "Organization_Street"]?><br/>
						<label><span class="bold"><?php print CommonLanguage::getMessage('Email');?>   :</span></label><?php echo $org_details[0][ "Organization_Email"] ?><br/>
						<label><span class="bold"><?php print CommonLanguage::getMessage('Phone');?>   :</span></label><?php echo $org_details[0]["Organization_Phone"] ?><br/>
					</div>
					<div class="col-xs-4">
						<br/> <label><span class="bold"><?php print CommonLanguage::getMessage('truck');?> #  : </span></label><?php echo $Load_details[0]['Vehicle_Registration_Number'];?>
						<br/> <label><span class="bold"><?php print CommonLanguage::getMessage('driver');?> 	 : </span> </label><?php echo $Load_details[0]['Driver_Name'];?>
						<br/><label><span class="bold"><?php print CommonLanguage::getMessage('salesman');?> :</span></label> <?php echo $Load_details[0]['Sales_Man_Name'];?>
					</div>
					<div class="col-xs-4 inv-info">
						<br/><label><span class="bold">Loading<?php print CommonLanguage::getMessage('danger');?> # :</span> </label>1
						<br/><label><span class="bold">Zone<?php print CommonLanguage::getMessage('danger');?> 	 : </span></label><?php echo $Load_details[0]['Zone_Name'];?>
						<br/><label><span class="bold">Load-Date<?php print CommonLanguage::getMessage('danger');?> : </span></label><?php echo $Load_details[0]['Loading_Order_Date'];?>
						<input type="hidden" id="Loading_ID" value="<?php echo $Load_ID?>">
					</div>
				</div>
				<hr>
				<div class="col-md-12">
					<div class="col-md-12   clearfix" style="margin:5px;border: 1px solid #4c0870;padding-left: 6px;padding-right:0">
						<h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('Total_Quantity');?></h5>
						<?php if ($EditMode == true){?>
						<button type="button" class="btn btn-primary pull-right" id="EditInput" style="margin-right:10px;margin-top: -20px;"><i class="fa fa-pencil"></i> <?php print CommonLanguage::getMessage('Edit');?></button>
						<?php }?>
						<div ID="ReturnDamageLoadTableLoader" style="display:none;position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:999"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>
						<table class="table" cellpadding="0" cellspacing="0" id="ReturnDamageLoadTable">
							<thead>
								<tr>
									<th class="text-center">#</th>
									<th class="text-center"><?php print CommonLanguage::getMessage('Code');?></th>
									<th class="text-center"><?php print CommonLanguage::getMessage('Item');?></th>
									<th class="text-center"><?php print CommonLanguage::getMessage('Quantity');?></th>
									<th class="text-center"><?php print CommonLanguage::getMessage('return');?></th>

									<th class="text-center"><?php print CommonLanguage::getMessage('Damage');?></th>

								</tr>
							</thead>
							<tbody>
								<?php 
								for($x=0;$x<count($Total_Quantity_details);$x++){
									$CurItem = $Total_Quantity_details[$x];
								?>
								<tr data-code="<?php echo $CurItem['Product_ID']?>" data-load="<?php echo $Load_ID?>">
									<td class="text-center"><?php echo $x+1;?></td>
									<td class="text-center"><?php echo $CurItem['Product_Code'];?></td>
									<td class="text-center"><?php echo $CurItem['Product_Name'];?></td>
									<td class="text-center" ><input type="hidden" class="Product_QTY" value="<?php echo $CurItem['Total_Quantity'];?>"/><?php echo $CurItem['Total_Quantity'];?></td>
									<td class="text-center ReturnVal"><?php if($EditMode == true){?><input  disabled='disabled' type="text" class="ReturnQuantityVal" value="<?php if(empty($Return_details)){echo 0;} else{ echo $Return_details[$x]['Return_Quantity'];}?>"/>  

										<span class='fa fa-plus-circle Return' style='color:#4c0870; margin-left: 10px;'></span><?php }else echo $Return_details[$x]['Return_Quantity'];?></td>



									<td class="text-center DamageVal"><?php if($EditMode == true){?><input  disabled='disabled' type="text"  class="DamagedQuantity" value="<?php if(empty($Return_details)){echo 0;} else{ echo $Return_details[$x]['Damaged_Quantity'];}?>"/>

									<span class='fa fa-plus-circle Damage' style='color:#4c0870; margin-left: 10px;'></span><?php }else echo $Return_details[$x]['Damaged_Quantity'];?></td>

								</tr>
								<?php 
								}
								?>
							</tbody>
						</table>
					</div>
				</div>
				<?php if ($EditMode == true){?>
				<div class="container-sm-height" >
					<button class=" btn  btn-cons m-b-10 pull-right disabled" id="ReturnDamagedLoadButton" style="color:#fff;background-color:#4c0870 ;padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save');?></span></button>
				</div>
				<?php }?>
			</div>
			</form>
		<nav class="navbar navbar-default bg-master-lighter sm-padding-10" role="navigation">
			<div class="container-fluid">
				<div class="collapse navbar-collapse" id="sub-nav">
					<div class="row"> 
						<div class="col-sm-4 ">
							<ul class="nav navbar-nav navbar-center">
								<li><a href="#" data-toggle="tooltip" title="Print" class="PrintThisTableButton" data-table="#tableWithSearch" data-date="" data-title="Return List"><i class="fa fa-print"></i></a></li>
								<li><a href="#" data-toggle="tooltip" data-placement="bottom" title="Download"><i class="fa fa-download"></i></a></li>
							</ul>
						</div>
						<div class="col-sm-4 pull-right">
							<ul class="nav navbar-nav navbar-right">
								<li>
									<a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-pdf" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png" src="<?php echo SITE_LINK; ?>img/invoice/pdf2x.png"></a>
								</li>
								<li>
									<a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-image" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/image2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/image2x.png" src="<?php echo SITE_LINK; ?>img/invoice/image2x.png"></a>
								</li>
								<li>
									<a href="#" class="p-r-10"><img width="25" height="25" alt="" class="icon-doc" data-src-retina="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" data-src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png" src="<?php echo SITE_LINK; ?>img/invoice/doc2x.png"></a>
								</li>
								<li><a href="#" class="p-r-10" onclick="$.Pages.setFullScreen(document.querySelector('html'));return false"><i class="fa fa-expand"></i></a></li>
							</ul>
						</div>
					</div>
				</div>
			</div>
		</nav>
	</div>
	</div>


<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="role-mode" id="add_Expiry" aria-hidden="true" style="display: none;     width: 50%;
																														  margin: 0 auto;">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
				<h4 class="modal-title" id="myModalLabel"> <?php print CommonLanguage::getMessage('Add_Expiry_Date');?></h4>
				<div id="ExpirySuccess" class="hidden"></div>
				<br>
			</div>
			<div class="modal-body" id="Add">
				<input type="hidden" name="Product_ID"  id="Product_ID" class="form-control input-rounded" required>
				<input type="hidden" name="Category_ID"  id="Category_ID" class="form-control input-rounded" required>
				<div class="form-group col-md-12 AddRow">
					<div  class=" col-md-6">
						<input type="text" name="Product_Quantity"  id="Product_Quantity" placeholder="<?php print CommonLanguage::getMessage('Quantity');?>" class="form-control input-rounded Product_Quantity" required>
					</div>
					<div  class=" col-md-5">
						<input type="text" name="Product_ExpiryDate"  id="Product_ExpiryDate" placeholder="<?php print CommonLanguage::getMessage('Expiry_Date');?>" class="form-control input-rounded Product_ExpiryDate" required>
					</div>
					<span class="fa fa-plus-circle" style="color:#8a7dbe;margin-top:10px"></span>
					<span class="fa fa-minus-circle" style="color:#ed9421;margin-top:10px;display:none"></span>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" id="Closemodal" ><?php print CommonLanguage::getMessage('Close');?></button>
				<button type="submit" class="btn btn-primary" id="SubmitExpiry"><?php print CommonLanguage::getMessage('Save');?></button>
			</div>
		</div>
	</div>
</div>
<script>
	var Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully'));?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit'));?>;
		var type=0;
	$(function(){
	$("#Product_ExpiryDate").datepicker({autoclose:true}).on("changeDate",function(){})
		$("#ReturnDamageLoadTable tbody").on("click","tr > .ReturnVal > span.fa-plus-circle,tr > .DamageVal > span.fa-plus-circle",function(){
			var me = $(this).parents("tr");
			
			if($(this).hasClass('Return')){
				type = 3;
			}else if ($(this).hasClass('Damage'))
			{
				type = 7;
				
			}
			$("#add_Expiry").modal('show')
			$("#Product_ID").val(me.attr('data-code'))
			$("#Category_ID").val(me.attr('data-cid'))
		})
		$("#Add").on("click",".AddRow > .fa-plus-circle",function(e){
			$(".AddRow > .fa-minus-circle").css("display","")
			var Parent = $(this).parents("#Add").find(".AddRow:eq(0)"),NewItem = Parent.clone().insertAfter(Parent);
			NewItem.find("input").val('');
			NewItem.find("#Product_ExpiryDate").datepicker({autoclose:true})
		})
		$("#Add").on("click",".AddRow > .fa-minus-circle",function(e){
			$(this).closest(".AddRow").empty().remove();
			$("#Add").each(function(){
				$(".AddRow > .fa-minus-circle",$(this).parent()).css({"display":$(".AddRow",$(this).parent()).length <= 1 ? "none" : "inline-block"})
			})
		})
	
	
	})
	
	
	$("#ReturnDamagedLoadButton").on("click",function(){
		var Changes = {
			// Loading_Order_ID   :$("#Loading_ID").val(),
			Return:[]
		};
		$("#ReturnDamageLoadTable tr[data-code]").each(function(){
			var NewObject = {
				Loading_Order_ID:			$(this).attr("data-load"),
				Product_ID:			$(this).attr("data-code"),
				Product_Qty:		($.trim($(".Product_QTY",this).val())),
				Return_Quantity:	($.trim($(".ReturnQuantityVal",this).val())),
				Damaged_Quantity:	($.trim($(".DamagedQuantity",this).val())),
				Total_Remaining_Qty:($.trim($(".Product_QTY",this).val()))-($.trim($(".ReturnQuantityVal",this).val()))-($.trim($(".DamagedQuantity",this).val()))
			}
			Changes.Return.push(NewObject)
		})
		console.log(Changes)
		//if($(".ReturnQuantity").val() == 0 || $(".DamagedQuantity").val() ){alert("There are no changes has been made");return}
		$("#ReturnDamageLoadTableLoader").show().appendTo("#ReturnDamagedItemForm .panel-body")
		$.ajax({
			url:"InventoryAjax/ReturnDamagedLoadAjax",
			method:"POST",
			data:Changes,
			complete:function(v,vv){
				if(vv == "success"){
					console.log(v.responseText);
					$(document.body).animate({scrollTop:0})
					$("#ReturnItemSuccess").attr("class","alert alert-success").show().html(Submitted_Successfully)
					$(".ReturnVal>input,.DamageVal>input").attr('disabled', 'disabled')
				}else{
					//alert("Failed to submit, please try again")
					$("#ReturnItemSuccess").removeClass("hidden,alert-success")
					$("#ReturnItemSuccess").attr("class","alert alert-danger").show().html(Failed_Submit)
				}
				$("#ReturnDamageLoadTableLoader").hide().insertBefore("#ReturnDamageLoadTable")
			}
		})
	})
	$("#EditInput").on("click",function(){
		$(".ReturnVal>input,.DamageVal>input").removeAttr("disabled").addClass("EditRow")
	})
	$("#ReturnDamageLoadTable tbody").on("keyup",".ReturnVal>input,.DamageVal>input",function(){
		UpdateSubmitButton()
	})
	function UpdateSubmitButton(){
		var IsValidated=true;
		$("#ReturnDamageLoadTable tr[data-code]").each(function(){
			var Qy   = parseInt($(".Product_QTY",this).val()),
				ReturnQy=parseInt($(".ReturnQuantityVal",this).val()),
				DamQy = parseInt($(".DamagedQuantity",this).val());
			var ReturnValue =(ReturnQy+DamQy);
			if((Qy < ReturnQy) || (Qy < DamQy) || (Qy < ReturnValue ) || $(".ReturnVal>input").val() == "" || ($(".ReturnVal>input").hasClass("ReturnQuantityVal") && ($(".ReturnVal>input").val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)
			   ||$(".DamageVal>input").val() == "" || ($(".DamageVal>input").hasClass("DamagedQuantity") && ($(".DamageVal>input").val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)
			  )
			{
				IsValidated = false;
			}
		})
		if(!IsValidated){
			$("#ReturnDamagedLoadButton").addClass("disabled")}
		else{$("#ReturnDamagedLoadButton").removeClass("disabled")}
	}
	
	
	
	
	
	
	
	
		$("#SubmitExpiry").on("click",function(){
		var Data={
			Product_ID  : $("#Product_ID").val(),
			type        : type,
			Depot_ID    : 144,
			Category_ID : 0,
			Expiry:[]
		}
		$("#Add > .AddRow").each(function(){
			var me= $(this);
			Data.Expiry.push({
				Expiry_Date : me.find(".Product_ExpiryDate").val(),
				Product_Quantity : me.find(".Product_Quantity").val()
			})
		})
		$.ajax({
			url:"InventoryAjax/ReturnDamagedLoadAjax",
			method:"POST",
			data:Data,
			complete:function(v1,v2){
				if(v2 == "success"  &&  v1.responseText == "OK"){
					$("#ExpirySuccess").attr("class","alert alert-success").html(Submitted_Successfully)
					setTimeout(function(){
						$("#add_Expiry").modal('hide')
						$("#ExpirySuccess").addClass('hidden')				 
						$('.AddRow').not('div:first').remove()
						$('.AddRow > .fa-minus-circle').not('div:first').css("display","none")			 
					},800)
				}else{
					$("#ExpirySuccess").attr("class","alert alert-danger").html(Failed_Submit)
				}
			}
		})
		$('#Add  input').val('')
	})
	$("#Closemodal").on("click",function(){
		$('#add_Expiry').modal('hide')
		$('.AddRow').not('div:first').remove()
		$('.AddRow > .fa-minus-circle').not('div:first').css("display","none")
		$('#Add  input').val('')
	})
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
</script>
