<?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 INNER JOIN stock_item ON item_stock_level.item = stock_item.id   WHERE item_stock_level.shop IS NULL AND item_stock_level.id=%i", $stockitem);
			
				if(DB::count() != 1)
				{
					$err = $err."Stock Item Not Identified!<br>";
				}
				 
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}

	if($err == "")
	{
		try
		{
			$shopoptions = "";
			
			$shopdata = DB::query("SELECT id, CONCAT(full_name, ' (', shop_code, ')') AS shop_name FROM shop WHERE is_active = 1");
			
			foreach ($shopdata as $shopoption)
			{
				$shopoptions .= '<option value="' . $shopoption['id'] . '">' . $shopoption['shop_name'] . '</option>';
			}
			
			$transfergoodsformdata = '<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title text-center">Item Transfer To Shop Form</h4>
						</div>
						<div class="modal-body">
							<div id="transferitemerrormessage">
							</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>Stock 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-3">
									<div class="form-group">
										<label for="valuedate">Transfer Date (mm/dd/yyyy)</label>
										<input type="text" name="valuedate" id="valuedate" value="'.date('m/d/Y').'"  class="form-control" data-inputmask="\'alias\': \'mm/dd/yyyy\'" data-mask />
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-3">
									<div class="form-group">
										<label for="transfernumber">Transfer Number</label>
										<input type="text" name="transfernumber"  value="'.$stockitemdata['item_code'].'" id="transfernumber" class="form-control" maxlength="195" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-3">
									<div class="form-group">
										<label for="shop">Destination Shop</label>
										<select  class="form-control" name="shop" id="shop" data-placeholder="Choose One">
											<option value="">Choose One</option>
											' . $shopoptions . '
										</select>
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-3">
									<div class="form-group">
										<label for="quantity">Transfer 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>
							
							<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>
						
						
						
						<!-- 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>
						<!-- 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>
							//Datemask2 mm/dd/yyyy
							$("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
							//Money Euro
							$("[data-mask]").inputmask();
						
							$("#largemodal").on("hidden.bs.modal", function (e){
								$("#transferitemerrormessage").html("");
							});
							
							$("#largemodal").on("shown.bs.modal", function (e){
								$("#valuedate").focus();
							});
							
							$("#quantity").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							
							$("#savebtn").click(function()
							{
								var err = "";
							
								$("#transferitemerrormessage").html("");
								
								if($("#valuedate").val().trim() == "")
								{
									err += "Transfer Date Required!<br>";
								}
								else
								{
									if(!isDate($("#valuedate").val().trim()))
									{
										err += "Valid Transfer Date Required!<br>";
									}
									else
									{
										var boundarydate = new Date();
										var testdate = new Date($("#valuedate").val().trim());
									
										if(testdate.getTime() > boundarydate.getTime())
											err += "Transfer Date Greater Than The Current Date Not Supported!<br>";
									}
								}
								
								if($("#shop").val() == "")
									err += "Destination Shop Required!<br>";
									
								if($("#quantity").val() == "")
								{
									err += "Transfer Quantity Required!<br>";
								}
								else
								{
									if(parseFloat($("#quantity").val().replace(/[^0-9\.]/g,"")) > parseFloat('.$stockitemdata['quantity'].'))
										err += "Transfer Quantity Not Exceeding Stock Quantity Required!<br>";
								}
								
								if(err == "")
								{
									$("#transferitemerrormessage").html("");
								
									$.ajax
									(
										{
											url: "itemtransfertoshopsavenew.php",
											async: false, 
											type: "POST",
											dataType: "json",
											data: {valuedate: $("#valuedate").val().trim(), transfernumber: $("#transfernumber").val().trim(), shop: $("#shop").val(), quantity: $("#quantity").val().trim(), memo: $("#memo").val().trim(), stockitem: ' . $stockitem . ', recversion: ' . $recversion . '},
											success: function(json)
											{
												if(json[0].issaved == 0)
												{
													$("#transferitemerrormessage").html(json[0].message);
												}
												else
												{
													$("#transferitemerrormessage").html(json[0].message);
													window.location.reload(true); 
												}
											},
											error: function(jqXHR, exception)
											{	
												if (jqXHR.status === 0) 
												{
													$("#transferitemerrormessage").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) 
												{
													$("#transferitemerrormessage").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) 
												{
													$("#transferitemerrormessage").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") 
												{
													$("#transferitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Requested JSON Parse Failed" + jqXHR.responseText + ".</div>");
												} 
												else if (exception === "timeout") 
												{
													$("#transferitemerrormessage").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") 
												{
													$("#transferitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Ajax Request Aborted.</div>");
												} 
												else 
												{
													$("#transferitemerrormessage").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
								{
									$("#transferitemerrormessage").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' => $transfergoodsformdata);
			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>Item Transfer To Shop 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);
	}
?>