<?php
	include("includes/dbconfig.php");
	$pagetitle = "Shop Setup";
	require('includes/applicationtop.php');
	require('includes/applicationmenu.php');
	
	$err= "";
	
	$successsave="";
	
	if(isset($_POST['shopfocus']))
	{
		$shopfocus = $_POST['shopfocus'];
	}
	
	if(!(isset($_POST['savedatabtn'])) && (isset($shopfocus) && $shopfocus > 0))
	{
		$shopdata = DB::queryFirstRow("SELECT full_name, shop_code, logo_file, address_line_1, address_line_2, address_line_3, zip_code, city, country, tin, phone, fax, email, is_active, version FROM shop WHERE id=%i", $shopfocus);
		
		if(DB::count() == 1)
		{   
			$_POST['shopfocus'] = $shopfocus;
			$_POST['shopname'] = ($shopdata['full_name'] != "") ? $shopdata['full_name'] : "";
			$_POST['shopcode'] = ($shopdata['shop_code'] != "") ? $shopdata['shop_code'] : "";
			$_POST['status'] = $shopdata['is_active'];
			$_POST['currentlogo'] = ($shopdata['logo_file'] != "") ? $shopdata['logo_file'] : "";
			$_POST['addressline1'] = ($shopdata['address_line_1'] != "") ? $shopdata['address_line_1'] : "";
			$_POST['addressline2'] = ($shopdata['address_line_2'] != "") ? $shopdata['address_line_2'] : "";
			$_POST['addressline3'] = ($shopdata['address_line_3'] != "") ? $shopdata['address_line_3'] : "";
			$_POST['postalcode'] = ($shopdata['zip_code'] != "") ? $shopdata['zip_code'] : "";
			$_POST['city'] = ($shopdata['city'] != "") ? $shopdata['city'] : "";
			$_POST['country'] = ($shopdata['country'] != "") ? $shopdata['country'] : "";
			$_POST['tin'] = ($shopdata['tin'] != "") ? $shopdata['tin'] : "";
			$_POST['phone'] = ($shopdata['phone'] != "") ? $shopdata['phone'] : "";
			$_POST['fax'] = ($shopdata['fax'] != "") ? $shopdata['fax'] : "";
			$_POST['email'] = ($shopdata['email'] != "") ? $shopdata['email'] : "";
			$_POST['recversion'] = $shopdata['version'];
		}
	}
	
	if(isset($_POST['savedatabtn']))
	{
		if($_SESSION["connectedusergroup"] == 1)
		{
			if(trim($_POST['shopname']) == "")
				$err = $err."Shop Name Required!<br>";
				
			if(trim($_POST['shopcode']) == "")
			{
				$err = $err."Shop Code Required!<br>";
			}
			else
			{
				if($shopfocus == 0)
				{
					if(DB::queryFirstField("SELECT COUNT(id) FROM shop WHERE shop_code=%s", trim($_POST['shopcode'])) > 0)
						$err = $err."Shop Code Already Exists!<br>";
				}
				else
				{
					if(DB::queryFirstField("SELECT COUNT(id) FROM shop WHERE shop_code=%s AND id!=%i", trim($_POST['shopcode']), $shopfocus) > 0)
						$err = $err."Shop Code Already Exists!<br>";
				}
			}
			
			if($_POST['status'] == "")
				$err = $err."Status Required!<br>";

			if(trim($_POST['email'])!="")
			{
				if(!filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL))
				{
					$err = $err."Valid Email Address Required!<br>";
				}
			}
			
			if($err == "")
			{
				$shoplogofile = "";
				
				DB::$error_handler = false;
				DB::$throw_exception_on_error = true;
			
				if($shopfocus == 0)
				{
					try
					{
						DB::startTransaction();
						DB::query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
						DB::insert
						('shop', 
							array
							(
								'created_by' => $_SESSION["connecteduserid"],
								'full_name' => (trim($_POST['shopname']) != "") ? trim($_POST['shopname']) : NULL,
								'shop_code' => trim($_POST['shopcode']),
								'address_line_1' => (trim($_POST['addressline1']) != "") ? trim($_POST['addressline1']) : NULL,
								'address_line_2' => (trim($_POST['addressline2']) != "") ? trim($_POST['addressline2']) : NULL,
								'address_line_3' => (trim($_POST['addressline3']) != "") ? trim($_POST['addressline3']) : NULL,
								'zip_code' => (trim($_POST['postalcode']) != "") ? trim($_POST['postalcode']) : NULL,
								'city' => (trim($_POST['city']) != "") ? trim($_POST['city']) : NULL,
								'country' => (trim($_POST['country']) != "") ? trim($_POST['country']) : NULL,
								'tin' => (trim($_POST['tin']) != "") ? trim($_POST['tin']) : NULL,
								'phone' => (trim($_POST['phone']) != "") ? trim($_POST['phone']) : NULL,
								'fax' => (trim($_POST['fax']) != "") ? trim($_POST['fax']) : NULL,
								'email' => (trim($_POST['email']) != "") ? trim($_POST['email']) : NULL,
								'is_active' => ($_POST['status'] == 1) ? 1 : 0
							)
						);
						
						$recid = DB::insertId();
						
						DB::insert
						('cash_sale_receipt_number_seq', 
							array
							(
								'id' => $recid
							)
						);
						
						if($_FILES['file']['name'])
						{
							if($_FILES["file"]["error"] == 0)
							{
								$temp = explode(".", $_FILES["file"]["name"]);
								$extension = end($temp);
								$shoplogofile = $recid . "." . $extension;
								move_uploaded_file($_FILES["file"]["tmp_name"], "images/shoplogos/" . $recid . "." . $extension);
							}
						}
						
						if($shoplogofile != "")
						{
							DB::query("UPDATE shop SET logo_file=%s WHERE id=%i", $shoplogofile, $recid);
						}
						
						$items = DB::query("SELECT id, default_cost_price, default_sell_price FROM stock_item");
						
						foreach($items as $item)
						{
							DB::insert
							('item_stock_level', 
								array
								(
									'created_by' => $_SESSION["connecteduserid"], 
									'shop' => $recid, 
									'item' => $item['id'],
									'quantity' => 0
								)
							);
							
							DB::insert
							('item_price', 
								array
								(
									'created_by' => $_SESSION["connecteduserid"],
									'shop' => $recid,
									'item' => $item['id'],
									'cost_price' => $item['default_cost_price'],
									'sell_price' => $item['default_sell_price']
								)
							);
						}
						
						DB::commit();
						
						$successsave="New Shop Successfully Saved!";
						
						unset($_POST['shopfocus']);
						unset($_POST['shopname']);
						unset($_POST['shopcode']);
						unset($_POST['status']);
						unset($_POST['addressline1']);
						unset($_POST['addressline2']);
						unset($_POST['addressline3']);
						unset($_POST['postalcode']);
						unset($_POST['city']);
						unset($_POST['country']);
						unset($_POST['tin']);
						unset($_POST['phone']);
						unset($_POST['fax']);
						unset($_POST['email']);
						unset($_POST['recversion']);
					}
					catch(MeekroDBException $e)
					{
						$err = $err."Critical Error Occured!<br>";
						$err = $err.$e->getMessage()."<br>";
						$err = $err.$e->getQuery()."<br>";
						DB::rollback();
						DB::$error_handler = 'meekrodb_error_handler';
						DB::$throw_exception_on_error = false;
					}
				}
				else
				{
					try
					{
						$trxnConnextn = new MeekroDB();
						$nonTrxnConnextn = new MeekroDB();
						
						$trxnConnextn->startTransaction();
						$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
						$trxnConnextn->query("SELECT * FROM shop WHERE id=%i FOR UPDATE", $_POST['shopfocus']);
						
						$trxnConnextn->update
						('shop', 
							array
							(
								'updated_date' => $trxnConnextn->sqleval("current_timestamp()"),
								'updated_by' => $_SESSION['connecteduserid'], 
								'full_name' => (trim($_POST['shopname']) != "") ? trim($_POST['shopname']) : NULL,
								'shop_code' => trim($_POST['shopcode']),
								'address_line_1' => (trim($_POST['addressline1']) != "") ? trim($_POST['addressline1']) : NULL,
								'address_line_2' => (trim($_POST['addressline2']) != "") ? trim($_POST['addressline2']) : NULL,
								'address_line_3' => (trim($_POST['addressline3']) != "") ? trim($_POST['addressline3']) : NULL,
								'zip_code' => (trim($_POST['postalcode']) != "") ? trim($_POST['postalcode']) : NULL,
								'city' => (trim($_POST['city']) != "") ? trim($_POST['city']) : NULL,
								'country' => (trim($_POST['country']) != "") ? trim($_POST['country']) : NULL,
								'tin' => (trim($_POST['tin']) != "") ? trim($_POST['tin']) : NULL,
								'phone' => (trim($_POST['phone']) != "") ? trim($_POST['phone']) : NULL,
								'fax' => (trim($_POST['fax']) != "") ? trim($_POST['fax']) : NULL,
								'email' => (trim($_POST['email']) != "") ? trim($_POST['email']) : NULL,
								'is_active' => ($_POST['status'] == 1) ? 1 : 0,
								'version' => ($_POST['recversion'] + 1)
							), 
							"id=%i", $_POST['shopfocus']
						);
						
						$shopversionrow = $nonTrxnConnextn->queryFirstRow("SELECT version FROM shop WHERE id=%i LIMIT 1", $_POST['shopfocus']);
						
						if($shopversionrow['version'] == $_POST['recversion'])
						{
							if($_FILES['file']['name'])
							{
								if($_FILES["file"]["error"] == 0)
								{
									$temp = explode(".", $_FILES["file"]["name"]);
									$extension = end($temp);
									$shoplogofile = $_POST['shopfocus'] . "." . $extension;
									
									if(file_exists("images/shoplogos/" . $_POST['currentlogo']))
										unlink("images/shoplogos/" . $_POST['currentlogo']);
			
									move_uploaded_file($_FILES["file"]["tmp_name"], "images/shoplogos/" . $_POST['shopfocus'] . "." . $extension);
								}
							}
							
							if($shoplogofile != "")
							{
								$trxnConnextn->query("UPDATE shop SET logo_file=%s WHERE id=%i", $shoplogofile, $_POST['shopfocus']);
							}
						
							$trxnConnextn->commit();
?>
							<script>
								location.href="shops.php";
							</script>
<?php
							exit();
						}
						else
						{
							$trxnConnextn->rollback();
							$err = "Shop Details Could Not Be Updated Due To Updates Just Done By Another System User!<br>";
						}
					}
					catch(MeekroDBException $e)
					{
						$err = $err."Critical Error Occured!<br>";
						$err = $err.$e->getMessage()."<br>";
						$err = $err.$e->getQuery()."<br>";
						$trxnConnextn->rollback();
						DB::$error_handler = 'meekrodb_error_handler';
						DB::$throw_exception_on_error = false;
					}
				}
			}
		}
		else
		{
			$err = $err."Limited Acccess!<br>";
		}
	}
?>
			<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<!-- Content Header (Page header) -->
				<section class="content-header">
					<h1>Shop Setup</h1>
					<ol class="breadcrumb">
					</ol>
				</section>

				<!-- Main content -->
				<section class="content">
					<!-- Default box -->
					  <div class="card">
						<?php
							if($_SESSION["connectedusergroup"] == 1)
							{
						?>
						<div class="card-header with-border text-center">
							<h3 class="card-title">Shop Setup Form</h3>
						</div>
						
						<div class="card-body">
							<?php
								if($err!="")
								{
							?>
							<div class="alert alert-danger alert-dismissable">
								<i class="glyphicon glyphicon-ban-circle"></i>
								<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><br>
								<?php 
									echo $err; 
								?>
							</div>
							<?php
								}
							?>
							
							<?php
								if($successsave!="")
								{
							?>
							<div class="alert alert-success alert-dismissable">
								<i class="glyphicon glyphicon-ok"></i>
								<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
								<?php 
									echo $successsave; 
								?>
							</div>
							<?php
								}
							?>
							<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
								<INPUT name="shopfocus" id="shopfocus" type=hidden value="<?php echo isset($_POST['shopfocus']) ? $_POST['shopfocus'] : 0 ?>">
								<INPUT name="recversion" id="recversion" type=hidden value="<?php echo isset($_POST['recversion']) ? $_POST['recversion'] : 0 ?>">
							<div class="row">
								<div class="col-sm-6">
									<div class="col-sm-8">
										<div class="form-group">
											<label for="shopname">Shop Name</label>
											<input type="text" name="shopname" id="shopname" maxlength="100" class="form-control" value="<?php echo isset($_POST['shopname']) ? $_POST['shopname'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="shopcode">Shop Code</label>
											<input type="text" name="shopcode" id="shopcode" maxlength="3" class="form-control" value="<?php echo isset($_POST['shopcode']) ? $_POST['shopcode'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="status">Status</label>
											<select  class="form-control" name="status" id="status" data-placeholder="Choose One">
												<option value="">Choose One</option>
												<option <?php if(isset($_POST['status']) && "1"==$_POST['status']) echo "selected=\"selected\""; ?> value="1">Active</option>
												<option <?php if(isset($_POST['status']) && "0"==$_POST['status']) echo "selected=\"selected\""; ?> value="0">Inactive</option>
											</select>
										</div><!-- form-group -->
									</div>
									
									<INPUT name="currentlogo" id="currentlogo" type=hidden value="<?php echo isset($_POST['currentlogo']) ? $_POST['currentlogo'] : "" ?>">
									
									<div class="col-sm-4">
										<div class="row col-sm-12">
											<label >Shop Logo</label>
											<div style="height: 100px width: 100px">
												<img class="img-thumbnail" id="userphoto" src="<?php echo (isset($_POST['currentlogo']) && $_POST['currentlogo'] != "") ? "images/shoplogos/" . $_POST['currentlogo'] : "images/shoplogos/noimage.gif" ?>" alt="..." style="width: 100%;max-height: 100%">
											</div>
										</div>
										
										<div class="row">	
											<div class="form-group">
												<div class="col-sm-12">
													<input name="file" type="file" id="file" accept="image/jpg,image/png,image/jpeg,image/gif"/>
												</div>
											</div><!-- form-group -->
										</div>
									</div>
									
									<div class="col-sm-12">
										<div class="form-group">
											<label for="addressline1">Address Line 1</label>
											<input type="text" name="addressline1" id="addressline1" maxlength="95" class="form-control" value="<?php echo isset($_POST['addressline1']) ? $_POST['addressline1'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="addressline2">Address Line 2</label>
											<input type="text" name="addressline2" id="addressline2" maxlength="95" class="form-control" value="<?php echo isset($_POST['addressline2']) ? $_POST['addressline2'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="addressline3">Address Line 3</label>
											<input type="text" name="addressline3" id="addressline3" maxlength="95" class="form-control" value="<?php echo isset($_POST['addressline3']) ? $_POST['addressline3'] : "" ?>" >
										</div><!-- form-group -->
									</div>
								</div>
								
								<div class="col-sm-6">
									<div class="col-sm-12">
										<div class="form-group">
											<label for="postalcode">Postal Code</label>
											<input type="text" name="postalcode" id="postalcode" maxlength="95" class="form-control" value="<?php echo isset($_POST['postalcode']) ? $_POST['postalcode'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="city">City/Town</label>
											<input type="text" name="city" id="city" maxlength="95" class="form-control" value="<?php echo isset($_POST['city']) ? $_POST['city'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="country">Country</label>
											<input type="text" name="country" id="country" maxlength="95" class="form-control" value="<?php echo isset($_POST['country']) ? $_POST['country'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="tin">Tax Identification Number (TIN)</label>
											<input type="text" name="tin" id="tin" maxlength="95" class="form-control" value="<?php echo isset($_POST['tin']) ? $_POST['tin'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="row">
											<div class="form-group col-sm-6">
												<label for="phone">Telephone Number</label>
												<input type="text" name="phone" id="phone" maxlength="45" class="form-control" value="<?php echo isset($_POST['phone']) ? $_POST['phone'] : "" ?>" >
											</div><!-- form-group -->
											
											<div class="form-group col-sm-6">
												<label for="fax">Fax Number</label>
												<input type="text" name="fax" id="fax" maxlength="45" class="form-control" value="<?php echo isset($_POST['fax']) ? $_POST['fax'] : "" ?>" >
											</div><!-- form-group -->
										</div>
									
										<div class="form-group">
											<label for="email">Email Address</label>
											<input type="text" name="email" id="email" maxlength="95" class="form-control" value="<?php echo isset($_POST['email']) ? $_POST['email'] : "" ?>" >
										</div><!-- form-group -->
									</div>
								</div>
							</div>
						</div><!-- /.box-body -->
						
						<div class="box-footer">
							
							<div class="btn-list">
							<div class="text-right">
								<a href="shops.php" class="btn btn-danger"><i class="glyphicon glyphicon-remove"></i> Cancel</a>
								
								<button type="submit" name="savedatabtn" id="savedatabtn" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
							</div>
							</div>
						</div><!-- /.box-footer-->
							</form>
						<?php
							}
							else
							{
						?>
						<div class="alert alert-danger alert-dismissable">
							<i class="glyphicon glyphicon-ban-circle"></i><br>
							Limited Access
						</div>
						<?php
							}
						?>
					</div><!-- /.box -->
				</section><!-- /.content -->
			</div><!-- /.content-wrapper -->

			
		 

				<?php include ('includes/general_footer.php')?>
		<script src="plugins/bert/storepos.js" type="text/javascript"></script>
		<script src="plugins/bert/shopsetup.js" type="text/javascript"></script>
	</body>
</html>