<?php
session_name('CAKEPHP'); session_start();
error_reporting(0);

if (!function_exists('stock_summary_shutdown_debug')) {
	function stock_summary_shutdown_debug()
	{
		$error = error_get_last();
		if (!$error) {
			return;
		}
		$fatalTypes = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);
		if (!in_array($error['type'], $fatalTypes)) {
			return;
		}
		$message = 'Stock Summary Fatal Error: ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'];
		echo '<div style="margin:8px 0; padding:10px; border:1px solid #b00020; background:#fff3f3; color:#b00020;">' . htmlspecialchars($message, ENT_QUOTES) . '</div>';
		echo '<script type="text/javascript">console.error(' . json_encode($message) . ');</script>';
	}
}
register_shutdown_function('stock_summary_shutdown_debug');

$first_date = date('01/m/Y');
$cur_date = date('d/m/Y');

//For hmis User
$sql_user_store = "select hmis_storeid,StoreCode from www_users left join storetype on storetype.id=www_users.hmis_storeid where www_users.id='" . $_SESSION['UserID'] . "'";
$result_user_store = DB_query($sql_user_store, $db);
$rs_user_store = DB_fetch_array($result_user_store);
$main_store = $rs_user_store[0];


$sql_other_store = "select store_id,StoreCode from www_users_dtls left join storetype on storetype.id=www_users_dtls.store_id where user_id='" . $_SESSION['UserID'] . "'";
$result_other_store = DB_query($sql_other_store, $db);
while ($rs_other_store = DB_fetch_array($result_other_store)) {
	$store[] = $rs_other_store['store_id'];
}
if (!empty($store)) {
	$get_store_id = implode(",", $store);
}

//echo $_REQUEST['from_date'];
?>
<script type="text/javascript">
	function checkval() {
		var siteField = document.getElementById("site");
		var storeField = document.getElementById("store1");
		var fromField = document.getElementById("fromdate");
		var toField = document.getElementById("todate");
		var maincatField = document.getElementById("maincat");
		var idsite = siteField ? siteField.value : '';
		var idstore = storeField ? storeField.value : '';
		var fromdate = fromField ? fromField.value : '';
		var todate = toField ? toField.value : '';
		var maincat = maincatField ? maincatField.value : '0';
		console.log("Stock Summary checkval", {
			site: idsite,
			store: idstore,
			fromdate: fromdate,
			todate: todate,
			maincat: maincat
		});
		if (idsite == '0' || idsite == '') {
			alert("Select Site Name First.");
			return false;
		} else if (fromdate == '') {
			alert("Select From date.");
			return false;
		} else if (todate == '') {
			alert("Select To date.");
			return false;
		} else if (maincat == '0' && idstore == '0') {
			alert("Select Main category First.");
			return false;
		}
		return true;
	}
</script>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
	<div class="tab_div">
		<h1>Stock Summary</h1>
		<form method="post" action="">

			<table width="100%" border="0" cellspacing="0" cellpadding="3">
				<tr class="row1">
					<td width="13%" align="right">Branch <span style="color:#FF0000">*</span></td>
					<td width="20%"><?php
									$ss1 = "Select loccode, locationname from locations  where CompanyId='" . $_SESSION['ACGCompanyId'] . "' and loccode in('" . $_SESSION['AssignedBranch'] . "')";
									$site_sql1 = DB_query($ss1, $db);

									?>
						<select name="site" id="site" onchange="showsitename160(this.value)">
							<option value="">All</option>
							<?php

							while ($site_row = DB_fetch_array($site_sql1)) {
								$p = '';
								if ($site_row['loccode'] == $_POST['site'])
									$p = "selected";
							?>
								<option value="<?php echo $site_row['loccode']; ?>" <?php echo $p; ?>><?php echo $site_row['locationname']; ?></option>
							<?php } ?>
						</select>
					</td>
					<td width="13%" align="right">Store <span style="color:#FF0000">*</span></td>
					<td width="20%">
						<div id="storedata7">
							<select name="store1" id="store1">
								<option value='0'>All</option>
								<?php
								if ($_SESSION['UserType'] != 'SuperAdmin') {
									if ($get_store_id != '') {
										$store_sql = "SELECT id, StoreName,storecode FROM storetype where id in(" . $main_store . "," . $get_store_id . ")";
									} else if ($main_store != '') {
										$store_sql = "SELECT id, StoreName,storecode FROM storetype where id in(" . $main_store . ")";
									}
								} else {
									$store_sql = "SELECT id, StoreName,storecode FROM storetype";
								}
								$store_result = DB_query($store_sql, $db);
								while ($store_row = DB_fetch_array($store_result)) {
									$p = '';
									if ($store_row['id'] == $_REQUEST['store1'])
										$p = "selected";
								?>
									<option value="<?php echo $store_row['id'] ?>" <?php echo $p; ?>><?php echo $store_row['StoreName'] ?></option>
								<?php } ?>
							</select>
						</div>
					</td>
					<td width="13%" align="right">Enter Part Name of Item</td>
					<td><input type="text" name="itemName" value="" onkeyup="showItems(this.value)" /></td>
				</tr>
				<tr class="row1">
					<td align="right">Main Category</td>
					<td><select name="maincat" id="maincat" onchange="showsubcat(this.value)">
							<option value="0">Select</option>
							<?php
							$store_sql = "SELECT * FROM stockmaincategory where CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
							$store_result = DB_query($store_sql, $db);
							while ($store_row = DB_fetch_array($store_result)) {
								$p = '';
								if ($store_row['id'] == $_REQUEST['maincat'])
									$p = "selected";
							?>
								<option value="<?php echo $store_row['id'] ?>" <?php echo $p; ?>><?php echo $store_row['stockmaincategoryname'] ?></option>
							<?php } ?>
						</select></td>
					<td align="right">Sub Category</td>
					<td>
						<div id="subcatdata">
							<?php
							$store_sql = "SELECT * FROM stockcategory  where stockmaincategory = '" . $_POST['maincat'] . "'";
							?>
							<select name="subcat" id="subcat" onchange="showdata(this.value)">
								<option value="0">Select</option>
								<?php
								$store_result = DB_query($store_sql, $db);
								while ($store_row = DB_fetch_array($store_result)) {;
									$p = '';
									if ($store_row['id'] == $_REQUEST['subcat'])
										$p = "selected";
								?>
									<option value="<?php echo $store_row['id']; ?>" <?php echo $p; ?>><?php echo $store_row['categorydescription']; ?></option>
								<?php } ?>
							</select>
						</div>
					</td>
					<td valign="top" rowspan="2" align="right">Select Item</td>
					<td rowspan="2">
						<div id="itemid">
							<div style="overflow:auto; height:100px; width:auto; border:1px solid #808080; background:#fff; padding:2px 3px;">
								<?php
								if ($_REQUEST['site'] != '' && $_REQUEST['site'] != '0' && $_REQUEST['store1'] != '' && $_REQUEST['store1'] != '0') {
									$item_sql = DB_query("select item_master.id,item_master.StockID,item_master.item_name
										from item_master
										where item_master.CompanyId='" . $_SESSION['ACGCompanyId'] . "'
										and exists (
											select 1
											from opening_stockitemwise
											where opening_stockitemwise.itemcode = item_master.id
											and opening_stockitemwise.site = '" . $_REQUEST['site'] . "'
											and opening_stockitemwise.store = '" . intval($_REQUEST['store1']) . "'
											and opening_stockitemwise.stock > 0
										)
										order by item_master.StockID ASC", $db);
									$c3 = 0;
									while ($row3 = DB_fetch_array($item_sql)) {
										$c = '';
										if (isset($_REQUEST['item'][$c3]) && $_REQUEST['item'][$c3] == $row3['id']) {
											$c = "checked";
										}
								?>
									<input type="checkbox" name="item[<?php echo $c3; ?>]" id="item_<?php echo $c3; ?>" value="<?php echo $row3['id']; ?>" <?php echo $c; ?> />
									<?php echo $row3['StockID'] . " - " . $row3['item_name']; ?><br />
								<?php
										$c3++;
									}
								} else {
									echo "<em>Select site and store to load items with opening stock greater than zero.</em>";
								}
								?>
							</div>
						</div>
					</td>

				</tr>
				<tr class="row1">
					<td align="right">From Date</td>
					<td><input type="text" name="from_date" id="fromdate" value="<?php if ($_REQUEST['from_date'] != '') {
																						echo $_REQUEST['from_date'];
																					} else {
																						echo $first_date;
																					}  ?>" onchange="javascript:checkdate(this.value)" class="datepicker"></td>
					<td align="right">To Date</td>
					<td><input type="text" name="to_date" id="todate" value="<?php if ($_REQUEST['to_date'] != '') {
																					echo $_REQUEST['to_date'];
																				} else {
																					echo $cur_date;
																				} ?>" onchange="javascript:checkdate(this.value)" class="datepicker">
						<input type="hidden" value="<?php echo ConvertSQLDate($_SESSION['financialYrStart']); ?>" id='from'>
						<input type="hidden" value="<?php echo ConvertSQLDate($_SESSION['financialYrEnd']); ?>" id='to'>
					</td>

				</tr>
				<tr class="row1">
					<td align="right">Category</td>
					<td><select name="category_flag" id="category_flag">
							<option value="">Select</option>
							<option value="narcotic" <?= isset($_REQUEST['category_flag']) && $_REQUEST['category_flag'] == 'narcotic' ? "selected" : ""  ?>>Narcotics</option>
							<option value="emergency" <?= isset($_REQUEST['category_flag']) && $_REQUEST['category_flag'] == 'emergency' ? "selected" : ""  ?>>Emergency</option>
							<option value="high_risk" <?= isset($_REQUEST['category_flag']) && $_REQUEST['category_flag'] == 'high_risk' ? "selected" : ""  ?>>High Risk</option>
						</select>
					</td>
					<td colspan="6" style="text-align:center">
						<input type="submit" name="view" value="View" class="search" onclick="return checkval()">
					</td>
				</tr>
			</table>

		</form>
		<?php
		$shouldRenderReport = isset($_REQUEST['view']) || $_SERVER['REQUEST_METHOD'] === 'POST';
		if ($shouldRenderReport) {
			$reportDebugMessages = array();
			$reportDebugMessages[] = 'Stock summary view request received';

			$_SESSION['stock_print'] = $_REQUEST;
			// echo "<pre>";
			// print_r($_REQUEST); die;


			// print_r($_SESSION['stock_print']);
			$category_flag_filter  = '';
			$item_code_filter = "";
			if (isset($_POST['category_flag']) && !empty($_POST['category_flag'])) {
				$category_flag = $_POST['category_flag'];
				if ($category_flag == 'emergency' || $category_flag == 'high_risk') {
					$category_flag_filter = " and $category_flag = 1 ";
				} else {
					$category_flag_filter = ' and narcotic = "Y"';
				}
			}

			if ($_REQUEST['from_date'] == '') {
				$_REQUEST['from_date'] = $_SESSION['financialYrStart'];
				$from_date = $_REQUEST['from_date'];
				$from = $from_date;
			} else {
				$from_date = $_REQUEST['from_date'];
				$from_date_brk = explode('/', $from_date);
				$from = $from_date_brk[2] . "-" . $from_date_brk[1] . "-" . $from_date_brk[0];
			}
			if ($_REQUEST['to_date'] == '') {
				$_REQUEST['to_date'] = $_SESSION['financialYrEnd'];
				$to_date = $_REQUEST['to_date'];
				$to = $to_date;
			} else {
				$to_date = $_REQUEST['to_date'];
				$to_date_brk = explode('/', $to_date);
				$to = $to_date_brk[2] . "-" . $to_date_brk[1] . "-" . $to_date_brk[0];
			}



			if ($_REQUEST['site'] != '0') {
				$site = $_REQUEST['site'];
			}
			$reportDebugMessages[] = 'Selected site: ' . $site;

			if ($_REQUEST['store1'] == 0) {
				$store12 = array();
				$store_sql = "SELECT id FROM storetype where Store_Site = '" . $_REQUEST['site'] . "'";
				$store_sql1 = DB_query($store_sql, $db);
				while ($st_rows = DB_fetch_array($store_sql1)) {
					$store12[] = $st_rows['id'];
				}
				$store = implode("','", $store12);
				$reportDebugMessages[] = 'Using all stores for site. Store count: ' . count($store12);
			} else
				$store = $_REQUEST['store1'];
			$reportDebugMessages[] = 'Store filter: ' . $store;
			if ($_REQUEST['maincat'] != '0')
				$filter2[] = "CategoryID='" . $_REQUEST['maincat'] . "'";
			if ($_REQUEST['subcat'] != '0')
				$filter2[] = "SubCategoryID='" . $_REQUEST['subcat'] . "'";

			$item = $_REQUEST['item'];
			//print_r($item);				
			if (is_array($item) && !empty($item)) {
				$item_string = implode("','", $item);
				$filter2[] = " item_master.id in('" . $item_string . "')";
			} elseif ($item != '' && $item != '0') {
				$filter2[] = " item_master.id in('" . $item . "')";
			}
			if ($filter2 != '') {

				$filter4 = implode(' and ', $filter2);
			}
			$function_filter[0] = $site;
			$function_filter[1] = $store;
			$function_filter[2] = $from;
			$function_filter[3] = $to;

			$fdate = $from;

			if ($_SESSION['UserType'] == 'Dealer') {
				include('includes/associate_stock_summary_function.php');
			} else {
				include('includes/stock_summary_function.php');
			}


		?>

			<?php
			if ($branch != '') {
				$branch = $s->getField('locations', 'loccode', $_REQUEST['site'], 'locationname');
			} else {
				$branch = "All";
			}

			if ($_REQUEST['store1'] != '0')
				$storedata = "store  " . $s->getField('storetype', 'id', $_REQUEST['store1'], 'StoreName');
			else
				$storedata = "ALL Store";
			if ($_REQUEST['maincat'] != '0' && $_REQUEST['store1'] !== '0') {
				$sub = $s->getField('stockcategory', 'id', $_REQUEST['subcat'], 'categorydescription');
				$cat = $s->getField('stockmaincategory', 'id', $_REQUEST['maincat'], 'stockmaincategoryname');
			}
			if ($_REQUEST['maincat'] != '0') {
				$message = "Showing Records of <u><span class='fntBig'>" . $storedata . "</span></u> of Branch -- <u><span class='fntBig'>" . $branch . "</span></u> Category -- <u><span class='fntBig'>" . $cat . "</span></u> -- and SubCategory -- <u><span class='fntBig'>" . $sub . "</span></u> and From <u><span class='fntBig'>" . $_REQUEST['from_date'] . "</span></u> to <u><span class='fntBig'>" . $_REQUEST['to_date'] . "</span></u>";
			} elseif ($from_date != "" && $to_date != "") {
				$message = "Showing Records of <u><span class='fntBig'>" . $storedata . "</span></u> of Branch -- <u><span class='fntBig'>" . $branch . "</span></u> From <u><span class='fntBig'>" . $_REQUEST['from_date'] . "</span></u> to <u><span class='fntBig'>" . $_REQUEST['to_date'] . "</span></u>";
			} elseif ($from_date == "" && $to_date == "") {
				$message = "Showing Records of <u><span class='fntBig'>" . $storedata . "</span></u> of Branch -- <u><span class='fntBig'>" . $branch . "</span></u> From <u><span class='fntBig'>" . ConvertSQLDate($_SESSION['financialYrStart']) . "</span></u> to <u><span class='fntBig'>" . ConvertSQLDate($_SESSION['financialYrEnd']) . "</span></u>";
			}

			$_SESSION['mess1'] = $message;
			?>

			<?php //for($k=0; $k<5; $k++){

			if (is_array($item) && !empty($item)) {
				$item_string = implode("','", $item);
				$filter2[] = " item_master.id in('" . $item_string . "')";
			} elseif ($item != '' && $item != '0') {
				$filter2[] = " item_master.id in('" . $item . "')";
			}


			$item2 = $_REQUEST['item'];
			if (is_array($item2) && !empty($item2)) {
				$item_string1 = implode(",", $item2);
			} elseif ($item2 != '' && $item2 != '0') {
				$item_string1 = $item2;
			}

			?>

			<?php if ($shouldRenderReport) { ?>
				<p align="center"><strong><?php echo $message; ?></strong> <a href="stock_summary_print.php" target="_blank" style="float:right;"><input type="button" name="print" class="search" value="Print"></a></p>
				<div id="stock-summary-debug" style="margin:8px 0; padding:8px 10px; background:#f7f7f7; border:1px solid #d9d9d9; color:#333;">
					Report request received. Loading stock summary...
				</div>
			<?php } ?>

			<table width="100%" border="0" cellspacing="0" cellpadding="3" class="thborder">
				<tr>
					<th width="4%">S.No.</th>

					<th width="8%" rowspan="2">Item Code</th>
					<th rowspan="2">Item Name</th>
					<!-- <th rowspan="2" style="text-align:center;">Primary UOM</th>
                   <th rowspan="2" style="text-align:center;">Secondary UOM</th> -->
					<th colspan="2" style="text-align:center;">Opening Balance Qty.</th>
					<th colspan="2" style="text-align:center;">Received Qty.</th>
					<th colspan="2" style="text-align:center;">Issued Qty.<br />(Branch & Patient Issue)</th>
					<th colspan="4" style="text-align:center;">Variance<br />(Stock Adjustment)</th>
					<th colspan="2" style="text-align:center;">Closing Balance Qty.</th>
				</tr>
				<tr>
					<th width="8%" style="text-align:center;">Primary</th>
					<th width="8%" style="text-align:center;">Secondary</th>
					<th width="8%" style="text-align:center;">Primary</th>
					<th width="8%" style="text-align:center;">Secondary</th>
					<th width="8%" style="text-align:center;">Primary</th>
					<th width="8%" style="text-align:center;">Secondary</th>
					<th colspan="2" style="text-align:center;">Plus</th>
					<th colspan="2" style="text-align:center;">Minus</th>
					<th width="8%" style="text-align:center;">Primary</th>
					<th width="8%" style="text-align:center;">Secondary</th>
				</tr>
				<?php
				$subQuery = '';
				if ($item_string1 != '')
					$subQuery .= " and item_master.id IN(" . $item_string1 . ")";

				if ($_REQUEST['maincat'] != 0)
					$subQuery .= " and item_master.CategoryID='" . $_REQUEST['maincat'] . "'";
				if ($_REQUEST['subcat'] != 0)
					$subQuery .= " and item_master.SubCategoryID='" . $_REQUEST['subcat'] . "'";

				$stockFilter = " and opening_stockitemwise.stock > 0";
				if ($_REQUEST['site'] != '' && $_REQUEST['site'] != '0') {
					$stockFilter .= " and opening_stockitemwise.site = '" . $_REQUEST['site'] . "'";
				}
				if ($_REQUEST['store1'] != '' && $_REQUEST['store1'] != '0') {
					$stockFilter .= " and opening_stockitemwise.store = '" . intval($_REQUEST['store1']) . "'";
				} elseif (!empty($store12)) {
					$stockFilter .= " and opening_stockitemwise.store in('" . implode("','", $store12) . "')";
				}

				$baseSql = "select item_master.*
				from item_master
				where 1=1
				" . $subQuery . " $category_flag_filter
				and exists (
					select 1
					from opening_stockitemwise
					where opening_stockitemwise.itemcode = item_master.id
					" . $stockFilter . "
				)";

				$page = isset($_REQUEST['page']) ? max(1, intval($_REQUEST['page'])) : 1;
				$perPage = 20;
				$offset = ($page - 1) * $perPage;
				$countSql = "select count(*) as total_rows from (" . $baseSql . ") as stock_summary_count";
				$countResult = DB_query($countSql, $db, '', '', false, false);
				$countRow = $countResult ? DB_fetch_array($countResult) : array('total_rows' => 0);
				$totalRows = intval($countRow['total_rows']);
				$countQueryError = $countResult ? '' : DB_error_msg($db);
				$reportDebugMessages[] = 'Matched item count: ' . $totalRows;
				if ($countQueryError != '') {
					$reportDebugMessages[] = 'Count query error: ' . $countQueryError;
				}
				$totalPages = max(1, ceil($totalRows / $perPage));
				if ($page > $totalPages) {
					$page = $totalPages;
					$offset = ($page - 1) * $perPage;
				}
				$sql1 = $baseSql . " order by CategoryID,SubCategoryID,item_name ASC limit " . intval($perPage) . " offset " . intval($offset);

				$_SESSION['sqlquery_' . $rd] = $baseSql . " order by CategoryID,SubCategoryID,item_name ASC";
				$_SESSION['from_date'] = $_REQUEST['from_date'];
				$_SESSION['to_date'] = $_REQUEST['to_date'];
				$_SESSION['store'] = $_REQUEST['store1'];
				$result1 = DB_query($sql1, $db, '', '', false, false);
				$mainQueryError = $result1 ? '' : DB_error_msg($db);
				if ($mainQueryError != '') {
					$reportDebugMessages[] = 'Main query error: ' . $mainQueryError;
				}

				$i = $offset + 1;
				$renderedRows = 0;
				$debugText = htmlspecialchars(implode(' | ', $reportDebugMessages), ENT_QUOTES);
				?>
				<script type="text/javascript">
					console.log("Stock Summary Debug: <?php echo $debugText; ?>");
					<?php if ($countQueryError != '') { ?>
					console.error("Stock Summary Count Query Error: <?php echo htmlspecialchars($countQueryError, ENT_QUOTES); ?>");
					<?php } ?>
					<?php if ($mainQueryError != '') { ?>
					console.error("Stock Summary Main Query Error: <?php echo htmlspecialchars($mainQueryError, ENT_QUOTES); ?>");
					<?php } ?>
				</script>
				<script type="text/javascript">
					(function() {
						var debugBox = document.getElementById('stock-summary-debug');
						if (debugBox) {
							debugBox.innerHTML = <?php echo json_encode(implode(' | ', $reportDebugMessages)); ?>;
						}
					})();
				</script>
				<tr>
					<td colspan="16" style="padding:10px; background:#f7f7f7; color:#333;">
						Showing <?php echo $totalRows; ?> matched item(s).
					</td>
				</tr>
				<?php
				if ($countQueryError != '') {
					?>
					<tr>
						<td colspan="16" style="text-align:center; padding:18px; color:#b00020;">
							Count query error: <?php echo htmlspecialchars($countQueryError); ?>
						</td>
					</tr>
					<?php
				}
				if (!$result1) {
					?>
					<tr>
						<td colspan="16" style="text-align:center; padding:18px; color:#b00020;">Unable to load report data. <?php echo htmlspecialchars($mainQueryError); ?></td>
					</tr>
					<?php
				}
				while ($result1 && ($row1 = DB_fetch_array($result1))) {

					$confac = $row1['conv_factor'];
					$movementSummary = stockValuationTableSummary($function_filter, $row1['id']);
					$con_factor = ((float)$confac == 0) ? 1 : $confac;
					if ($_SESSION['UserType'] == 'dealer') {
						$opening_stock = (float)$movementSummary['opening_qty'];
						$received_qty = (float)$movementSummary['received_qty'];
						$issueded_qty = (float)$movementSummary['issued_qty'];
						$tot = (float)$movementSummary['closing_qty'];
						$stockallitems = $tot;
						$in_7 = (float)$movementSummary['plus_qty'];
						$out_7 = (float)$movementSummary['minus_qty'];
						$opening_stock_sec = ($opening_stock * $con_factor);
						$received_qty_sec = ($received_qty * $con_factor);
						$issueded_qty_sec = ($issueded_qty * $con_factor);
						$_SESSION['opening_' . $rd] = $opening_stock;
					} else {
						$opening_stock = (float)$movementSummary['opening_qty'];
						$received_qty = (float)$movementSummary['received_qty'];
						$issueded_qty = (float)$movementSummary['issued_qty'];
						$tot = (float)$movementSummary['closing_qty'];
						$stockallitems = $tot;
						$in_7 = (float)$movementSummary['plus_qty'];
						$out_7 = (float)$movementSummary['minus_qty'];
						$opening_stock_sec = ($opening_stock * $con_factor);
						$received_qty_sec = ($received_qty * $con_factor);
						$issueded_qty_sec = ($issueded_qty * $con_factor);
						$_SESSION['opening_' . $rd] = $opening_stock;
					}
					// echo "<pre>";
					$renderedRows++;
					if ($row1['SubCategoryID'] != $subC_id) {
						$subC_id = $row1['SubCategoryID'];
				?>
						<tr bgcolor="#e4e4e4" style="color:#00695f;">
							<td colspan="16" valign="middle"><b><?php echo $s->GetFieldValue('stockmaincategory', 'id="' . $row1['CategoryID'] . '"', 'stockmaincategoryname'); ?></b>&nbsp;<img src="images/orange-right-arrow-button.png" height="20" width="20" style="vertical-align:middle;" />&nbsp;<b><?php echo $s->GetFieldValue('stockcategory', 'id="' . $row1['SubCategoryID'] . '"', 'categorydescription') ?></b></td>
						</tr>
					<?php }  ?>
					<tr>
						<td><?= $i++; ?></td>

						<td><?php echo $row1['StockID']; ?></td>
						<td><?php echo $row1['item_name']; ?></td>
						<!--<td><?php echo $s->getField('unitsofmeasure', 'unitid', $row1['mst_unitid'], 'unitname'); ?></td>
               <td><?php echo $s->getField('unitsofmeasure', 'unitid', $row1['conv_unit'], 'unitname'); ?></td> -->


						<td style="text-align:right;"><?php if ($opening_stock == '') {
															echo "0";
														} else {
															echo number_format($opening_stock, 2);
														} ?> <?php if ($opening_stock != '') echo $s->getField('unitsofmeasure', 'unitid', $row1['mst_unitid'], 'unitname'); ?></td>
						<td style="text-align:right;"><?php if ($opening_stock_sec == '') {
															echo "0";
														} else {
															echo number_format($opening_stock_sec, 2);
														} ?> <?php if ($opening_stock_sec != '') echo $s->getField('unitsofmeasure', 'unitid', $row1['conv_unit'], 'unitname'); ?></td>
						<td style="text-align:right;"><?php if ($received_qty == '') {
															echo "0";
														} else {
															echo number_format($received_qty, 2);
														} ?> <?php echo $s->getField('unitsofmeasure', 'unitid', $row1['mst_unitid'], 'unitname'); ?></td>
						<td style="text-align:right;"><?php if ($received_qty_sec == '') {
															echo "0";
														} else {
															echo number_format($received_qty_sec, 2);
														} ?> <?php echo $s->getField('unitsofmeasure', 'unitid', $row1['conv_unit'], 'unitname'); ?></td>
						<td style="text-align:right;"><?php if ($issueded_qty == '') {
															echo "0";
														} else {
															echo number_format($issueded_qty, 2);
														} ?> <?php echo $s->getField('unitsofmeasure', 'unitid', $row1['mst_unitid'], 'unitname'); ?></td>
						<td style="text-align:right;"><?php if ($issueded_qty_sec == '') {
															echo "0";
														} else {
															echo number_format($issueded_qty_sec, 2);
														} ?> <?php echo $s->getField('unitsofmeasure', 'unitid', $row1['conv_unit'], 'unitname'); ?></td>
						<td width="4%" style="text-align:right;"><?php echo number_format((float)$in_7, 2); ?></td>
						<td width="4%" style="text-align:right;"><?php echo number_format(($in_7 * $con_factor), 2) ?></td>
						<td width="4%" style="text-align:right;"><?php echo number_format((float)$out_7, 2); ?></td>
						<td width="4%" style="text-align:right;"><?php echo number_format(($out_7 * $con_factor), 2) ?></td>
						<td style="text-align:right;"><?php echo number_format($tot, 2); ?> <?php echo $s->getField('unitsofmeasure', 'unitid', $row1['mst_unitid'], 'unitname'); ?></td>
						<td style="text-align:right;"><?php echo number_format(($tot * $con_factor), 2); ?> <?php echo $s->getField('unitsofmeasure', 'unitid', $row1['conv_unit'], 'unitname'); ?></td>
						</tr>

					<?php
				}

				if ($renderedRows === 0) {
					?>
					<tr>
						<td colspan="16" style="text-align:center; padding:18px;">No records found.</td>
					</tr>
					<?php
				}

					?>
			</table>
			<?php if ($totalPages > 1) { ?>
				<?php
				$paginationParams = $_REQUEST;
				unset($paginationParams['page']);
				?>
				<div style="margin-top:12px; text-align:center;">
					<?php if ($page > 1) { ?>
						<a href="?<?php echo http_build_query(array_merge($paginationParams, array('page' => $page - 1))); ?>" class="search" style="display:inline-block; padding:6px 10px; text-decoration:none;">Previous</a>
					<?php } ?>
					<span style="display:inline-block; margin:0 10px;">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
					<?php if ($page < $totalPages) { ?>
						<a href="?<?php echo http_build_query(array_merge($paginationParams, array('page' => $page + 1))); ?>" class="search" style="display:inline-block; padding:6px 10px; text-decoration:none;">Next</a>
					<?php } ?>
				</div>
			<?php } ?>

		<?php }
		?>


	</div>
</div>


<script type="text/javascript">
	function checkdate(date) {
		var from = document.getElementById('from').value;
		var to = document.getElementById('to').value;

		var cdate = date.split("/");
		var sdate = from.split("/");
		var edate = to.split("/");

		cdate[1] = cdate[1] - 1;
		sdate[1] = sdate[1] - 1;
		edate[1] = edate[1] - 1;

		var dateC = new Date(cdate[2], cdate[1], cdate[0]); //Year, Month, Date 
		var dateS = new Date(sdate[2], sdate[1], sdate[0]); //Year, Month, Date
		var dateE = new Date(edate[2], edate[1], edate[0]); //Year, Month, Date

		if (dateS > dateE) {
			alert("Start Date is not greather then Date End.");
			document.getElementById('fromdate').value = from;
			document.getElementById('todate').value = to;

		}

		if (dateC > dateE) {
			alert("Date Not greather than " + to);
			document.getElementById('fromdate').value = from;
			document.getElementById('todate').value = to;

		}

		if (dateC < dateS) {
			alert(" Date Not less than " + from);
			document.getElementById('fromdate').value = from;
			document.getElementById('todate').value = to;

		}


	}
</script>
<script type="text/javascript">
	function refreshItemList(partName) {
		var site = $("#site").val();
		var store = $("#store1").val();
		if (site == "" || site == "0" || store == "" || store == "0") {
			$("#itemid").html("<div style='padding:6px;border:1px solid;'>Select site and store first.</div>");
			return;
		}
		$.post("Get_itemcode.php", {
			"partName": partName || "",
			"site": site,
			"store": store
		}, function(data) {
			document.getElementById("itemid").innerHTML = data;
		});
	}

	function showItems(str) {
		refreshItemList(str);
	}

	function showsitename160(str) {

		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var data = xmlhttp.responseText.split("__");
				document.getElementById("storedata7").innerHTML = data[0];
				var storeValue = $("#store1").val();
				if (storeValue != "" && storeValue != "0") {
					refreshItemList("");
				} else {
					$("#itemid").html("<div style='padding:6px;border:1px solid;'>Select site and store first.</div>");
				}
			}
		}
		xmlhttp.open("GET", "get_sitenamedata3.php?site=" + str, true);
		xmlhttp.send();

		//xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);


	}


	function showsubcat(str) {
		var xmlhttp;
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var data = xmlhttp.responseText.split("__");
				document.getElementById("subcatdata").innerHTML = data[0];
				document.getElementById("itemid").innerHTML = data[1];
			}
		}
		xmlhttp.open("GET", "get_sitenamedatasubcat.php?site=" + str, true);
		xmlhttp.send();




	}

	function showdata(str) {
		if (str == "") {
			document.getElementById("itemid").innerHTML = "";
			return;
		}
		if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else { // code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				document.getElementById("itemid").innerHTML = xmlhttp.responseText;
			}
		}
		var cat = document.getElementById("maincat").value;
		xmlhttp.open("GET", "Get_itemcode1.php?partName=" + str + "&main=" + cat, true);
		xmlhttp.send();

	}
</script>
