<?php
include('includes/config/config.php');
include('includes/functions.php');
include('log_entry.php');
$noOfRows = $_POST['count_items'];
error_log($_SESSION['current_ohcttype']);

$sql = "select a.*,date(a.start_date_time) as date from shift_status_details a where current_status='R' and ohc_location_id='" . $_SESSION['current_ohcttype'] . "'";
$result = @mysqli_query($conn, $sql);
error_log("rows counting for checking current running shift " . mysqli_num_rows($result));
if (!$row = @mysqli_fetch_assoc($result)) {
	error_log($sql);
}
$data = '';
$shift_id = $_POST['shift_id'];

$shift_id_new = $row['shift_id'];
$date = $row['record_date'];

error_log("existing shift" . $shift_id_new);
error_log("existing date" . $date);

// echo $procurement_refno;
begin();
if (mysqli_num_rows($result) != 0) {
	$query = "update shift_status_details set end_date_time=NOW(),current_status='C',modified_by = '" . $_SESSION['user_id'] . "' where current_status='R' and ohc_location_id='" . $_SESSION['current_ohcttype'] . "' ";
	$data = $shift_id_new;
	updateItemStockDispensaryShiftBalance($_SESSION['current_ohcttype'], $shift_id_new, $date);
	// updateItemStockStoreShiftBalance($shift_id_new,$date);
} else {

	$query = "insert into shift_status_details set record_date=NOW(),shift_id='" . $shift_id . "',start_date_time=NOW(),current_status='R',ohc_location_id='" . $_SESSION['current_ohcttype'] . "',modified_by = '" . $_SESSION['user_id'] . "' ";
	$data = 1;
	error_log("query:" . $query);
}

if (!$result = @mysqli_query($conn, $query)) {
	error_log("Failed to save Shift Status:" . mysqli_error($conn) . ".  Failed query:" . $query);
	rollback();
	exit(error_log(mysqli_error($conn)));
}
echo json_encode($data);
commit();