<?php
$table = 'opening_stockitemwise';
$action = $_REQUEST['action'];
$daction = $_REQUEST['daction'];
$msgErr = '';
$status = true;
include('cocoon_config.php');

//************************Delete*********************************************** 
if ($action == 'del') {
	$condition = "id='" . $_REQUEST['ID'] . "'";
	$s->DeleteRecord($table, $condition);
	DB_query("delete from stock_valuation_tbl where against_voucher_main_id='" . $_REQUEST['ID'] . "' and type='OP'", $db);
	$s->pageLocation("index.php?route=Inventory/transation/Opening_Stock_Item_Wise_index&modid=" . $_REQUEST['modid'] . "&frmid=" . $_REQUEST['frmid']);
}
//************************Edit*********************************************** 

if (!$_REQUEST['Save'] &&  $status && $action == 'Edit') {
	$condition = "id='" . $_REQUEST['ID'] . "'";
	$allready = $s->GetRecord($table,  $condition);
	$Select = DB_query($allready, $db);
	$RData = DB_fetch_array($Select);
	//echo "<pre>"	;
	//print_r($RData);
	$_REQUEST['site'] = $RData['site'];
	$reveive_date = ConvertSQLDate($RData['reveive_date']);
	$date_of_mfg = ConvertSQLDate($RData['date_of_mfg']);
	$expiry = ConvertSQLDate($RData['expiry']);


	$batch = $RData['batch'];


	$store = $RData['store'];
	$itemcode = $RData['itemcode'];
	$itemdesc = $RData['itemdesc'];
	$stock = $RData['stock'];
	$rate = $RData['rate'];
	$amount = $RData['amount'];
}

if ($_REQUEST['Save'] &&  $status && $action == 'Edit') {
	if ($_REQUEST['batch'] == "") {
		$_REQUEST['batch'] = "N/A";
	}


	$sql_erp_stock = "select stock from opening_stockitemwise where store='" . $_REQUEST['store'] . "' and itemcode='" . $_REQUEST['itemcode'] . "' and batch='" . $_REQUEST['batch'] . "' and id='" . $_REQUEST['ID'] . "' ";
	$result_erp_stock = DB_query($sql_erp_stock, $db);
	$rs_erp_stock = DB_fetch_array($result_erp_stock);
	$cur_stock = $rs_erp_stock[0];


	$SQL_item = DB_fetch_array(DB_query("SELECT * from item_master where id='" . $_REQUEST['itemcode'] . "' ", $db));
	$data['site'] = $_REQUEST['site'];
	$data['reveive_date'] = FormatDateForSQL($_REQUEST['reveive_date']);
	$data['CompanyId'] = $_SESSION['ACGCompanyId'];
	$data['store'] = $_REQUEST['store'];
	//$data['itemcode']=$_REQUEST['itemcode'];
	$data['itemcode'] = $_REQUEST['itemcode'];
	$data['itemdesc'] = htmlspecialchars($SQL_item['item_name'], ENT_QUOTES);
	$data['stock'] = $_REQUEST['stock'];
	$data['rate'] = $_REQUEST['rate'];
	$data['expiry'] = FormatDateForSQL($_REQUEST['expiry']);
	$data['date_of_mfg'] = FormatDateForSQL($_REQUEST['mfg']);


	$data['batch'] = $_REQUEST['batch'];
	$data['amount'] = $_REQUEST['stock'] * $_REQUEST['rate'];
	$cond = "id='" . $_REQUEST['ID'] . "'";
	$update = $s->EditRecord($table, $data, $cond);

	$row = DB_query($update, $db);

	if (!$row) {
		die('Error' . DB_error());
	}
	//echo"Select stockbalance from stock_maintenance where itemcode='".$_REQUEST['itemcode']."'";

	DB_query("Delete from stock_valuation_tbl where against_voucher_main_id='" . $_REQUEST['ID'] . "' and type='OP' and mst_itemid='" . $_REQUEST['itemcode'] . "'", $db);
	$data1['site'] = $_REQUEST['site'];
	$data1['store'] = $_REQUEST['store'];
	$data1['mst_itemid'] = $_REQUEST['itemcode'];
	$data1['inwardqty_primary'] = $_REQUEST['stock'];
	$data1['inwardqty_secondary'] = $SQL_item['conv_factor'] * $_REQUEST['stock'];
	$data1['primary_unit'] = $SQL_item['mst_unitid'];
	$data1['secondary_unit'] = $SQL_item['conv_unit'];
	$data1['batch_no'] = $_REQUEST['batch'];
	$data1['date_of_mfg'] = FormatDateForSQL($_REQUEST['mfg']);
	$data1['date_of_expiry'] = FormatDateForSQL($_REQUEST['expiry']);
	$data1['inward_rate'] = $_REQUEST['rate'];
	$data1['inwared_value'] = $_REQUEST['stock'] * $_REQUEST['rate'];
	$data1['type']         = 'OP';
	$data1['status']       = 1;
	$data1['pending_qty'] = $_REQUEST['stock'];
	$data1['flag']        = 0;
	$data1['trasaction'] = FormatDateForSQL($_REQUEST['reveive_date']) . " " . date('H:i:s', time());
	$data1['against_voucher_main_id'] = $_REQUEST['ID'];
	$s->RecordInsert('stock_valuation_tbl', $data1);

	//$update1= $s->EditRecord("stock_valuation_tbl", $data1, $cond1);


	/*$query="update stock_valuation_tbl set site='".$_REQUEST['site']."',
	 			store='".$_REQUEST['store']."',
	 			mst_itemid='".$_REQUEST['itemcode']."',
	 			inwardqty_primary='".$_REQUEST['stock']."',
	 			inwardqty_secondary='".$SQL_item['conv_factor'] * $_REQUEST['stock']."',
	 			primary_unit='".$SQL_item['mst_unitid']."',
	 			secondary_unit='".$SQL_item['conv_unit']."',
	 			batch_no='".$_REQUEST['batch']."',
	 			date_of_mfg='".FormatDateForSQL($_REQUEST['mfg'])."',
	 			date_of_expiry='".FormatDateForSQL($_REQUEST['expiry'])."',
				inward_rate='".$_REQUEST['rate']."',
	 			inwared_value='".$_REQUEST['stock']*$_REQUEST['rate']."',
	 			type='OP',
	 			status='1',
	 			flag='0'	where against_voucher_main_id='".$_REQUEST['ID']."'";

	 			$insertResult = DB_query($query,$db,$ErrMsg);*/

	//Update in hmis





	$queryItem = "select * from item_master where id ='" . $_REQUEST['itemcode'] . "'";
	$resultItem = DB_query($queryItem, $db);
	$itemsItem = DB_fetch_assoc($resultItem, $db);
	//echo "<br>";

	$queryStore = "select * from storetype where id ='" . $_REQUEST['store'] . "'";
	$resultStore = DB_query($queryStore, $db);
	$itemsStore = DB_fetch_assoc($resultStore, $db);

	//echo "<br>";


	$queryMajorCode = "select * from stockmaincategory where id ='" . $itemsItem['CategoryID'] . "'";
	$resultMajorCode = DB_query($queryMajorCode, $db);
	$MajorCodeData = DB_fetch_assoc($resultMajorCode, $db);



	$srtoreItemSql = "select * from storeitems where store_code='" . $itemsStore['StoreCode'] . "' and item='" . $itemsItem['StockID'] . "' and major_code='" . $MajorCodeData['stockmaincategoryid'] . "'";
	//$srtoreItemSql="select * from storeitems where store_code='STRPHY' and item='".$itemsItem['StockID']."'";
	$srtoreItemQry = mysqli_query($link1, $srtoreItemSql, $link1);
	$srtoreItemRow = mysqli_fetch_array($srtoreItemQry);

	$ItemId = $srtoreItemRow['id'];


	$srtoreItemQtySql = "UPDATE storeitems SET stock_level=stock_level+" . $_REQUEST['stock'] . "-'" . $cur_stock . "' where id= $ItemId";

	$srtoreItemQtyQry = mysqli_query($link1, $srtoreItemQtySql, $link1);


	$srtorebatchItemSql = "select * from batchdetails where store_code='" . $itemsStore['StoreCode'] . "' and item_code='" . $itemsItem['StockID'] . "' and batch_no='" . $_REQUEST['batch'] . "'";
	$srtorebatchItemSql = mysqli_query($link1, $srtorebatchItemSql, $link1);
	$srtoreBatchItemRow = mysqli_fetch_array($srtorebatchItemSql);
	$batchId = $srtoreBatchItemRow['id'];

	$srtoreItemQtySql = "update batchdetails set qty=" . $_REQUEST['stock'] . " where id='" . $batchId . "'";
	$srtoreItemQtyQry = mysqli_query($link1, $srtoreItemQtySql, $link1);





	$s->pageLocation("index.php?route=Inventory/transation/Opening_Stock_Item_Wise_index&modid=" . $_REQUEST['modid'] . "&frmid=" . $_REQUEST['frmid']);
}

//************************INSERT*********************************************** 

?>

<script src="js/function-ajax.js"></script>
<script language="javascript">
	function calAmt() {
		var a = document.getElementById('stock').value;
		var b = document.getElementById('rate').value;
		document.getElementById('amount').value = a * b;

	}

	function chck_grdate(obj) {

		//$(obj).closest("tr").find("td").eq(7).find("input").val();
		var endDate = $("#expiry").val();
		var startDate = $("#mfg").val();
		if (startDate == "") {
			alert("Please Select Date Of Mfg First");
			$("#expiry").val("");
			return false;
		}
		var D1 = new Date(startDate);
		var D2 = new Date(endDate);
		if (parseInt(D2.getTime()) <= parseInt(D1.getTime())) {

			alert("Date of Expiry should be greater than Date of Mfg");
			$("#expiry").val("");
			return false;
		}

	}
</script>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
	<div class="tab_div">
		<style>
			#slidingDiv {
				display: none;
				height: 100px;
				background-color: #D9D6DA;
				padding: 20px;
			}
		</style>
		<form action="" method="post" onsubmit="return validate()">
			<h1>Opening Stock Item Wise</h1>
			<table width="100%" border="0" cellspacing="0" cellpadding="3">
				<?php if (isset($daction)) { ?>
					<tr class="row1">
						<td colspan="7">
							<div class="success">
								<?php
								if ($_REQUEST['daction'] != 1 && $_REQUEST['daction'] != 2)
									echo "Record " . $_REQUEST['daction'] . " Successfully";
								elseif ($_REQUEST['daction'] == 1)
									echo "Can't Delete This Record because AccountName Attatch with LedgerDayBook table ";
								elseif ($_REQUEST['daction'] == 2)
									echo "Can't Delete This Record. First Delete it's Parent Record   ";
								?>
							</div>
						</td>
					</tr>
				<?php }
				if (isset($msgErr) && $msgErr != '') { ?>
					<tr class="row1">
						<td colspan="7">
							<div class="error"><?php
												for ($kp = 0; $kp < count($msgErr); $kp++) {
													echo  $msgErr[$kp] . '<br>';
												}
												?></div>
						</td>
					</tr>
				<?php } ?>
				<tr class="row1">
					<td width="13%" align="right">Branch</td>
					<td width="20%">
						<?php
						if ($_SESSION['AssignedBranch'] != '') {
							$ss = "Select loccode,locationname from locations where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and loccode in('" . $_SESSION['AssignedBranch'] . "')";
							$site_sql = DB_query($ss, $db);
						} else {
							$ss = "Select loccode,locationname from locations where CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
							$site_sql = DB_query($ss, $db);
						}
						?>
						<select name="site" id="site" onchange="ShowDiv(this.value,'hid-Godown-div','GoDownByBranch.php')">
							<option value="000">---Select---</option>
							<?php
							while ($site_row = DB_fetch_array($site_sql)) {
							?>
								<option value="<?php echo $site_row['loccode']; ?>" <?php echo ($_REQUEST['site'] == $site_row['loccode'] ? 'selected' : '') ?>><?php echo $site_row['locationname']; ?></option>
							<?php } ?>
						</select>
					</td>
					<td width="13%" align="right">Store</td>
					<td width="20%">
						<div id='hid-Godown-div'><?php
													$sql_store = "select id, StoreCode, StoreName from storetype  where Store_Site='" . $_REQUEST['site'] . "' and id IN(SELECT hmis_storeid FROM www_users WHERE id='" . $_SESSION['UserID'] . "')or id in(SELECT store_id FROM www_users_dtls WHERE user_id='" . $_SESSION['UserID'] . "')";
													$resultStkLocs = DB_query($sql_store, $db);
													?>
							<select name="store" id="store">
								<?php
								while ($myrow = DB_fetch_array($resultStkLocs)) {
									$p = '';
									if ($myrow['id'] == $store)
										$p = "selected";
								?>
									<option value="<?php echo $myrow['id']; ?>" <?php echo $p; ?>><?php echo $myrow['StoreName']; ?></option>
								<?php
								}
								?>
							</select>
						</div>
					</td>
					<td width="13%" align="right">Received Date</td>
					<td><input name="reveive_date" type="text" class="datepicker" id="reveive_date" value="<?php echo $reveive_date ?>" size="15" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>
				</tr>
				<tr class="row1">
					<td align="right">Item Code/Name</td>
					<td>
						<?php
						$SQL_item = db_query("SELECT * from item_master where id='" . $itemcode . "'", $db);
						$n = db_num_rows($SQL_item);
						?>
						<select name="itemcode" onchange="Get_itemname(this.value)" id="itemcode">
							<?php while ($row_item = db_fetch_array($SQL_item)) {
								$p = '';
								if ($row_item['id'] == $itemcode)
									$p = "selected";
							?>
								<option value="<?php echo $row_item['id'] ?>" <?php echo $p; ?>><?php echo $row_item['item_name'] . ' (' . $row_item['StockID'] . ')' ?> </option>
							<?php } ?>
						</select>
					</td>
					<td align="right">Opening Qty.</td>
					<td><input type="text" name="stock" id="stock" onkeypress="return isNumberKey(event)" value="<?php echo $stock; ?>" onkeyup="changeAmount()" />
					<td align="right">Rate</td>
					<td><input type="text" name="rate" id="rate" value="<?php echo $rate; ?>" onkeypress="return isNumberKey(event)" onkeyup="changeAmount()" /></td>
				</tr>
				<tr class="row1">
					<td align="right">Amount</td>
					<td><input readonly="" type="text" name="amount" id="amount" value="<?php echo $amount; ?>" onfocus="calAmt();" /></td>
					<td align="right">Batch No.</td>
					<td><input type="text" name="batch" id="batch" value="<?php echo $batch; ?>" onkeyup="javascript:checkBatch(this.value,this.id)" /></td>
					<td colspan="2"></td>
				</tr>
				<tr class="row1">
					<td align="right">Date of Mfg.</td>
					<td><input type="text" name="mfg" id="mfg" class="datepicker" value="<?php echo $date_of_mfg; ?>" placeholder="dd/mm/yyyy" onchange="chkdteformat(this)" /></td>
					<td align="right">Date of Exp.</td>
					<td><input type="text" name="expiry" id="expiry" class="datepicker" value="<?php echo $expiry; ?>" placeholder="dd/mm/yyyy" onchange="chkdteformat(this);chck_grdate(this);" autocomplete="off" /></td>
					<td colspan="2"></td>
				</tr>
				<tr class="row1">
					<td colspan="6" align="center"><input type="submit" name="Save" value="Save" class="search" /> <input type="reset" name="Reset" value="Reset" class="search" /></td>
				</tr>
			</table>

		</form>
	</div>
</div>


<script>
	function checkBatch(batch, id) {
		if (batch == "") {
			var batch = "N/A";
		}
		if ($('#site').val() == "") {
			alert("Please Select Branch First");
			document.getElementById("site").focus();
			document.getElementById("batch").value = "";
			return false;
		}
		var site = $('#site').val();
		if ($('#store').val() == "") {
			alert("Please Select Store First");
			document.getElementById("store").focus();
			document.getElementById("batch").value = "";
			return false;
		}

		var store = $('#store').val();
		var item_id = document.getElementById("itemcode").value;
		if (item_id != '') {
			$.post("GoDownByBranch.php", {
				"checkbatch": 'yes',
				'site': site,
				'store': store,
				'item': item_id,
				"batch": batch
			}, function(data) {
				if (data == 0) {
					alert('Stock already exist for this item');
					$('#batch').val('');
					$('#batch').focus();
				}

			});

		}
	}

	function chkdteformat(obj) {
		var pattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
		var currID = obj.id;
		var input = document.getElementById(currID).value;
		if (!pattern.test(input)) {
			alert("Date should be in dd/mm/yyyy Format");
			document.getElementById(currID).value = "";
		}
	}

	function isNumberKey(evt) {
		var charCode = (evt.which) ? evt.which : event.keyCode;
		if (charCode != 46 && charCode > 31 &&
			(charCode < 48 || charCode > 57))
			return false;

		return true;
	}

	function changeAmount() {
		var qty = parseFloat(document.getElementById('stock').value);
		var rate = parseFloat(document.getElementById('rate').value);

		if (isNaN(qty))
			qty = 0;
		if (isNaN(rate))
			rate = 0;

		var total = parseFloat(qty * rate);
		if (!isNaN(total))
			document.getElementById('amount').value = total.toFixed(2);
	}

	function validate() {
		//alert(document.getElementById("batch").value);
		if (document.getElementById("site").value == '000') {
			alert("Must Select Branch Name");
			document.getElementById("site").focus();
			return false;
		}
		if (document.getElementById("store").value == '0') {
			alert("Must Select Store");
			document.getElementById("store").focus();
			return false;
		}
		if (document.getElementById("itemcode").value == '') {
			alert("Must Select Item Name");
			document.getElementById("itemcode").focus();
			return false;
		}

		if (document.getElementById("batch").value == '') {
			alert("Must Enter Batch");
			document.getElementById("batch").focus();
			return false;
		}
		if (document.getElementById("reveive_date").value == '') {

			alert("Must Enter Received Date");
			document.getElementById("reveive_date").focus();
			return false;
		}
		if (document.getElementById("stock").value == '') {
			alert("Must Enter Opening Qty");
			document.getElementById("stock").focus();
			return false;
		}
		if (document.getElementById("rate").value == '') {
			document.getElementById("rate").focus();
			alert("Must Enter Item Rate");
			return false;
		}
		return true;
	}

	function open_items() {
		//alert(document.getElementById('site').value);	
		if (document.getElementById('site').value != '000') {
			var site1 = document.getElementById("site").value;
			var store = document.getElementById("store").value;
			window.open("opening_items.php?action=add&site=" + site1 + "&store=" + store + "&modid=<?php echo $_REQUEST['modid']; ?>&frmid=<?php echo $_REQUEST['frmid']; ?>", "item_popup_window", "height=700,width=1000,toolbar=no,menubar=no,dependent=yes,resizable =yes, scrollbars=yes");
		} else {
			alert("Must Select Branch");
		}

	}
</script>