<?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"] == 2 || $_SESSION["connectedusergroup"] == 3 || $_SESSION["connectedusergroup"] == 1)
		{
			if($stockitem == "")
			{
				$err = $err."Item Identification Required!<br>";
			}
			else
			{
				
				
				$stockitemdata = DB::queryFirstRow("SELECT stock_item.status, item_stock_level.shop,   stock_item.item_name, stock_item.item_code, stock_item.bar_code, item_stock_level.quantity FROM item_stock_level INNER JOIN stock_item ON item_stock_level.item = stock_item.id  WHERE item_stock_level.id=%i", $stockitem);
			
				if(DB::count() != 1)
				{
					$err = $err."Stock Item Not Identified!<br>";
				}
				else
				{
					 
				}
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}

	if($err == "")
	{
		try
		{
			$items_off_stock  = 0;//store no sold off given away damanges and debit sale items
			
				
												 
												  $item_id = DB::query("SELECT  id from stock_item WHERE item_code   = ".$stockitemdata['item_code']."  ");
												  foreach($item_id as $rowi)
												{
					
													
													$item_price_id = DB::query("SELECT  id, shop from item_price WHERE   item   = ".$rowi['id']."  ");
													 foreach($item_price_id as $rowid)
												        {
					
			
															$item_id = DB::query("SELECT  IFNULL(SUM(quantity) , 0) as qty FROM cash_sale_item WHERE price_id   = ".$rowid['id']."  ");
															 
															  $items_off_stock  +=  intval($item_id[0]['qty']);
			
	
				 
															   
															  //$special_sales = DB::query('SELECT  IFNULL(SUM(quantity) , 0)  as qty FROM special_sale_item WHERE  is_cancelled ="0" AND price_id   = '.$rowid['id'].'  AND shop = '.$stockitemdata['shop'].' ');
															  
                                                               $special_sales = DB::query('SELECT  IFNULL(SUM(quantity) , 0)  as qty FROM special_sale_item WHERE  is_cancelled =0 AND price_id   = '.$rowid['id'].'  AND shop = '.$rowid['shop'].' ');
															  															  
					
															   
															    $items_off_stock  +=  intval($special_sales[0]['qty']);
																
																
															   
															   
															   $debit_sales = DB::query('SELECT  SUM(quantity) as qty FROM deposit_sale_item WHERE  is_cancelled ="0" AND price_id   = '.$rowid['id'].' AND   shop = '.$rowid['shop'].'  ');
															 
															 
															  $items_off_stock  +=  $debit_sales[0]['qty'];
															 
															 //customer_claims
															 $claim_sales = DB::query('SELECT  COUNT(id) as qty FROM customer_claims WHERE   product_id   = '.$rowi['id'].' AND   shop_id = '.$rowid['shop'].'  ');
															 
															 
															  $items_off_stock  +=   $claim_sales[0]['qty'];
															  
															  
															
															
															
														}    
												} 
												
													
												 
													 
			$adjustmentformdata = '<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title text-center">Item Adjustment Form</h4>
						</div>
						<div class="modal-body">
							<div id="adjustmentitemerrormessage">
							</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 At Hand </b>
								</div>
								
								<div class="col-sm-2">
									'.(number_format($stockitemdata['quantity'], 2) -  $items_off_stock ).'
								</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">Change Date (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-3">
									<div class="form-group">
										<label for="referencenumber">Reference Number</label>
										<input type="text" name="referencenumber" id="referencenumber" class="form-control" maxlength="195" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-3">
									<div class="form-group">
										<label for="adjustmenttype">Adjustment Type</label>
										<select  class="form-control" name="adjustmenttype" id="adjustmenttype" data-placeholder="Choose One">
											<option value="">Choose One</option>
											<option value="1">Addition</option>
											<option value="0">Reduction</option>
										</select>
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-3">
									<div class="form-group">
										<label for="quantity">Adjustment 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">
										<label for="memo">Memo</label>
										<input type="text" name="memo" id="memo" class="form-control" maxlength="195" >
									</div><!-- form-group -->
								</div>
								
								<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){
								$("#adjustmentitemerrormessage").html("");
							});
							
							$("#largemodal").on("shown.bs.modal", function (e){
								$("#valuedate").focus();
							});
							
							$("#quantity").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							
							$("#savebtn").click(function()
							{
								var err = "";
							
								$("#adjustmentitemerrormessage").html("");
								
								if($("#valuedate").val().trim() == "")
								{
									err += "Adjustment Date Required!<br>";
								}
								else
								{
									if(!isDate($("#valuedate").val().trim()))
									{
										err += "Valid Adjustment Date Required!<br>";
									}
									else
									{
										var boundarydate = new Date();
										var testdate = new Date($("#valuedate").val().trim());
									
										if(testdate.getTime() > boundarydate.getTime())
											err += "Adjustment Date Greater Than The Current Date Not Supported!<br>";
									}
								}
								
								if($("#adjustmenttype").val() == "")
									err += "Adjustment Type Required!<br>";
									
								if($("#quantity").val() == "")
								{
									err += "Adjustment Quantity Required!<br>";
								}
								else
								{
									if($("#adjustmenttype").val() == "0" && (parseFloat($("#quantity").val().replace(/[^0-9\.]/g,"")) > parseFloat('.$stockitemdata['quantity'].')))
										err += "Reduction Quantity Not Exceeding Stock Quantity Required!<br>";
								}
								
								if(err == "")
								{
									$("#adjustmentitemerrormessage").html("");
								
									$.ajax
									(
										{
											url: "itemadjustmentsave.php",
											async: false, 
											type: "POST",
											dataType: "json",
											data: {valuedate: $("#valuedate").val().trim(), referencenumber: $("#referencenumber").val().trim(), adjustmenttype: $("#adjustmenttype").val(), quantity: $("#quantity").val().trim(), memo: $("#memo").val().trim(), stockitem: ' . $stockitem . ', recversion: ' . $recversion . '},
											success: function(json)
											{
												if(json[0].issaved == 0)
												{
													$("#adjustmentitemerrormessage").html(json[0].message);
												}
												else
												{
													$("#adjustmentitemerrormessage").html(json[0].message);
													window.location.reload(true);
												}
											},
											error: function(jqXHR, exception)
											{	
												if (jqXHR.status === 0) 
												{
													$("#adjustmentitemerrormessage").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) 
												{
													$("#adjustmentitemerrormessage").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) 
												{
													$("#adjustmentitemerrormessage").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") 
												{
													$("#adjustmentitemerrormessage").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") 
												{
													$("#adjustmentitemerrormessage").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") 
												{
													$("#adjustmentitemerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Ajax Request Aborted.</div>");
												} 
												else 
												{
													$("#adjustmentitemerrormessage").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
								{
									$("#adjustmentitemerrormessage").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' => $adjustmentformdata);
			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 Adjustment 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);
	}
?>