<?php
require "global.ajax.php";

switch ($_GET["op"]) {

	case 'ajaxSaveStockAdjustment':

		// POST VARIABLES
		$adjust_ent_id = isset($_POST["adjust_ent_id"]) ? funCheckInput($_POST["adjust_ent_id"]) : "";
		$adjust_pos_id = isset($_POST["adjust_pos_id"]) ? funCheckInput($_POST["adjust_pos_id"]) : "";
		$adjust_type = isset($_POST["adjust_type"]) ? funCheckInput($_POST["adjust_type"]) : "";
		$adjust_product_id = isset($_POST["adjust_product_id"]) ? funCheckInput($_POST["adjust_product_id"]) : "";
		$adjust_current_stock = isset($_POST["adjust_current_stock"]) ? funCheckInput($_POST["adjust_current_stock"]) : "";
		$adjust_quantity = isset($_POST["adjust_quantity"]) ? funCheckInput($_POST["adjust_quantity"]) : "";
		$adjust_reason = isset($_POST["adjust_reason"]) ? funCheckInput($_POST["adjust_reason"]) : "";

		if (empty($adjust_ent_id)) $adjust_ent_id = $session_user_ent_id;
		if (empty($adjust_pos_id)) $adjust_pos_id = $session_user_pos_id;

		try {

			$pdo->beginTransaction();

			$stmt = $pdo->prepare("INSERT INTO tb_stock_adjustments (
				adjust_ent_id,
				adjust_pos_id,
				adjust_user_id,
				adjust_type,
				adjust_product_id,
				adjust_current_stock,
				adjust_quantity,
				adjust_reason
			) VALUES (
				:ent_id,
				:pos_id,
				:user_id,
				:type,
				:product_id,
				:current_stock,
				:quantity,
				:reason
			)");

			$stmt->execute([
				':ent_id'        => $adjust_ent_id,
				':pos_id'        => $adjust_pos_id,
				':user_id'       => $session_user_id,
				':type'          => $adjust_type,
				':product_id'    => $adjust_product_id,
				':current_stock' => $adjust_current_stock,
				':quantity'      => $adjust_quantity,
				':reason'        => $adjust_reason
			]);

			$pro_description = getProductsData($adjust_product_id)['pro_description'];

			$stockFinal = "";

			if ($adjust_type == "Increase") {
				$stockFinal = $adjust_current_stock + $adjust_quantity;
				$type = $posTranslate['increased_the_stock_of_product'];
			}

			if ($adjust_type == "Decrease") {
				$stockFinal = $adjust_current_stock - $adjust_quantity;
				$type = $posTranslate['decreased_the_stock_of_product'];
			}

			$posName = getBranchData($adjust_pos_id)['pos_name'];
			$posName = strtoupper($posName);
			$productName = strtoupper($pro_description);

			$log_description = "{$session_user_fullname} ID:{$session_user_id}, {$type} {$productName} ID: {$adjust_product_id}, {$posTranslate['of_the_pos']}: {$posName}, {$posTranslate['by_a_quantity_of']}: {$adjust_quantity}, {$posTranslate['previous_stock']}: {$adjust_current_stock}, {$posTranslate['final_stock']}: {$stockFinal}. {$posTranslate['for_the_reason_of']}: {$adjust_reason}.";

			if ($session_user_profile == "ROOT") {
				$saveLogs = saveLog($session_user_ent_id, $session_user_pos_id, $session_user_id, $log_description, $currentDateTimeByZone);
			} else {
				$saveLogs = saveLog($adjust_ent_id, $adjust_pos_id, $session_user_id, $log_description, $currentDateTimeByZone);
			}

			$response = array("message" => $translate['saved_successfully'], "status" => "success");

			$pdo->commit();
		} catch (\RuntimeException | \InvalidArgumentException $e) {
			if ($pdo->inTransaction()) $pdo->rollBack();
			$response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
		} catch (\PDOException $e) {
			if ($pdo->inTransaction()) $pdo->rollBack();
			$response = array("status" => "error", "message" => "Database error. {$translate['execution_failed_please_contact_the_system_vendor_for_technical_assistance']} <br>" . $e->getMessage(), "redirect" => true);
		}

		echo json_encode($response);

		break;


	case 'ajaxStockAdjustmentList':

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";
		$pro_id = isset($_GET["pro_id"]) ? funCheckInput($_GET["pro_id"]) : "";
		$dateFrom = isset($_GET["fromDate"]) ? funCheckInput($_GET["fromDate"]) : "";
		$dateTo = isset($_GET["toDate"]) ? funCheckInput($_GET["toDate"]) : "";

		$whereAdjustProId = "";
		if (!empty(trim((string) $pro_id))) {
			$whereAdjustProId = "AND adjust_product_id = {$pro_id}";
		}

		$whereDate = "AND DATE_FORMAT(adjust_datetime, '%Y-%m-%d %H:%i:%s') BETWEEN '{$last7Days} 07:00:00' AND '{$tomorrowEnd}'";

		if (!empty(trim((string) $dateFrom)) && !empty(trim((string) $dateTo))) {
			$fromDate = date("{$dateFrom} 07:00:00");
			$toDate = date("Y-m-d", strtotime("{$dateTo} +1 day")) . " 06:59:59";
			$whereDate = "AND DATE_FORMAT(adjust_datetime, '%Y-%m-%d %H:%i:%s') BETWEEN '{$fromDate}' AND '{$toDate}'";
		}

		$sql = "SELECT
		adjust_id
		,(SELECT pos_name FROM tb_pos WHERE pos_id = adjust_pos_id) AS pos_name
		,DATE_FORMAT(adjust_datetime, '%d-%b-%Y %H:%i:%s') AS adjust_datetime
		,(SELECT CONCAT(user_firstname,' ',user_lastname) FROM tb_users WHERE user_id = adjust_user_id) AS user_fullname
		,(SELECT pro_description FROM tb_products WHERE pro_id = adjust_product_id) AS product_name
		,adjust_type
		,adjust_current_stock
		,adjust_quantity
		,IF(adjust_type = 'Increase',IFNULL(adjust_current_stock+adjust_quantity,0),IFNULL(adjust_current_stock-adjust_quantity,0)) AS adjust_final_stock
		,adjust_reason
		FROM tb_stock_adjustments
		WHERE adjust_ent_id = {$ent_id} AND adjust_pos_id = {$pos_id} $whereAdjustProId $whereDate
		ORDER BY adjust_id ASC;";

		// exit($sql);

		$result = executePDOFetchAllAPI($sql);
		echo json_encode($result);

		exit();

		// $result = executePDOFetchAll($sql, $translate['error_display_sale_list']);

		// $data = array();
		// /*=============================================
		// SEND DATA TO DATATABLE
		// =============================================*/

		// foreach ($result as $key => $value) {

		// 	$session_user_fullname = $value["user_fullname"];
		// 	if (!empty(trim((string) $session_user_fullname))) {
		// 		$users = explode("-", $session_user_fullname);
		// 		$added_by = $users[0] . ' ' . substr($users[1], 0, 1) . '.';
		// 	} else {
		// 		$added_by = "";
		// 	}

		// 	$stockFinal = "";
		// 	$increase = 0;
		// 	$decrease = 0;
		// 	$stockFinal = "";

		// 	if ($value['adjust_type'] == "Increase") {
		// 		$stockFinal = $value['adjust_current_stock'] + $value['adjust_quantity'];
		// 		$increase = $value['adjust_quantity'];
		// 	}

		// 	if ($value['adjust_type'] == "Decrease") {
		// 		$stockFinal = $value['adjust_current_stock'] - $value['adjust_quantity'];
		// 		$decrease = $value['adjust_quantity'];
		// 	}

		// 	$status = "<span>{$translate['canceled']}</span>";

		// 	if ($value['adjust_status'] == "Active") $status = '<div class="form-check form-switch mb-2"> <input class="form-check-input" type="checkbox" onclick="js_cancel(' . $value['adjust_id'] . ')" id="flexSwitchCheckChecked" checked> <label class="form-check-label" for="flexSwitchCheckChecked">' . $translate['enabled'] . '</label> </div>';

		// 	$data[] = array(

		// 		"0" => $value['adjust_id'],
		// 		"1" => $value['pos_name'],
		// 		"2" => $value['adjust_datetime'],
		// 		"3" => $added_by,
		// 		"4" => $value['product_name'],
		// 		"5" => $value['adjust_type'],
		// 		"6" => $value['adjust_current_stock'],
		// 		"7" => $increase,
		// 		"8" => $decrease,
		// 		"9" => $stockFinal,
		// 		"10" => $value['adjust_reason'],
		// 		"11" => $status
		// 	);
		// }

		// $results = array(

		// 	"sEcho" => 1, //Información para el datatables
		// 	"iTotalRecords" => count($data), //enviamos el total registros al datatable
		// 	"iTotalDisplayRecords" => count($data), //enviamos el total registros a visualizar
		// 	"aaData" => $data
		// );

		// echo json_encode($results);

		break;
}
