<?php
	include("includes/dbconfig.php");
	$pagetitle = "Item Setup";
	require('includes/applicationtop.php');
	require('includes/applicationmenu.php');
	
	$err= "";
	
	$successsave="";
	
	if(isset($_POST['itemfocus']))
	{
		$itemfocus = $_POST['itemfocus'];
	}
	
	if(!(isset($_POST['savedatabtn'])) && (isset($itemfocus) && $itemfocus > 0))
	{
		$itemdata = DB::queryFirstRow("SELECT item_name, item_code, bar_code, alt_barcode, item_image_file, description, category, measure_unit, reorder_level, default_cost_price, default_sell_price, status, version FROM stock_item WHERE id=%i", $itemfocus);
		
		if(DB::count() == 1)
		{   
			$_POST['itemfocus'] = $itemfocus;
			$_POST['itemname'] = ($itemdata['item_name'] != "") ? $itemdata['item_name'] : "";
			$_POST['itemcode'] = ($itemdata['item_code'] != "") ? $itemdata['item_code'] : "";
			$_POST['status'] = $itemdata['status'];
			$_POST['itemcurrentimage'] = ($itemdata['item_image_file'] != "") ? $itemdata['item_image_file'] : "";
			$_POST['itembarcode'] = ($itemdata['bar_code'] != "") ? $itemdata['bar_code'] : "";
			$_POST['altitembarcode'] = ($itemdata['alt_barcode'] != "") ? $itemdata['alt_barcode'] : "";
			$_POST['itemdescription'] = ($itemdata['description'] != "") ? $itemdata['description'] : "";
			$_POST['itemcat'] = $itemdata['category'];
			$_POST['unitmeasure'] = $itemdata['measure_unit'];
			$_POST['reorderlevel'] = ($itemdata['reorder_level'] != "") ? $itemdata['reorder_level'] : "";
			$_POST['costprice'] = ($itemdata['default_cost_price'] != "") ? $itemdata['default_cost_price'] : "";
			$_POST['sellprice'] = ($itemdata['default_sell_price'] != "") ? $itemdata['default_sell_price'] : "";
			$_POST['recversion'] = $itemdata['version'];
		}
	}
	
	if(isset($_POST['savedatabtn']))
	{
		if($_SESSION["connectedusergroup"] == 1)
		{
			if(trim($_POST['itemname']) == "")
				$err = $err."Item Name Required!<br>";
			
			if($_POST['status'] == "")
				$err = $err."Status Required!<br>";

			if(trim($_POST['itembarcode'])!="")
			{	
				if(DB::queryFirstField("SELECT COUNT(id) FROM stock_item WHERE alt_barcode=%s", trim($_POST['itembarcode'])) > 0)
					$err = $err."Item Barcode Already Exists!<br>";
			
				if($itemfocus == 0)
				{
					if(DB::queryFirstField("SELECT COUNT(id) FROM stock_item WHERE bar_code=%s", trim($_POST['itembarcode'])) > 0)
						$err = $err."Item Barcode Already Exists!<br>";
				}
				else
				{
					if(DB::queryFirstField("SELECT COUNT(id) FROM stock_item WHERE bar_code=%s AND id!=%i", trim($_POST['itembarcode']), $itemfocus) > 0)
						$err = $err."Item Barcode Already Exists!<br>";
				}
			}
			
			if(trim($_POST['altitembarcode'])!="")
			{	
				if(DB::queryFirstField("SELECT COUNT(id) FROM stock_item WHERE bar_code=%s", trim($_POST['altitembarcode'])) > 0)
					$err = $err."Item Barcode Already Exists!<br>";
			
				if($itemfocus == 0)
				{
					if(DB::queryFirstField("SELECT COUNT(id) FROM stock_item WHERE alt_barcode=%s", trim($_POST['altitembarcode'])) > 0)
						$err = $err."Item Barcode Already Exists!<br>";
				}
				else
				{
					if(DB::queryFirstField("SELECT COUNT(id) FROM stock_item WHERE alt_barcode=%s AND id!=%i", trim($_POST['altitembarcode']), $itemfocus) > 0)
						$err = $err."Item Barcode Already Exists!<br>";
				}
			}
			
			if(trim($_POST['itemcat']) == "")
				$err = $err."Item Category Required!<br>";
			
			if($err == "")
			{
				$itemimagefile = "";
				
				DB::$error_handler = false;
				DB::$throw_exception_on_error = true;
			
				if($itemfocus == 0)
				{
					try
					{
						DB::startTransaction();
						DB::query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
						DB::insert
						('stock_item', 
							array
							(
								'created_date' => date('Y-m-d H:i:s'),
								'created_by' => $_SESSION["connecteduserid"],
								'item_name' => (trim($_POST['itemname']) != "") ? trim($_POST['itemname']) : NULL,
								'bar_code' => (trim($_POST['itembarcode']) != "") ? trim($_POST['itembarcode']) : NULL,
								'alt_barcode' => (trim($_POST['altitembarcode']) != "") ? trim($_POST['altitembarcode']) : NULL,
								'description' => (trim($_POST['itemdescription']) != "") ? trim($_POST['itemdescription']) : NULL,
								'category' => $_POST['itemcat'],
								'measure_unit' => $_POST['unitmeasure'],
								'reorder_level' => (isset($_POST['reorderlevel']) && str_replace(",", "", trim($_POST['reorderlevel'])) > 0) ? str_replace(",", "", trim($_POST['reorderlevel'])) : 0,
								'default_cost_price' => (isset($_POST['costprice']) && str_replace(",", "", trim($_POST['costprice'])) > 0) ? str_replace(",", "", trim($_POST['costprice'])) : 0.00,
								'default_sell_price' => (isset($_POST['sellprice']) && str_replace(",", "", trim($_POST['sellprice'])) > 0) ? str_replace(",", "", trim($_POST['sellprice'])) : 0.00,
								'status' => $_POST['status']
							)
						);
						
						$recid = DB::insertId();
						
						$itemcode = (strlen(trim($_POST['itemcat'])) == 1) ? trim($_POST['itemcat']) . str_pad($recid, 8, '0', STR_PAD_LEFT) : ((strlen(trim($_POST['itemcat'])) == 2) ? trim($_POST['itemcat']) . str_pad($recid, 7, '0', STR_PAD_LEFT) : trim($_POST['itemcat']) . str_pad($recid, 6, '0', STR_PAD_LEFT));
						
						DB::update
						('stock_item', 
							array
							(
								'item_code' => $itemcode
							), 
							"id=%i", $recid
						);
						
						DB::insert
						('item_stock_level', 
							array
							(
								'created_by' => $_SESSION["connecteduserid"],
								'item' => $recid,
								'quantity' => 0,
								'is_active' => 1
							)
						);
						
						$shopsdata = DB::query("SELECT id FROM shop");
						
						foreach($shopsdata as $shoprow)
						{
							DB::insert
							('item_stock_level', 
								array
								(
									'created_by' => $_SESSION["connecteduserid"], 
									'shop' => $shoprow['id'], 
									'item' => $recid,
									'quantity' => 0,
									'is_active' => 1
								)
							);
							
							DB::insert
							('item_price', 
								array
								(
									'created_by' => $_SESSION["connecteduserid"],
									'shop' => $shoprow['id'],
									'item' => $recid,
									'cost_price' => (isset($_POST['costprice']) && str_replace(",", "", trim($_POST['costprice'])) > 0) ? str_replace(",", "", trim($_POST['costprice'])) : 0.00,
									'sell_price' => (isset($_POST['sellprice']) && str_replace(",", "", trim($_POST['sellprice'])) > 0) ? str_replace(",", "", trim($_POST['sellprice'])) : 0.00
								)
							);
						}
						
						if($_FILES['file']['name'])
						{
							if($_FILES["file"]["error"] == 0)
							{
								$temp = explode(".", $_FILES["file"]["name"]);
								$extension = end($temp);
								$itemimagefile = $recid . "." . $extension;
								move_uploaded_file($_FILES["file"]["tmp_name"], "images/stockitemimage/" . $recid . "." . $extension);
							}
						}
						
						if($itemimagefile != "")
						{
							DB::query("UPDATE stock_item SET item_image_file=%s WHERE id=%i", $itemimagefile, $recid);
						}
						
						DB::commit();
						
						$successsave="New Item Successfully Saved!";
						
						unset($_POST['itemfocus']);
						unset($_POST['itemname']);
						unset($_POST['itemcode']);
						unset($_POST['status']);
						unset($_POST['itembarcode']);
						unset($_POST['altitembarcode']);
						unset($_POST['itemdescription']);
						unset($_POST['itemcat']);
						unset($_POST['unitmeasure']);
						unset($_POST['reorderlevel']);
						unset($_POST['costprice']);
						unset($_POST['sellprice']);
						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 stock_item WHERE id=%i FOR UPDATE", $_POST['itemfocus']);
						
						$trxnConnextn->update
						('stock_item', 
							array
							(
								'updated_date' => date("Y-m-d H:i:s"),
								'updated_by' => $_SESSION['connecteduserid'], 
								'item_name' => (trim($_POST['itemname']) != "") ? trim($_POST['itemname']) : NULL,
								'item_code' => (strlen(trim($_POST['itemcat'])) == 1) ? trim($_POST['itemcat']) . str_pad($_POST['itemfocus'], 6, '0', STR_PAD_LEFT) : ((strlen(trim($_POST['itemcat'])) == 2) ? trim($_POST['itemcat']) . str_pad($_POST['itemfocus'], 5, '0', STR_PAD_LEFT) : trim($_POST['itemcat']) . str_pad($_POST['itemfocus'], 4, '0', STR_PAD_LEFT)),
								'bar_code' => (trim($_POST['itembarcode']) != "") ? trim($_POST['itembarcode']) : NULL,
								'alt_barcode' => (trim($_POST['altitembarcode']) != "") ? trim($_POST['altitembarcode']) : NULL,
								'description' => (trim($_POST['itemdescription']) != "") ? trim($_POST['itemdescription']) : NULL,
								'category' => $_POST['itemcat'],
								'measure_unit' => $_POST['unitmeasure'],
								'reorder_level' => (isset($_POST['reorderlevel']) && str_replace(",", "", trim($_POST['reorderlevel'])) > 0) ? str_replace(",", "", trim($_POST['reorderlevel'])) : 0,
								'default_cost_price' => (isset($_POST['costprice']) && str_replace(",", "", trim($_POST['costprice'])) > 0) ? str_replace(",", "", trim($_POST['costprice'])) : 0.00,
								'default_sell_price' => (isset($_POST['sellprice']) && str_replace(",", "", trim($_POST['sellprice'])) > 0) ? str_replace(",", "", trim($_POST['sellprice'])) : 0.00,
								'status' => $_POST['status'],
								'version' => ($_POST['recversion'] + 1)
							), 
							"id=%i", $_POST['itemfocus']
						);
						
						/*
						$trxnConnextn->update
						('item_price', 
							array
							(
								'updated_date' => date("Y-m-d H:i:s"),
								'updated_by' => $_SESSION['connecteduserid'], 
								'cost_price' => (isset($_POST['costprice']) && str_replace(",", "", trim($_POST['costprice'])) > 0) ? str_replace(",", "", trim($_POST['costprice'])) : 0.00,
								'sell_price' => (isset($_POST['sellprice']) && str_replace(",", "", trim($_POST['sellprice'])) > 0) ? str_replace(",", "", trim($_POST['sellprice'])) : 0.00
							), 
							"item=%i", $_POST['itemfocus']
						);
						*/
						
						$itemversionrow = $nonTrxnConnextn->queryFirstRow("SELECT version FROM stock_item WHERE id=%i LIMIT 1", $_POST['itemfocus']);
						
						if($itemversionrow['version'] == $_POST['recversion'])
						{
							if($_FILES['file']['name'])
							{
								if($_FILES["file"]["error"] == 0)
								{
									$temp = explode(".", $_FILES["file"]["name"]);
									$extension = end($temp);
									$itemimagefile = $_POST['itemfocus'] . "." . $extension;
									
									if(file_exists("images/stockitemimage/" . $_POST['itemcurrentimage']))
										unlink("images/stockitemimage/" . $_POST['itemcurrentimage']);
			
									move_uploaded_file($_FILES["file"]["tmp_name"], "images/stockitemimage/" . $_POST['itemfocus'] . "." . $extension);
								}
							}
							
							if($itemimagefile != "")
							{
								$trxnConnextn->query("UPDATE stock_item SET item_image_file=%s WHERE id=%i", $itemimagefile, $_POST['itemfocus']);
							}
						
							$trxnConnextn->commit();

							$successsave="Item Successfully Updated!";
						}
						else
						{
							$trxnConnextn->rollback();
							$err = "Item 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 Access!<br>";
		}
	}
?>
			<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<!-- Content Header (Page header) -->
				<section class="content-header">
					<h1>Item Setup</h1>
					<ol class="breadcrumb">
					</ol>
				</section>

				<!-- Main content -->
				<section class="content">
					<!-- Default card -->
					<div class="card card-primary">
					<?php
						if($_SESSION["connectedusergroup"] == 1)
						{
					?>
						<div class="card-header with-border text-center">
							<h3 class="card-title">Item Setup Form</h3>
						</div>
						
						<div class="card-body">
							<?php
								if($err!="")
								{
							?>
							<div class="alert alert-danger alert-dismissable">
								<i class="fa fa-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="fa fa-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="itemfocus" id="itemfocus" type=hidden value="<?php echo isset($_POST['itemfocus']) ? $_POST['itemfocus'] : 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="itemname">Item Name</label>
											<input type="text" name="itemname" id="itemname" maxlength="95" class="form-control" value="<?php echo isset($_POST['itemname']) ? $_POST['itemname'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group">
											<label for="itemcode">Item Code</label>
											<input type="text" name="itemcode" id="itemcode" maxlength="145" class="form-control" value="<?php echo isset($_POST['itemcode']) ? $_POST['itemcode'] : "" ?>" readonly >
										</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="itemcurrentimage" id="itemcurrentimage" type=hidden value="<?php echo isset($_POST['itemcurrentimage']) ? $_POST['itemcurrentimage'] : "" ?>">
									
									<div class="col-sm-4">
										<div class="row col-sm-12">
											<label >Item Image</label>
											<div style="height: 100px width: 100px">
												<img class="img-thumbnail" id="itemphoto" src="<?php echo (isset($_POST['itemcurrentimage']) && $_POST['itemcurrentimage'] != "") ? "images/stockitemimage/" . $_POST['itemcurrentimage'] : "images/stockitemimage/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="form-group col-sm-6">
											<label for="itembarcode">Item Barcode</label>
											<input type="text" name="itembarcode" id="itembarcode" maxlength="195" class="form-control" value="<?php echo isset($_POST['itembarcode']) ? $_POST['itembarcode'] : "" ?>" >
										</div><!-- form-group -->
										
										<div class="form-group col-sm-6">
											<label for="altitembarcode">Alternative Item Barcode</label>
											<input type="text" name="altitembarcode" id="altitembarcode" maxlength="195" class="form-control" value="<?php echo isset($_POST['altitembarcode']) ? $_POST['altitembarcode'] : "" ?>" >
										</div><!-- form-group -->
									
								</div>
								
								<div class="col-sm-6">
									<div class="form-group col-sm-12">
										<label for="itemdescription">Description</label>
										<textarea name="itemdescription" id="itemdescription" class="form-control" rows="4" maxlength="245" ><?php echo isset($_POST['itemdescription']) ? $_POST['itemdescription'] : "" ?></textarea>
									</div><!-- form-group -->
									
									<div class="form-group col-sm-6">
										<label for="itemcat">Item Category</label>
										<select  class="form-control" name="itemcat" id="itemcat" data-placeholder="Choose One">
											<option value="">Choose One</option>
											<?php
												$itemcatdata = DB::query("SELECT id, category_name FROM item_category");
												
												foreach($itemcatdata as $itemcat)
												{
											?>
											<option <?php if(isset($_POST['itemcat']) && ($itemcat['id'] == $_POST['itemcat'])) echo "selected=\"selected\""; ?> value="<?php echo $itemcat['id']; ?>"><?php echo $itemcat['category_name']; ?></option>
											<?php
												}
											?>
										</select>
									</div><!-- form-group -->
									
									<div class="form-group col-sm-6">
										<label for="unitmeasure">Item Unit Measure</label>
										<select  class="form-control" name="unitmeasure" id="unitmeasure" data-placeholder="Choose One">
											<option value="">Choose One</option>
											<?php
												$unitmeasuredata = DB::query("SELECT id, measure_name FROM item_unit_measure");
												
												foreach($unitmeasuredata as $unitmeasure)
												{
											?>
											<option <?php if(isset($_POST['unitmeasure']) && ($unitmeasure['id'] == $_POST['unitmeasure'])) echo "selected=\"selected\""; ?> value="<?php echo $unitmeasure['id']; ?>"><?php echo $unitmeasure['measure_name']; ?></option>
											<?php
												}
											?>
										</select>
									</div><!-- form-group -->
									
									<div class="form-group col-sm-4">
										<label for="reorderlevel">Reorder Level</label>
										<input type="text" name="reorderlevel" id="reorderlevel" maxlength="95" class="form-control" value="<?php echo isset($_POST['reorderlevel']) ? $_POST['reorderlevel'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group col-sm-4">
										<label for="costprice">Default Cost Price</label>
										<input type="text" name="costprice" id="costprice" maxlength="45" class="form-control" value="<?php echo isset($_POST['costprice']) ? $_POST['costprice'] : "" ?>" >
									</div><!-- form-group -->
									
									<div class="form-group col-sm-4">
										<label for="sellprice">Default Sell Price</label>
										<input type="text" name="sellprice" id="sellprice" maxlength="45" class="form-control" value="<?php echo isset($_POST['sellprice']) ? $_POST['sellprice'] : "" ?>" >
									</div><!-- form-group -->
								</div>
							</div>
						</div><!-- /.card-body -->
						
						<div class="card-footer">
							
							<div class="btn-list">
								<div class="text-right">
									<a href="dashboard.php" class="btn btn-danger"><i class="fa fa-remove"></i> Cancel</a>
									
									<button type="submit" name="savedatabtn" id="savedatabtn" class="btn btn-success"><i class="fa fa-floppy-disk"></i> Save</button>
								</div>
							</div>
						</div><!-- /.card-footer-->
							</form>
					<?php
						}
						else
						{
					?>
						<div class="alert alert-danger alert-dismissable">
							<i class="fa fa-ban-circle"></i><br>
							Limited Access
						</div>
					<?php
						}
					?>
					</div><!-- /.card -->
				</section><!-- /.content -->
			</div><!-- /.content-wrapper -->

			 
		</div><!-- ./wrapper -->
<?php include ('includes/general_footer.php')?>
		
		<script src="plugins/bert/storepos.js" type="text/javascript"></script>
		<script src="plugins/bert/jquery.price_format.min.js" type="text/javascript"></script>
		<script src="plugins/bert/itemsetup.js" type="text/javascript"></script>
	</body>
</html>