<?php
include ('includes/config/config.php');
include ('includes/functions.php');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);
// include log entry header file
include ('log_entry.php');


// error_reporting(E_ERROR | E_PARSE);
$appointment_id = $_REQUEST['appointment_id'];

if (empty($appointment_id)) {

	$query = "select max(appointment_id)  appointment_id from employee_appointment ";
	// echo $query;
	error_log("max appointment_id query: " . $query);
	if (!$result = @mysqli_query($conn, $query)) {
		rollback();
		die(error_log(mysqli_error($conn)));
	}
	if (mysqli_num_rows($result) > 0) {
		while ($row = mysqli_fetch_assoc($result)) {
			$appointment_id = $row['appointment_id'] + 1;
		}
	}
}

error_log("appointment_id" . $appointment_id);
$consume_id = $_REQUEST['detentionId'];
$data = array();
$appointment_date = date('Y-m-d', strtotime($_POST['appointment_date']));

$disposal_time = ($_POST['disposal_time'] != null) ? date('Y-m-d', strtotime($_POST['disposal_time'])) : null;
$query = "";
$query_initial = "";
$query_end = " ";
begin();


$sql_select_existing = "select * from  opd_consumables where  consume_id='" . $appointment_id . "' ";
$results = mysqli_query($conn, $sql_select_existing);
$num_rows_existing = mysqli_num_rows($results);
// if update case found
if ($num_rows_existing != 0) {
	//add back to the dispensary stock the existing qty
	if ($_SESSION['RoleCode'] == 'DIS' || in_array('DIS', $Rolecodes)) {
		resetOPDConsumablesDispensaryItemsStock($appointment_id, $_SESSION['current_ohcttype']);
	} else {
		resetOPDConsumablesStoreItemsStock($appointment_id, $_SESSION['current_ohcttype']);
	}

	//then delete the record
	if (!@mysqli_query($conn, "delete from  opd_consumables where  consume_id='" . $appointment_id . "' ")) {
		error_log("No records found for deletion:" . mysqli_error($conn));
		rollback();
		die(mysqli_error($conn));
	}
}

for ($i = 0; $i < $_REQUEST['count_items1']; $i++) {
	if (${"medicine$i"} != null && ${"medicine$i"} != "") {
		$query_consumables = "insert into  opd_consumables  SET consume_id='" . $appointment_id . "',
              medicine='" . addslashes(${"medicine$i"}) . "',consum_item_batch_no='" . addslashes(${"consum_item_batch_no$i"}) . "',issued_qty='" . ${"issued_qty$i"} . "',modified_by='" . $_SESSION['user_id'] . "'  ";
		error_log("queryyyyyy" . $query_consumables);
		if (!$result = @mysqli_query($conn, $query_consumables)) {
			error_log("Error Saving consumables data: " . mysqli_error($conn) . " Failed Query:" . $query_consumables);
			rollback();
			die(mysqli_error($conn));
		}


		// insert or update the cost details start
		$past_consume_id = getTableFieldValue('treatment_cost_master', 'consumable_id', 'item_id', ${"medicine$i"}, 'consumable_id', $appointment_id);

		if ($past_consume_id != "" || $past_consume_id != null) {
			error_log("update case for cost saving for detention ");
			$initquery = "update ";
			$endquery = " where item_id='" . ${"medicine$i"} . "' and consumable_id='" . $appointment_id . "'";
		} else {
			$initquery = "insert into ";
			$endquery = "";
		}


		$present_per_unit_cost = getTableFieldValue('item_cost', 'item_rate_latest', 'ohc_type_id', $_SESSION['current_ohcttype'], 'item_id', ${"medicine$i"});

		$total_cost = round($present_per_unit_cost * ${"issued_qty$i"});

		error_log("latest rate for item id " . getItemWithFormName(${"medicine$i"}) . " " . $present_per_unit_cost . "  total sum for this item " . $total_cost);

		$insert_treatment_cost = $initquery . " treatment_cost_master set consumable_id='" . $appointment_id . "',ohc_type_id='" . $_SESSION['current_ohcttype'] . "',issued_item_cost='" . $total_cost . "',item_id='" . ${"medicine$i"} . "' $endquery";

		error_log("cost saving query for opd consumables" . $insert_treatment_cost);

		if (!$insert_treatment_cost_result = mysqli_query($conn, $insert_treatment_cost)) {
			error_log("error in cost saving query for opd consumables" . mysqli_error($conn));
		}


		// insert or update the cost details end
		//reduce the new stock qty from the dispensary stock
		if ($_SESSION['RoleCode'] == 'DIS' || in_array('DIS', $Rolecodes)) {
			updateItemStockAtDispensaryLevel($_SESSION['current_ohcttype'], addslashes(${"medicine$i"}), ${"issued_qty$i"}, );
		} else {
			updateItemStockAtStoreLevel($_SESSION['current_ohcttype'], addslashes(${"medicine$i"}), ${"issued_qty$i"}, ${"consum_item_batch_no$i"});
		}
	}
}


commit();
$data['appointment_id'] = $appointment_id;
echo json_encode($data);
?>