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

	if($err == "")
	{
		try
		{
			$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 Price Form</h4>
						</div>
						<div class="modal-body">
							<div id="priceerrormessage">
							</div>
							
							<div class="row">
								<div class="col-sm-3">
									<b>Item Name </b>
								</div>
								
								<div class="col-sm-9">
									'.$stockitemdata['item_name'].'
								</div>
							</div>
							<div class="col-md-12" style="margin-top: 15px"></div>
							<div class="row">
								<div class="col-sm-3">
									<b>Item Code </b>
								</div>
					
								<div class="col-sm-9">
									'.$stockitemdata['item_code'].'
								</div>
							</div>
							<div class="col-md-12" style="margin-top: 15px"></div>
							<div class="row">
								<div class="col-sm-3">
									<b>Barcode </b>
								</div>
								
								<div class="col-sm-9">
									'.$barcode.'
								</div>
							</div>
							
							<div class="col-md-12" style="margin-top: 15px"></div>
							
							<div class="row">
								<div class="col-sm-6">
									<div class="form-group">
										<label for="costprice">Cost Price</label>
										<input type="text" name="costprice" id="costprice" class="form-control" value="'.$stockitemdata['cost_price'].'" >
									</div><!-- form-group -->
								</div>
								
								<div class="col-sm-6">
									<div class="form-group">
										<label for="sellprice">Sell Price</label>
										<input type="text" name="sellprice" id="sellprice" class="form-control" value="'.$stockitemdata['sell_price'].'" >
									</div><!-- form-group -->
								</div>
							</div>
						</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>
						
						<!-- 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>
							$("#mediummodal").on("hidden.bs.modal", function (e){
								$("#priceerrormessage").html("");
							});
							
							$("#mediummodal").on("shown.bs.modal", function (e){
								$("#costprice").focus();
							});
							
							$("#costprice").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							
							$("#sellprice").priceFormat({
								prefix: "",
								thousandsSeparator: ",",
								centsLimit: 2,
								clearOnEmpty: true
							});
							
							$("#savebtn").click(function()
							{
								var err = "";
							
								$("#priceerrormessage").html("");
									
								if($("#sellprice").val() == "")
								{
									err += "Sell Price Required!<br>";
								}
								else
								{
									if(parseFloat($("#sellprice").val().replace(/[^0-9\.]/g,"")) <= 0)
										err += "Sell Price Greater Than Zero Required!<br>";
								}
								
								if(err == "")
								{
									$("#priceerrormessage").html("");
								
									$.ajax
									(
										{
											url: "pricesetupsave.php",
											async: false, 
											type: "POST",
											dataType: "json",
											data: {costprice: $("#costprice").val().trim(), sellprice: $("#sellprice").val().trim(), stockitem: ' . $stockitem . ', recversion: ' . $recversion . '},
											success: function(json)
											{
												if(json[0].issaved == 0)
												{
													$("#priceerrormessage").html(json[0].message);
												}
												else
												{
													$("#priceerrormessage").html(json[0].message);
													window.location.reload(true); 
												}
											},
											error: function(jqXHR, exception)
											{	
												if (jqXHR.status === 0) 
												{
													$("#priceerrormessage").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) 
												{
													$("#priceerrormessage").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) 
												{
													$("#priceerrormessage").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") 
												{
													$("#priceerrormessage").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") 
												{
													$("#priceerrormessage").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") 
												{
													$("#priceerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Ajax Request Aborted.</div>");
												} 
												else 
												{
													$("#priceerrormessage").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
								{
									$("#priceerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" + err + "</div>");
								}
							});
							
						</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 Price 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);
	}
?>