<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$stockitem = $_POST['stockitem'];
	$recversion = $_POST['recversion'];
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] < 4)
		{
			if($stockitem == "")
			{
				$err = $err."Item Identification Required!<br>";
			}
			else
			{
				$stockitemdata = DB::queryFirstRow("SELECT stock_item.status, stock_item.item_name, stock_item.item_code, stock_item.bar_code, item_stock_level.quantity , item_stock_level.id as stockid  FROM item_stock_level, stock_item WHERE  item_stock_level.id=%i AND item_stock_level.item = stock_item.id ", $stockitem);
			
			
				if(DB::count() != 1)
				{
					$err = $err."Stock Item Not Identified!<br>";
				}
				else
				{
					if($stockitemdata['status'] != 1)
						$err = $err."Item Status Does Not Support Goods Receipt!<br>";
				}
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}

	if($err == "")
	{
		try
		{
			$supplieroptions = "";
			
			$supplierdata = DB::query("SELECT id, supplier_name FROM supplier WHERE supplier_status = 1");
			
			foreach ($supplierdata as $supplieroption)
			{
				$supplieroptions .= '<option value="' . $supplieroption['id'] . '">' . $supplieroption['supplier_name'] . '</option>';
			}
			
			$receivegoodsformdata = '<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title text-center">Receive Item Goods Form</h4>
						</div>
						<div class="modal-body">
							<div id="receiveitemerrormessage">
							</div>
							
							<div class="row">
								<div class="col-sm-2">
									<b>Item Name </b>
								</div>
								
								<div class="col-sm-2">
									'.$stockitemdata['item_name'].'
								</div>
								
								<div class="col-sm-2">
									<b>Item Code </b>
								</div>
								
								<div class="col-sm-2">
									'.$stockitemdata['item_code']. '
								</div>
								
								<div class="col-sm-2">
									<b>Quantity </b>
								</div>
								
								<div class="col-sm-2">
									'.number_format($stockitemdata['quantity'], 2).'
								</div>
							</div>
							
							<div class="col-md-12" style="margin-top: 25px"></div>
							
							<div class="row">
								<div class="col-sm-4">
									<div class="form-group">
										<label for="valuedate">Date Received (mm/dd/yyyy)</label>
										 
										<input type="text" value="'.date('m/d/Y').'"   name="valuedate" id="valuedate" class="form-control" data-inputmask="\'alias\': \'mm/dd/yyyy\'" data-mask />
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-4">
									<div class="form-group">
										<label for="grn">Goods Received Number</label>
										<input type="hidden" name="grn" id="grn"  value="'.$stockitemdata['stockid'].'"  class="form-control" maxlength="95" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-4">
									<div style="margin-bottom: 32px"></div>
									<div class="form-group">
										<label>
											<input type="checkbox" id="isbatchlot" class="minimal" />
											Track Received Goods As A Batch
										</label>
									</div>
								</div>

							</div>
							
							<div class="row">
								<div class="col-sm-4">
									<div class="form-group">
										<label for="batchcode">Batch Code</label>
										<input type="text" name="batchcode" id="batchcode" class="form-control" maxlength="195" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-4">
									<div class="form-group">
										<label for="datemanufactured">Manufactured Date (mm/dd/yyyy)</label>
										<input type="text" name="datemanufactured" id="datemanufactured" class="form-control" data-inputmask="\'alias\': \'mm/dd/yyyy\'" data-mask />
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-4">
									<div class="form-group">
										<label for="expirydate">Expiry Date (mm/dd/yyyy)</label>
										<input type="text" name="expirydate" id="expirydate" class="form-control" data-inputmask="\'alias\': \'mm/dd/yyyy\'" data-mask />
									</div><!-- form-group -->
								</div>
							</div>
						
							<div class="row">																
								<div class="col-sm-3">
									<div class="form-group">
										<label for="unitcost">Unit Cost</label>
										<input type="text" name="unitcost" id="unitcost" class="form-control" maxlength="95" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-3">
									<div class="form-group">
										<label for="unitsellprice">Unit Sell Price</label>
										<input type="text" name="unitsellprice" id="unitsellprice" class="form-control" maxlength="95" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-4">
									<div class="form-group">
										<label for="supplier">Supplier</label>
										<select  class="form-control" name="supplier" id="supplier" data-placeholder="Choose One">
											<option value="">Choose One</option>
											' . $supplieroptions . '
										</select>
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-2">
									<div class="form-group">
										<label for="quantity">Received Quantity</label>
										<input type="text" name="quantity" id="quantity" class="form-control" maxlength="95" >
									</div><!-- form-group -->
								</div>
							</div>
							
							<div class="row">
								<div class="col-sm-12">
									<div class="form-group">
										 
										<input type="hidden" name="memo" id="memo"  value="'.$stockitemdata['stockid'].'"  class="form-control" maxlength="195" >
									</div><!-- form-group -->
								</div>
								<div class="col-sm-12">
								<div id="notesfooter" class="modal-footer">
									<a href="" data-dismiss="modal" class="btn btn-danger"><i class="fa fa-times"></i> Close</a>
									<button name="savebtn" id="savebtn" class="btn btn-primary"><i class="fa fa-save"></i> Save</button>
									
								</div>
								</div>
						
						
							</div>
                      
						</div>
						
						
						
						<!-- InputMask -->
						<script src="plugins/input-mask/jquery.inputmask.js" type="text/javascript"></script>
						<script src="plugins/input-mask/jquery.inputmask.date.extensions.js" type="text/javascript"></script>
						<script src="plugins/input-mask/jquery.inputmask.extensions.js" type="text/javascript"></script>
						<!-- iCheck 1.0.1 -->
						<script src="plugins/iCheck/icheck.min.js" type="text/javascript"></script>
						<!-- AdminLTE App -->
						<script src="dist/js/app.min.js" type="text/javascript"></script>
						<!-- AdminLTE for demo purposes -->
						<script src="dist/js/demo.js" type="text/javascript"></script>
						<script src="plugins/bert/jquery.price_format.min.js" type="text/javascript"></script>
						
						<script>
							var trackbatchlot = 0;
							
							//Datemask2 mm/dd/yyyy
							$("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
							//Money Euro
							$("[data-mask]").inputmask();
							
							//iCheck for checkbox
							$("input[type=\"checkbox\"].minimal").iCheck({
								checkboxClass: "icheckbox_minimal-blue"
							});
					
							$("#isbatchlot").on("ifChecked", function()
							{ 
								trackbatchlot = 1;
								
								document.getElementById("batchcode").value = "";
								$("#batchcode").prop("disabled", false);
								
								document.getElementById("datemanufactured").value = "";
								$("#datemanufactured").prop("disabled", false);
								
								document.getElementById("expirydate").value = "";
								$("#expirydate").prop("disabled", false);
								
								document.getElementById("unitcost").value = "";
								$("#unitcost").prop("disabled", false);
								
								document.getElementById("unitsellprice").value = "";
								$("#unitsellprice").prop("disabled", false);
							});
							
							$("#isbatchlot").on("ifUnchecked", function()
							{
								trackbatchlot = 0;
								
								document.getElementById("batchcode").value = "";
								$("#batchcode").prop("disabled", true);
								
								document.getElementById("datemanufactured").value = "";
								$("#datemanufactured").prop("disabled", true);
								
								document.getElementById("expirydate").value = "";
								$("#expirydate").prop("disabled", true);
								
								document.getElementById("unitcost").value = "";
								$("#unitcost").prop("disabled", true);
								
								document.getElementById("unitsellprice").value = "";
								$("#unitsellprice").prop("disabled", true);
							});
						
				
							$("#largemodal").on("hidden.bs.modal", function (e){
								$("#receiveitemerrormessage").html("");
							});
							
							$("#largemodal").on("shown.bs.modal", function (e){
								$("#valuedate").focus();
								
								document.getElementById("batchcode").value = "";
								$("#batchcode").prop("disabled", true);
								
								document.getElementById("datemanufactured").value = "";
								$("#datemanufactured").prop("disabled", true);
								
								document.getElementById("expirydate").value = "";
								$("#expirydate").prop("disabled", true);
								
								document.getElementById("unitcost").value = "";
								$("#unitcost").prop("disabled", true);
								
								document.getElementById("unitsellprice").value = "";
								$("#unitsellprice").prop("disabled", true);
							});
							
							$("#quantity").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							 
							$("#unitcost").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							
							$("#unitsellprice").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							
							$("#savebtn").click(function()
							{
								var err = "";
							
								$("#receiveitemerrormessage").html("");
								
								if($("#valuedate").val().trim() == "")
								{
									err += "Date Received Required!<br>";
								}
								else
								{
									if(!isDate($("#valuedate").val().trim()))
									{
										err += "Valid Date Received Required!<br>";
									}
									else
									{
										var boundarydate = new Date();
										var testdate = new Date($("#valuedate").val().trim());
									
										if(testdate.getTime() > boundarydate.getTime())
											err += "Value Date greater Than The Current Date Not Supported!<br>";
									}
								}
								
								if($("#grn").val().trim() == "")
									err += "Goods Received Number Required!<br>";
									
								if(trackbatchlot == 1)
								{
									if($("#batchcode").val().trim() == "")
										err += "Batch Code Required!<br>";
										
									if($("#datemanufactured").val().trim() == "")
									{
										err += "Manufactured Date Required!<br>";
									}
									else
									{
										if(!isDate($("#datemanufactured").val().trim()))
										{
											err += "Valid Manufactured Date Required!<br>";
										}
										else
										{
											var boundarydate = new Date();
											var testdate = new Date($("#datemanufactured").val().trim());
										
											if(testdate.getTime() > boundarydate.getTime())
												err += "Manufactured Date greater Than The Current Date Not Supported!<br>";
										}
									}
									
									if($("#expirydate").val().trim() == "")
									{
										err += "Expiry Date Required!<br>";
									}
									else
									{
										if(!isDate($("#expirydate").val().trim()))
										{
											err += "Valid Expiry Date Required!<br>";
										}
										else
										{
											var boundarydate = new Date();
											var testdate = new Date($("#expirydate").val().trim());
										
											if(testdate.getTime() <= boundarydate.getTime())
												err += "Expiry Date Not Exceeding Current Date Not Supported!<br>";
										}
									}
								}
								
								if($("#quantity").val().trim() == "")
									err += "Received Quantity Required!<br>";
								
								if(err == "")
								{
									$("#receiveitemerrormessage").html("");
								
									$.ajax
									(
										{
											url: "receivegoodsavenew.php",
											async: false, 
											type: "POST",
											dataType: "json",
											data: {valuedate: $("#valuedate").val().trim(), goodsreceivednote: $("#grn").val().trim(), trackbatchlot: trackbatchlot, batchcode: $("#batchcode").val().trim(), datemanufactured: $("#datemanufactured").val().trim(), expirydate: $("#expirydate").val().trim(), unitsellprice: $("#unitsellprice").val().trim(), supplier: $("#supplier").val(), quantity: $("#quantity").val().trim(), unitcost: $("#unitcost").val().trim(), memo: $("#memo").val().trim(), stockitem: ' . $stockitem . ', recversion: ' . $recversion . '},
											success: function(json)
											{
												if(json[0].issaved == 0)
												{
													$("#receiveitemerrormessage").html(json[0].message);
												}
												else
												{
													$("#receiveitemerrormessage").html(json[0].message);
													window.location.reload(true);
												}
											},
											error: function(jqXHR, exception)
											{	
												if (jqXHR.status === 0) 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Not Connected Verify Network.</div>");
												} 
												else if (jqXHR.status == 404) 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Requested Operation Not Found.</div>");
												} 
												else if (jqXHR.status == 500) 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Internal Server Error.</div>");
												} 
												else if (exception === "parsererror") 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Requested JSON Parse Failed.</div>");
												} 
												else if (exception === "timeout") 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Time Out Error.</div>");
												} 
												else if (exception === "abort") 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Ajax Request Aborted.</div>");
												} 
												else 
												{
													$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Uncaught Error " + jqXHR.responseText + ".</div>");
												}
											}
										}
									);
									
								}
								else
								{
									$("#receiveitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" + err + "</div>");
								}
							});
							
							function isDate(txtDate)
							{
								var currVal = txtDate;
									if(currVal == "")
										return false;
							   
								var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; 
								var dtArray = currVal.match(rxDatePattern); // is format OK?

								if (dtArray == null)
									return false;
							 
								//Checks for mm/dd/yyyy format.
								dtMonth = dtArray[1];
								dtDay= dtArray[3];
								dtYear = dtArray[5];

								if (dtMonth < 1 || dtMonth > 12)
									return false;
								else if (dtDay < 1 || dtDay> 31)
									return false;
								else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
									return false;
								else if (dtMonth == 2)
								{
									var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
									if (dtDay> 29 || (dtDay ==29 && !isleap))
										return false;
								}
								return true;
							}
						</script>';
	
			$server_response[] = array('isdataobtained' => 1, 'message' => $receivegoodsformdata);
			echo json_encode($server_response);
		}
		catch(Exception $e)
		{
			$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Receive Item Goods Form Load Error Occured. Try Again</div>";
			$server_response[] = array('isdataobtained' => 0, 'message' => $errormessage);
			echo json_encode($server_response);
			exit();
		}
		
	}
	else
	{
		$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>".$err."</div>";
		$server_response[] = array('isdataobtained' => 0, 'message' => $errormessage);
		echo json_encode($server_response);
	}
?>