<?php
	header('Content-Type: application/json');
	include("includes/dbconfig.php");
	
	session_write_close();
	
	$err = "";
	
	$server_response = array();
	
	$receipt = $_POST['receipt'];
	$recversion = $_POST['recversion'];
	
	if(isset($_SESSION['connecteduserid']))
	{
		if($_SESSION["connectedusergroup"] == 1 || $_SESSION["connectedusergroup"] == 3)
		{
			if($receipt == "")
			{
				$err = $err."Receipt Identification Required!<br>";
			}
			else
			{
				$receiptdata = DB::queryFirstRow("SELECT value_date, receipt_number, shop, customer_name, bill, is_cancelled FROM cash_receipt WHERE id=%i", $receipt);
			
				if(DB::count() != 1)
				{
					$err = $err."Receipt Not Identified!<br>";
				}
				else
				{
					if($receiptdata['is_cancelled'] == 1)
						$err = $err."Receipt Is Already Cancelled!<br>";
						
					if($_SESSION["connectedusergroup"] == 3 && $receiptdata['shop'] != $_SESSION["connecteduserbranch"])
						$err = $err."You Cannot Cancel Receipts In A Shop Other Than Yours!<br>";
				}
			}
		}
		else
		{
			$err = $err."Limited Access!<br>";
		}
	}
	else
	{
		$err = $err."Un Authenticated User Access Detected!<br>";
	}

	if($err == "")
	{
		try
		{
			$receiptcancelformdata = '<div class="modal-header">
							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
							<h4 class="modal-title text-center">Receipt Cancel Form</h4>
						</div>
						<div class="modal-body">
							<div id="receiptcancelerrormessage">
							</div>
							
							<div class="row">
								<div class="col-sm-3">
									<b>Receipt Number </b>
								</div>
								
								<div class="col-sm-3">
									'.$receiptdata['receipt_number'].'
								</div>
								
								<div class="col-sm-3">
									<b>Receipt Date </b>
								</div>
					
								<div class="col-sm-3">
									'.$receiptdata['value_date'].'
								</div>
							</div>					
							<div class="col-md-12" style="margin-top: 15px"></div>
							<div class="row">
								<div class="col-sm-3">
									<b>Customer </b>
								</div>
								
								<div class="col-sm-3">
									'.$receiptdata['customer_name'].' 
								</div>
								
								<div class="col-sm-3">
									<b>Receipt Amount </b>
								</div>
								
								<div class="col-sm-3">
									'.number_format($receiptdata['bill'], 2).'
								</div>
							</div>
							<div class="col-md-12" style="margin-top: 15px"></div>
							
							<div class="form-group">
								<label for="cancelreason">Cancel Reason</label>
								<textarea name="cancelreason" id="cancelreason" class="form-control" rows="3" maxlength="195" ></textarea>
							</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>
						
						<!-- 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){
								$("#receiptcancelerrormessage").html("");
							});
							
							$("#mediummodal").on("shown.bs.modal", function (e){
								$("#cancelreason").focus();
							});
							
							$("#savebtn").click(function()
							{
								var err = "";
							
								$("#receiptcancelerrormessage").html("");
									
								if($("#cancelreason").val().trim() == "")
									err += "Cancel Reason Required!<br>";
								
								if(err == "")
								{
									$("#receiptcancelerrormessage").html("");
								
									$.ajax
									(
										{
											url: "cancelreceiptsave.php",
											async: false, 
											type: "POST",
											dataType: "json",
											data: {cancelreason: $("#cancelreason").val().trim(), receipt: ' . $receipt . ', recversion: ' . $recversion . '},
											success: function(json)
											{
												if(json[0].issaved == 0)
												{
													$("#receiptcancelerrormessage").html(json[0].message);
												}
												else
												{
													$("#receiptcancelerrormessage").html(json[0].message);
													location.reload(true);
												}
											},
											error: function(jqXHR, exception)
											{	
												if (jqXHR.status === 0) 
												{
													$("#receiptcancelerrormessage").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) 
												{
													$("#receiptcancelerrormessage").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) 
												{
													$("#receiptcancelerrormessage").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") 
												{
													$("#receiptcancelerrormessage").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") 
												{
													$("#receiptcancelerrormessage").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") 
												{
													$("#receiptcancelerrormessage").html("<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>Ajax Request Aborted.</div>");
												} 
												else 
												{
													$("#receiptcancelerrormessage").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
								{
									$("#receiptcancelerrormessage").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' => $receiptcancelformdata);
			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>Receipt Cancel 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);
	}
?>