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

switch ($_GET["op"]) {

	/* This is the code that is executed when the user clicks on the save button. */
	case 'ajaxSaveUpdate':

		// POST VARIABLES
		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$pos_ent_id = isset($_POST["pos_ent_id"]) ? funCheckInput($_POST["pos_ent_id"]) : "";
		$pos_name = isset($_POST["pos_name"]) ? funCheckInput($_POST["pos_name"]) : "";
		$pos_name = mb_strtoupper($pos_name);
		$pos_business_category = isset($_POST["pos_business_category"]) ? funCheckInput($_POST["pos_business_category"]) : "";
		$pos_currency = isset($_POST["pos_currency"]) ? funCheckInput($_POST["pos_currency"]) : "";
		$pos_country = isset($_POST["pos_country"]) ? funCheckInput($_POST["pos_country"]) : "";
		$pos_state = isset($_POST["pos_state"]) ? funCheckInput($_POST["pos_state"]) : "";
		$pos_zip_code = isset($_POST["pos_zip_code"]) ? funCheckInput($_POST["pos_zip_code"]) : "";
		$pos_city = isset($_POST["pos_city"]) ? funCheckInput($_POST["pos_city"]) : "";
		$pos_time_zone = isset($_POST["pos_time_zone"]) ? funCheckInput($_POST["pos_time_zone"]) : "";
		$pos_address = isset($_POST["pos_address"]) ? funCheckInput($_POST["pos_address"]) : "";
		$pos_phone = isset($_POST["pos_phone"]) ? funCheckInput($_POST["pos_phone"]) : "";
		$pos_phone2 = isset($_POST["pos_phone2"]) ? funCheckInput($_POST["pos_phone2"]) : "";
		$pos_usd_exchange_rate = isset($_POST["pos_usd_exchange_rate"]) ? funCheckInput($_POST["pos_usd_exchange_rate"]) : "";
		$pos_tax = isset($_POST["pos_tax"]) ? funCheckInput($_POST["pos_tax"]) : "";
		$pos_legal_tipping = isset($_POST["pos_legal_tipping"]) ? funCheckInput($_POST["pos_legal_tipping"]) : "";
		$pos_card_tax = isset($_POST["pos_card_tax"]) ? funCheckInput($_POST["pos_card_tax"]) : "";
		$pos_ticket_footer = isset($_POST["pos_ticket_footer"]) ? funCheckInput($_POST["pos_ticket_footer"]) : "";
		$pos_lang = isset($_POST["pos_lang"]) ? funCheckInput($_POST["pos_lang"]) : "";
		$pos_cash_back_percentage = isset($_POST["pos_cash_back_percentage"]) ? funCheckInput($_POST["pos_cash_back_percentage"]) : "";
		$pos_cash_back_availability_days = isset($_POST["pos_cash_back_availability_days"]) ? funCheckInput($_POST["pos_cash_back_availability_days"]) : "";
		$pos_cash_back_expiration_days = isset($_POST["pos_cash_back_expiration_days"]) ? funCheckInput($_POST["pos_cash_back_expiration_days"]) : "";
		$pos_created_by = isset($_POST["pos_created_by"]) ? funCheckInput($_POST["pos_created_by"]) : "";
		$pos_created_at = isset($_POST["pos_created_at"]) ? funCheckInput($_POST["pos_created_at"]) : "";

		try {

			$pdo->beginTransaction();

			$isNew = empty(trim($pos_id));

			if ($isNew) {

				$token_pos_code = createTokenNumber('tb_pos', 'pos_code', '10');
				$pos_code = md5($token_pos_code);

				$sqlSave = "
                    INSERT INTO tb_pos (
                    pos_code,pos_ent_id,pos_name,pos_business_category,pos_currency,pos_country,pos_state,pos_zip_code,pos_city,pos_time_zone,pos_address,pos_phone,pos_phone2,pos_usd_exchange_rate,pos_tax,pos_legal_tipping,pos_card_tax,pos_ticket_footer,pos_lang,pos_cash_back_percentage,pos_cash_back_availability_days,pos_cash_back_expiration_days,pos_created_by
                    ) VALUES (:pos_code,:pos_ent_id,:pos_name,:pos_business_category,:pos_currency,:pos_country,:pos_state,:pos_zip_code,:pos_city,:pos_time_zone,:pos_address,:pos_phone,:pos_phone2,:pos_usd_exchange_rate,:pos_tax,:pos_legal_tipping,:pos_card_tax,:pos_ticket_footer,:pos_lang,:pos_cash_back_percentage,:pos_cash_back_availability_days,:pos_cash_back_expiration_days,:pos_created_by
                    )
                ";

				$paramsValueSave = [
					':pos_code' => $pos_code,
					':pos_ent_id' => $pos_ent_id,
					':pos_name' => $pos_name,
					':pos_business_category' => $pos_business_category,
					':pos_currency' => $pos_currency,
					':pos_country' => $pos_country,
					':pos_state' => $pos_state,
					':pos_zip_code' => $pos_zip_code,
					':pos_city' => $pos_city,
					':pos_time_zone' => $pos_time_zone,
					':pos_address' => $pos_address,
					':pos_phone' => $pos_phone,
					':pos_phone2' => $pos_phone2,
					':pos_usd_exchange_rate' => $pos_usd_exchange_rate,
					':pos_tax' => $pos_tax,
					':pos_legal_tipping' => $pos_legal_tipping,
					':pos_card_tax' => $pos_card_tax,
					':pos_ticket_footer' => $pos_ticket_footer,
					':pos_lang' => $pos_lang,
					':pos_cash_back_percentage' => $pos_cash_back_percentage,
					':pos_cash_back_availability_days' => $pos_cash_back_availability_days,
					':pos_cash_back_expiration_days' => $pos_cash_back_expiration_days,
					':pos_created_by' => $session_user_id,
				];

				$pdo->prepare($sqlSave)->execute($paramsValueSave);

				$pos_id = $pdo->lastInsertId();

				// Define sale types based on category
				$saleTypes = [];

				if ($pos_business_category === "Restaurant") {
					$saleTypes = ['Local', 'Take Away', 'Delivery'];
				} elseif ($pos_business_category === "Nightclub") {
					$saleTypes = ['Local'];
				} else {
					$saleTypes = ['Local', 'Delivery'];
				}

				// Insert sale types
				$sqlSale = "INSERT INTO tb_sale_type 
				(sale_type_ent_id, sale_type_pos_id, sale_type_created_by, sale_type_name)
				VALUES (:ent_id, :pos_id, :created_by, :name)";

				$stmtSale = $pdo->prepare($sqlSale);

				foreach ($saleTypes as $type) {
					$stmtSale->execute([
						':ent_id'     => $pos_ent_id,
						':pos_id'     => $pos_id,
						':created_by' => $session_user_id,
						':name'       => $type
					]);
				}

				// Define payment types
				$paymentTypes = ['CASH', 'CREDIT CARD', 'BANK DEPOSIT', 'CASHBACK'];

				// Insert payment types
				$sqlPayment = "INSERT INTO tb_payments_type 
    			(pay_type_ent_id, pay_type_pos_id, pay_type_created_by, pay_type_name) 
    			VALUES (:ent_id, :pos_id, :created_by, :name)";

				$stmtPayment = $pdo->prepare($sqlPayment);

				foreach ($paymentTypes as $type) {
					$stmtPayment->execute([
						':ent_id'     => $pos_ent_id,
						':pos_id'     => $pos_id,
						':created_by' => $session_user_id,
						':name'       => $type
					]);
				}

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

				$sqlUpdate = "UPDATE tb_pos SET 
					pos_name = :pos_name,
					pos_business_category = :pos_business_category,
					pos_currency = :pos_currency,
					pos_country = :pos_country,
					pos_state = :pos_state,
					pos_zip_code = :pos_zip_code,
					pos_city = :pos_city,
					pos_time_zone = :pos_time_zone,
					pos_address = :pos_address,
					pos_phone = :pos_phone,
					pos_phone2 = :pos_phone2,
					pos_usd_exchange_rate = :pos_usd_exchange_rate,
					pos_tax = :pos_tax,
					pos_legal_tipping = :pos_legal_tipping,
					pos_card_tax = :pos_card_tax,
					pos_ticket_footer = :pos_ticket_footer,
					pos_lang = :pos_lang,
					pos_cash_back_availability_days = :pos_cash_back_availability_days,
					pos_cash_back_percentage = :pos_cash_back_percentage,
					pos_cash_back_expiration_days = :pos_cash_back_expiration_days
					WHERE pos_id = :pos_id";

				$paramsValueUpdate = [
					':pos_name' => $pos_name,
					':pos_business_category' => $pos_business_category,
					':pos_currency' => $pos_currency,
					':pos_country' => $pos_country,
					':pos_state' => $pos_state,
					':pos_zip_code' => $pos_zip_code,
					':pos_city' => $pos_city,
					':pos_time_zone' => $pos_time_zone,
					':pos_address' => $pos_address,
					':pos_phone' => $pos_phone,
					':pos_phone2' => $pos_phone2,
					':pos_usd_exchange_rate' => $pos_usd_exchange_rate,
					':pos_tax' => $pos_tax,
					':pos_legal_tipping' => $pos_legal_tipping,
					':pos_card_tax' => $pos_card_tax,
					':pos_ticket_footer' => $pos_ticket_footer,
					':pos_lang' => $pos_lang,
					':pos_cash_back_availability_days' => $pos_cash_back_availability_days,
					':pos_cash_back_percentage' => $pos_cash_back_percentage,
					':pos_cash_back_expiration_days' => $pos_cash_back_expiration_days,
					':pos_id' => $pos_id
				];

				$pdo->prepare($sqlUpdate)->execute($paramsValueUpdate);

				$response = array("message" => $translate['updated_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;

	/* Getting the name of the POS by the ID. */
	case 'ajaxGetPosData':

		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";
		$posInfo = getBranchData($pos_id);
		echo json_encode($posInfo);

		break;



	case 'ajaxBranchList':

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$pos_status = isset($_GET["pos_status"]) ? funCheckInput($_GET["pos_status"]) : "";

		$whereStatus = "AND pos_status = '{$pos_status}'";
		if ($pos_status == "All") $whereStatus = "";

		$sql = "SELECT * FROM tb_pos WHERE pos_ent_id = '{$ent_id}' $whereStatus ORDER BY pos_name ASC;";
		// exit($sql);
		$rows = executePDOFetchAllAPI($sql);
		echo json_encode($rows);

		break;


	case 'ajaxSwitchUsdInOnlineMenu':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_show_menu_usd_amount = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajaxSwitchFestiveMode':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_festive_mode = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);

		if ($result['status'] == "success") {

			$posName = getBranchData($pos_id)["pos_name"];

			$log_description = "{$session_user_fullname} ID: {$session_user_id}. {$translate['enabled_the_festive_mode_in_the_pos']} ID: {$pos_id} {$posName}";

			if ($status == "Off") $log_description = "{$session_user_fullname} ID: {$session_user_id}. {$translate['disabled_the_festive_mode_in_the_pos']} ID: {$pos_id} {$posName}";

			$saveLogs = saveLog($session_user_ent_id, $pos_id, $session_user_id, $log_description, $currentDateTimeByZone);
			// sendEmail($emailSender,$emailSenderName,$emailSubject,$emailReciver,$emailReciverName,$log_description);
		}

		echo json_encode($result);

		break;


	case 'ajaxSwitchOnlineMenuAccess':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_menu_access = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajaxSwitchCashbackAccess':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_cash_back_status = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajaxSwitchStatus':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_status = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajaxSwitchShowStatus':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_show = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajaxConfigShowStockMenu':

		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";
		$status = isset($_POST["status"]) ? funCheckInput($_POST["status"]) : "";

		$sql = "UPDATE tb_pos SET pos_show_stock_menu = '{$status}' WHERE pos_id = '$pos_id';";
		$result = executeQueryPDO($sql, $translate['successfully_executed'], $translate['execution_failed']);
		echo json_encode($result);

		break;


	case 'ajax_selectPos':

		$ent_id = isset($_POST["ent_id"]) ? funCheckInput($_POST["ent_id"]) : "";
		$pos_id = isset($_POST["pos_id"]) ? funCheckInput($_POST["pos_id"]) : "";

		$sql = "SELECT pos_id ,pos_name FROM tb_pos WHERE pos_ent_id = {$ent_id} GROUP BY pos_id ORDER BY pos_name;";

		// exit($sql);

		$answer = executePDOFetchAll($sql, $translate['could_not_display_data']);

		// echo '<option value="" >-- ' . $translate['select'] . ' --</option>';
		foreach ($answer as $key => $value) {
			$selected = "";
			if ($pos_id == $value['pos_id']) $selected = "selected";
			echo "<option value='{$value['pos_id']}'{$selected}>{$value['pos_name']}</option>";
		}

		break;


	case 'ajax_selectBranchesPermissionsByEntId':

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";

		// $sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_ent_id = {$ent_id} AND pos_status = 'Enabled' AND pos_show = 'On' ORDER BY pos_name ASC;";
		$sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_ent_id = {$ent_id} ORDER BY pos_name ASC;";

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

		break;


	case 'ajax_selectBranchesByPosId':

		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";

		$sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_id = {$pos_id} ORDER BY pos_name ASC;";

		$answer = executePDOFetchOneAPI($sql);
		echo json_encode($answer);

		break;


	case 'ajax_selectBranchesByUserPermission':

		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$pos_id = isset($_GET["pos_id"]) ? funCheckInput($_GET["pos_id"]) : "";

		$posEntId = $ent_id ? $ent_id : $session_user_ent_id;

		if ($session_user_profile == "ROOT" || $session_user_profile == "Owner") {

			$sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_ent_id = {$posEntId} AND pos_status = 'Enabled' ORDER BY pos_name ASC;";

			if (!empty($pos_id)) {
				$sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_id = {$pos_id} AND pos_status = 'Enabled' ORDER BY pos_name ASC;";
			}

			$res = executePDOFetchAllAPI($sql);

			if ($res["status"] == "success") {

				$posArrList = json_encode($res["data"]);

				$response = [
					"status" => "success",
					"data" => $posArrList,
					"title" => null,
					"message" => null
				];
			} else {
				$response = [
					"status" => "warning",
					"data" => null,
					"title" => $translate["access_denied"],
					"message" => $translate["you_are_not_authorized_to_access_any_branch"]
				];
			}
		} else {

			$sql = "SELECT user_branch_access FROM tb_users WHERE user_id = {$session_user_id};";

			$res = executePDOFetchOneAPI($sql);

			$has_permission = false;

			if ($res["status"] == "success") {

				$posArrList = $res["data"]["user_branch_access"];
				// Decode JSON to PHP array
				$posArrayDecoded = json_decode($posArrList, true);
				$posPermissions = $posArrayDecoded ?? [];

				// Extract pos_id values
				$posIds = array_column($posArrayDecoded, 'pos_id');

				// Join pos_id values with a comma
				$posIdString = implode(',', $posIds);
				// echo $posIdString; // Output: 2,12

				if (!empty($posIdString)) {

					$has_permission = true;

					$sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_id IN ({$posIdString}) AND pos_ent_id = {$posEntId} AND pos_status = 'Enabled' ORDER BY pos_name ASC;";

					if (!empty($pos_id)) {

						if (in_array($pos_id, $posIds)) {
							$sql = "SELECT pos_id,pos_name FROM tb_pos WHERE pos_id = {$pos_id} AND pos_ent_id = {$posEntId} AND pos_status = 'Enabled' ORDER BY pos_name ASC;";
						} else {
							$has_permission = false;
						}
					}

					$res = executePDOFetchAllAPI($sql);

					$posArrList = json_encode($res["data"]);

					$response = [
						"status" => $has_permission ? "success" : "warning",
						"data" => $posArrList,
						"title" => !$has_permission ? $translate["access_denied"] : null,
						"message" => !$has_permission ? $translate["you_are_not_authorized_to_access_this_branch"] : null
					];
				} else {
					$response = [
						"status" => "warning",
						"data" => $posArrList ?? null,
						"title" => $translate["access_denied"],
						"message" => $translate["you_are_not_authorized_to_access_any_branch"]
					];
				}
			} else {
				$response = [
					"status" => $res["status"],
					"data" => $posArrList ?? null,
					"title" => $translate["access_denied"],
					"message" => $translate["you_are_not_authorized_to_access_any_branch"]
				];
			}
		}

		echo json_encode($response);

		break;


		// case 'ajaxGetCurrencySymbolByCode':

		// 	$currency_code = isset($_GET["currency_code"]) ? funCheckInput($_GET["currency_code"]) : "";
		// 	$sql = "SELECT currency_symbol FROM tb_currencies WHERE currency_code = '{$currency_code}';";
		// 	$answer = executePDOFetchOneAPI($sql);
		// 	echo json_encode($answer);

		// 	break;
}
