<?php
include('includes/config/config.php');
include('includes/auth/auth.php');
include('includes/functions.php');
include('access.php');
error_reporting(E_ERROR | E_PARSE);
?>
<?php

$isOhcSpecific = getConfigKey("IS_OHC_SPECIFIC");
error_log("IS NOTICE OHC SPECFIC-> " . $isOhcSpecific);
$AndOhcFilter = "";
$WhereOhcFilter = "";
$CommaOhcFilter = "";
if ($isOhcSpecific == "TRUE") {
	$AndOhcFilter = "and ohc_type_id ='" . $_SESSION['current_ohcttype'] . "' ";

	$WhereOhcFilter = "where ohc_type_id = '" . $_SESSION['current_ohcttype'] . "' ";

	$CommaOhcFilter = "ohc_type_id = '" . $_SESSION['current_ohcttype'] . "' ";
}

// Connect to mysqli database
$page = 1; // The current page
$sortname = 'item_id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
// Get posted data
if (isset($_REQUEST['page'])) {
	$page = mysqli_real_escape_string($conn, $_REQUEST['page']);
}
if (isset($_REQUEST['sortname'])) {
	$sortname = mysqli_real_escape_string($conn, $_REQUEST['sortname']);
}
if (isset($_REQUEST['sortorder'])) {
	$sortorder = mysqli_real_escape_string($conn, $_REQUEST['sortorder']);
}
if (isset($_REQUEST['qtype'])) {
	$qtype = mysqli_real_escape_string($conn, $_REQUEST['qtype']);
}
if (isset($_REQUEST['query'])) {
	$query = mysqli_real_escape_string($conn, $_REQUEST['query']);
}
if (isset($_REQUEST['rp'])) {
	$rp = mysqli_real_escape_string($conn, $_REQUEST['rp']);
}
// Setup sort and search SQL using posted data
$hasReadAccess = isAccessible($_SESSION['RoleId'], $menu_key, 'R');
$hasWriteAccess = isAccessible($_SESSION['RoleId'], $menu_key, 'W');
$hasExecuteAccess = isAccessible($_SESSION['RoleId'], $menu_key, 'E');

$sortSql = "order by $sortname $sortorder";

if ($qtype == 'usage_cat') {
	$searchSql = " where  medicine_usage_cat_id  in ( select medicine_usage_cat_id  from medicine_usage_cat where medicine_usage_cat_name like '%" . trim($query) . "%') and item_id in (select item_id from items_id where status='1') $AndOhcFilter and stock_qty>0";
} else if ($qtype == 'item_desc') {
	$searchSql = " where  item_id  in ( select item_id  from tbl_items where status='1' and item_name like '%" . trim($query) . "%')$AndOhcFilter and stock_qty>0";
} else if ($qtype == 'item_code') {
	$item_id = getFieldFromTable('item_id', 'tbl_items', 'item_code', trim($query));
	$searchSql = ($qtype != '' && $query != '') ? "where item_id  = $item_id $AndOhcFilter " : "$WhereOhcFilter";
} else if ($qtype == 'expiry_date') {
	$time = strtotime(trim($query));
	$exp_date = date('Y-m-d', $time);
	$searchSql = ($qtype != '' && $query != '') ? "where expiry_date = '" . $exp_date . "' $AndOhcFilter" : "$WhereOhcFilter";
} else {
	$searchSql = ($qtype != '' && $query != '') ? "where upper($qtype) like upper('%" . trim($query) . "%')$AndOhcFilter " : "$WhereOhcFilter and stock_qty>0";
}

$ohc_id = $_SESSION['current_ohcttype'];
// Get total count of records
$sql = "select count(distinct item_id)  from item_stock $searchSql ";

error_log("stock query count" . $sql);
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$total = $row[0];
if (!isset($rp)) {
	$rp = 10;
}
// Setup paging SQL
// $rp=1;
$pageStart = ($page - 1) * $rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();

// $sql1 = "select item_stock_id,item_id,item_batch_no,expiry_date,stock_qty from item_stock ";
$sql1 = "select distinct(item_id) from item_stock";

$sql_export = $sql1;
$sql1 .= " $searchSql $sortSql $limitSql ";


error_log("stock query " . $sql1);

$sql_export .= " $searchSql $sortSql ";

$results = mysqli_query($conn, $sql1);
$count = ($page - 1) * $rp + 1;
// echo $sql1;
// echo $access_level;

while ($row1 = mysqli_fetch_assoc($results)) {

	$total_available = 0;
	$total_hold = 0;
	$total_stock = 0;

	extract($row1);
	$item_id = $row1['item_id'];
	$item_desc = getItemWithFormName($item_id);
	$item_code = getTableFieldValue('tbl_items', 'item_code', 'item_id', $item_id);
	$unit_id = getTableFieldValue('tbl_items', 'unit_id', 'item_id', $item_id);
	$unit_name = getTableFieldValue('unit_master', 'unit_name', 'unit_id', $unit_id);
	$medicine_usage_cat_name = getTableFieldValue('medicine_usage_cat', 'medicine_usage_cat_name', 'medicine_usage_cat_id', $row1['medicine_usage_cat_id']);

	$sql_details = "";

	if ($qtype != '' && $qtype == 'expiry_date' && $query != '') {
		$exp_date = date('Y-m-d', strtotime($query));
		$sql_details = "select item_stock_id,item_id,item_batch_no,expiry_date,stock_qty from item_stock where item_id='" . $row1['item_id'] . "' and expiry_date='" . $exp_date . "' $AndOhcFilter";
	} else {
		$sql_details = "select item_stock_id,item_id,item_batch_no,expiry_date,stock_qty from item_stock where item_id='" . $row1['item_id'] . "' $AndOhcFilter";
	}
	error_log("Detail Query" . $sql_details);
	$result_details = mysqli_query($conn, $sql_details);
	$detailed_info = '';

	while ($row_details = mysqli_fetch_assoc($result_details)) {
		extract($row_details);
		$item_stock = $stock_qty;
		$sql_item_stock1 = "select sum(issue_qty),item_batch_no from stock_issue_items where stock_issue_id in (select stock_issue_id from stock_issue where STATUS='N' or STATUS='R' ) and item_id=$item_id and item_batch_no='" . $item_batch_no . "'  group by item_batch_no,item_id and stock_qty>0 ";
		$result_item_stock1 = mysqli_query($conn, $sql_item_stock1);
		$row_item_stock1 = mysqli_fetch_array($result_item_stock1);
		if ($row_item_stock1[0] != "" && $row_item_stock1[0] != null) {
			$hold_qty = $row_item_stock1[0];
		} else {
			$hold_qty = 0.0;
		}
		$item_stock += $hold_qty;
		$total_hold += $hold_qty; //total stock to be inclusive of hold qty but would not be available for issue
		$total_stock += $item_stock;
		$available_qty = floatval($item_stock) - floatval($hold_qty);

		if ($total_stock > 0) { //display only if there is some stock or else do not list the item batch
			$edit_link1 = "";
			if ($hasWriteAccess || $hasExecuteAccess) {
				$edit_link1 = "<a href=\"#\" class=\"blue\" onclick=\"open_item('" . $item_id . "','" . $item_batch_no . "','E');\"><i class=\"ace-icon fa fa-pencil bigger-130\"></i></a>";
			}

			$detailed_info .= "<p><b>Batch</b>:" . $item_batch_no;
			$detailed_info .= ", <b>Expiry</b>:";
			$detailed_info .= (isset($row_details['expiry_date'])) ? date_format(date_create($row_details['expiry_date']), "d-m-Y") : "";
			$detailed_info .= ", <b>Stock</b>: " . $item_stock . " " . $unit_name;
			$detailed_info .= ", <b>Hold</b>: " . $hold_qty . " " . $unit_name;
			$detailed_info .= ", <b>Available</b>: " . $available_qty . " " . $unit_name;
			$detailed_info .= "&nbsp; " . $edit_link1;
		}
	}

	//$links = $edit_link1;
	$total_available += floatval($total_stock) - floatval($total_hold);
	$data['rows'][] = array(
		'id' => $row1['item_id'],
		'cell' => array(
			$count++,
			$item_desc,
			$item_code,
			$medicine_usage_cat_name,
			$total_stock . " " . $unit_name,
			// $total_hold . " " . $unit_name,
			// $total_available . " " . $unit_name,
			$detailed_info
		)
	);
}
$data['rows'][] = array(
	'id' => $row['filterkey'],
	'cell' => array(
		'',
		"<input type=hidden name='filterkey' id='filterkey' value=\"" . base64_encode($sql_export) . "\">",
		"<input type=hidden name=paramlist id=paramlist value=\"" . base64_encode($paramlist) . "\">",
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		'',
		''
	)
);
echo json_encode($data);
?>