<?php
require "global.ajax.php";
require "../controllers/cloudinary-api.php";

switch ($_GET["op"]) {

	case 'ajaxSaveUpdate':

		// POST VARIABLES
		$user_id = isset($_POST["user_id"]) ? funCheckInput($_POST["user_id"]) : "";
		$user_ent_id = isset($_POST["user_ent_id"]) ? funCheckInput($_POST["user_ent_id"]) : "";
		$user_pos_id = isset($_POST["user_pos_id"]) ? funCheckInput($_POST["user_pos_id"]) : "";
		$user_firstname = isset($_POST["user_firstname"]) ? funCheckInput($_POST["user_firstname"]) : "";
		$user_lastname = isset($_POST["user_lastname"]) ? funCheckInput($_POST["user_lastname"]) : "";
		$user_document = isset($_POST["user_document"]) ? funCheckInput($_POST["user_document"]) : "";
		$user_document_number = isset($_POST["user_document_number"]) ? funCheckInput($_POST["user_document_number"]) : "";
		$user_birthday = isset($_POST["user_birthday"]) ? funCheckInput($_POST["user_birthday"]) : "";
		$user_phone = isset($_POST["user_phone"]) ? funCheckInput($_POST["user_phone"]) : "";
		$user_email = isset($_POST["user_email"]) ? funCheckInput($_POST["user_email"]) : "";
		$user_address = isset($_POST["user_address"]) ? funCheckInput($_POST["user_address"]) : "";
		$user_profile = isset($_POST["user_profile"]) ? funCheckInput($_POST["user_profile"]) : "";
		$user_name = isset($_POST["user_name"]) ? funCheckInput($_POST["user_name"]) : "";
		$user_password = isset($_POST["user_password"]) ? funCheckInput($_POST["user_password"]) : "";
		$user_password_confirm = isset($_POST["user_password_confirm"]) ? funCheckInput($_POST["user_password_confirm"]) : "";
		$current_password = isset($_POST["current_password"]) ? funCheckInput($_POST["current_password"]) : "";
		$user_created_by = $session_user_id;

		$user_firstname = ucwords(strtolower($user_firstname));
		$user_lastname = ucwords(strtolower($user_lastname));

		if (empty($user_ent_id)) $user_ent_id = $session_user_ent_id;
		if (empty($user_pos_id)) $user_pos_id = $session_user_pos_id;

		try {

			$pdo->beginTransaction();

			$entData = getEnterpriseData($user_ent_id);
			$ent_folder_name = $entData['ent_folder_name'];
			$saveToFolder = "evosyspos/{$ent_folder_name}/users";

			if (mdlVerifyData("[a-zA-Z0-9]{4,20}", $user_name)) {

				echo json_encode([
					"status" => "warning",
					"message" => "{$translate['invalid_username']}<br>{$translate['username_must_contain_4_20_letters_or_numbers']}."
				]);
				exit();
			}

			if (empty($user_password)) {
				$hashedPassword = $current_password;
			} else {

				if ($user_password == $user_password_confirm) {

					if (mdlVerifyData("[a-zA-Z0-9$@.-]{4,100}", $user_password)) {

						echo json_encode([
							"status" => "warning",
							"message" => "{$translate['invalid_password']}<br>{$translate['password_must_contain_4_20_letters_or_numbers']}."
						]);
						exit();
					} else {
						$hashedPassword = password_hash($user_password_profile, PASSWORD_DEFAULT);
					}
				} else {

					$response = array("status" => "warning", "message" => "{$translate['passwords_do_not_match']}.<br>{$translate['confirm_your_password_correctly']}");
					echo json_encode($response);
					exit();
				}
			}

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

			if ($isNew) {

				$checkIfExist = checkDuplication('tb_users', 'user_name', $user_name);

				if ($checkIfExist) {

					$response = array("status" => "warning", "message" => "{$translate['this_username_already_exists_please_try_another_one']}.");
					echo json_encode($response);
					exit();
				} else {

					$posInfo = getBranchData($user_pos_id);

					$posAccess = [['pos_id' => $posInfo['pos_id'], 'pos_name' => $posInfo['pos_name']]];
					$posAccessJson = json_encode($posAccess, JSON_PRETTY_PRINT);

					$stmt = $pdo->prepare("INSERT INTO tb_users (user_ent_id,user_pos_id,user_firstname,user_lastname,user_document,user_document_number,user_birthday,user_phone,user_email,user_address,user_profile,user_branch_access,user_name,user_password,user_created_by
					) VALUES (:ent_id,:pos_id,:firstname,:lastname,:document,:document_number,:birthday,:phone,:email,:address,:profile,:branch_access,:username,:password,:created_by
					)");

					$stmt->execute([
						':ent_id'          => $user_ent_id,
						':pos_id'          => $user_pos_id,
						':firstname'       => $user_firstname,
						':lastname'        => $user_lastname,
						':document'        => $user_document,
						':document_number' => $user_document_number,
						':birthday'        => $user_birthday,
						':phone'           => $user_phone,
						':email'           => $user_email,
						':address'         => $user_address,
						':profile'         => $user_profile,
						':branch_access'   => $posAccessJson, // JSON string
						':username'        => $user_name,
						':password'        => $hashedPassword,
						':created_by'      => $user_created_by
					]);

					$user_id = $pdo->lastInsertId();

					// Handle image upload (shared logic)
					if (isset($_FILES['user_image']) && is_uploaded_file($_FILES['user_image']['tmp_name'])) {

						$maxSize = 2 * 1024 * 1024; // 2MB
						if ($_FILES["user_image"]["size"] > $maxSize) {
							if ($pdo->inTransaction()) $pdo->rollBack();
							$response = array("status" => "warning", "message" => "File exceeds 2MB limit.");
							echo json_encode($response);
							exit();
						}

						$sourceFilePath = $_FILES["user_image"]["tmp_name"];
						$fileName = "user_{$user_id}";
						$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName, $oldFileToDelete = "");

						$imageUrl = $resCloudUpload['secure_url'];

						$sql = "UPDATE tb_users SET user_image = :user_image
						WHERE user_id = :user_id";

						$stmt = $pdo->prepare($sql);
						$stmt->execute([
							':user_image' => $imageUrl,
							':user_id'   => $user_id
						]);
					}
				}

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

				// CHECK IF THE USER NAME ALREADY EXISTS
				$extra = "AND user_id != '$user_id'";
				$checkIfExist = checkDuplication('tb_users', 'user_name', $user_name, $extra);

				$oldImage = getUserData($user_id)['user_image'];
				$imageUrl = $oldImage;

				if ($checkIfExist) {
					$response = array("status" => "warning", "message" => "{$translate['this_username_already_exists_please_try_another_one']}.");
					echo json_encode($response);
					exit();
				} else {

					// Handle image upload (shared logic)
					if (isset($_FILES['user_image']) && is_uploaded_file($_FILES['user_image']['tmp_name'])) {

						$maxSize = 2 * 1024 * 1024; // 2MB
						if ($_FILES["user_image"]["size"] > $maxSize) {
							// throw new \RuntimeException("File exceeds 2MB limit.");
							if ($pdo->inTransaction()) $pdo->rollBack();
							$response = array("status" => "warning", "message" => "File exceeds 2MB limit.");
							echo json_encode($response);
							exit();
						}

						$sourceFilePath = $_FILES["user_image"]["tmp_name"];
						$fileName = "user_{$user_id}";
						$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName, $oldFileToDelete = "");

						$imageUrl = $resCloudUpload['secure_url'];

						$sql = "UPDATE tb_users SET user_image = :user_image
						WHERE user_id = :user_id";

						$stmt = $pdo->prepare($sql);
						$stmt->execute([
							':user_image' => $imageUrl,
							':user_id'   => $user_id
						]);
					}

					$stmt = $pdo->prepare("UPDATE tb_users SET
						user_pos_id            = :pos_id,
						user_firstname         = :firstname,
						user_lastname          = :lastname,
						user_document          = :document,
						user_document_number   = :document_number,
						user_birthday          = :birthday,
						user_phone             = :phone,
						user_email             = :email,
						user_address           = :address,
						user_profile           = :profile,
						user_name              = :username,
						user_password          = :password,
						user_image             = :image,
						user_edited_by         = :edited_by,
						user_edited_at         = :edited_at
						WHERE user_id 		   = :user_id
					");

					$stmt->execute([
						':pos_id'          => $user_pos_id,
						':firstname'       => $user_firstname,
						':lastname'        => $user_lastname,
						':document'        => $user_document,
						':document_number' => $user_document_number,
						':birthday'        => $user_birthday,
						':phone'           => $user_phone,
						':email'           => $user_email,
						':address'         => $user_address,
						':profile'         => $user_profile,
						':username'        => $user_name,
						':password'        => $hashedPassword,
						':image'           => $imageUrl,
						':edited_by'       => $session_user_id,
						':edited_at'       => $currentDateTimeByZone,
						':user_id'         => $user_id
					]);
				}

				$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;


	case 'ajaxSaveUpdateUserProfile':

		// POST VARIABLES
		$user_id_profile = isset($_POST["user_id_profile"]) ? funCheckInput($_POST["user_id_profile"]) : "";
		$user_name_profile = isset($_POST["user_name_profile"]) ? funCheckInput($_POST["user_name_profile"]) : "";
		$user_password_profile = isset($_POST["user_password_profile"]) ? funCheckInput($_POST["user_password_profile"]) : "";
		$user_password_confirm_profile = isset($_POST["user_password_confirm_profile"]) ? funCheckInput($_POST["user_password_confirm_profile"]) : "";
		$current_password_profile = isset($_POST["current_password_profile"]) ? funCheckInput($_POST["current_password_profile"]) : "";
		$user_image_profile = isset($_POST["user_image_profile"]) ? funCheckInput($_POST["user_image_profile"]) : "";

		try {

			$pdo->beginTransaction();

			if (mdlVerifyData("[a-zA-Z0-9]{4,20}", $user_name_profile)) {

				echo json_encode([
					"status" => "warning",
					"message" => "{$translate['invalid_username']}<br>{$translate['username_must_contain_4_20_letters_or_numbers']}."
				]);
				exit();
			}

			if (empty($user_password_profile)) {
				$hashedPassword = $current_password_profile;
			} else {

				if ($user_password_profile == $user_password_confirm_profile) {

					if (mdlVerifyData("[a-zA-Z0-9$@.-]{4,100}", $user_password_profile)) {

						echo json_encode([
							"status" => "warning",
							"message" => "{$translate['invalid_password']}<br>{$translate['password_must_contain_4_20_letters_or_numbers']}."
						]);
						exit();
					} else {
						$hashedPassword = password_hash($user_password_profile, PASSWORD_DEFAULT);
					}
				} else {

					$response = array("status" => "warning", "title" => "{$translate['passwords_do_not_match']}", "message" => "{$translate['confirm_your_password_correctly']}");
					echo json_encode($response);
					exit();
				}
			}

			// CHECK IF THE USER NAME ALREADY EXISTS
			$extra = "AND user_id != '$user_id_profile'";
			$checkIfExist = checkDuplication('tb_users', 'user_name', $user_name_profile, $extra);

			if ($checkIfExist) {
				$response = array("status" => "warning", "message" => "{$translate['this_username_already_exists_please_try_another_one']}.");
				echo json_encode($response);
				exit();
			} else {

				$userInfo = getUserData($user_id_profile);
				$entData = getEnterpriseData($userInfo['user_ent_id']);
				$ent_folder_name = $entData['ent_folder_name'];
				$saveToFolder = "evosyspos/{$ent_folder_name}/users";

				$oldImage = $userInfo['user_image'];
				$imageUrl = $oldImage;

				// Handle image upload (shared logic)
				if (isset($_FILES['user_image_profile']) && is_uploaded_file($_FILES['user_image_profile']['tmp_name'])) {

					$maxSize = 2 * 1024 * 1024; // 2MB
					if ($_FILES["user_image_profile"]["size"] > $maxSize) {
						if ($pdo->inTransaction()) $pdo->rollBack();
						$response = array("status" => "warning", "message" => "File exceeds 2MB limit.");
						echo json_encode($response);
						exit();
					}

					$sourceFilePath = $_FILES["user_image_profile"]["tmp_name"];
					$fileName = "user_{$user_id_profile}";
					$resCloudUpload = fnUploadToCloudinary($sourceFilePath, $saveToFolder, "image", $fileName, $oldFileToDelete = "");

					$imageUrl = $resCloudUpload['secure_url'];
				}

				$stmt = $pdo->prepare("UPDATE tb_users SET
						user_name              = :username,
						user_password          = :password,
						user_image             = :image,
						user_edited_by         = :edited_by,
						user_edited_at         = :edited_at
						WHERE user_id 		   = :user_id
					");

				$stmt->execute([
					':username'        => $user_name_profile,
					':password'        => $hashedPassword,
					':image'           => $imageUrl,
					':edited_by'       => $session_user_id,
					':edited_at'       => $currentDateTimeByZone,
					':user_id'         => $user_id_profile
				]);
			}

			$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 'ajaxSaveUpdateBranchAccess':

		$user_id = $_POST["user_id"];
		$branch_permission = $_POST["branch_permission"];

		$sql = "UPDATE tb_users SET user_branch_access = '{$branch_permission}' WHERE user_id='{$user_id}';";

		$answer = executeQueryPDOApi($sql, "Updated", "USERS");

		if ($answer['status'] == "success") {
			$response = array("message" => $translate['saved_successfully'], "status" => "success");
		} elseif ($answer['status'] == "error") {
			$response = array("message" => "{$answer['message']}", "status" => "error");
		} else {
			$response = array("message" => "Error <br> {$answer['message']}", "status" => "error");
		}

		echo json_encode($response);

		break;


	/* Getting user data by the ID. */
	case 'ajaxGetUserData':

		$user_id = isset($_GET["user_id"]) ? funCheckInput($_GET["user_id"]) : "";
		$userData = getUserData($user_id);
		echo json_encode($userData);

		break;


	/* Getting user session data. */
	case 'ajaxGetUserSessionData':

		$userData = getUserData($_SESSION["user_id"]);
		echo json_encode($userData);

		break;


	// Lock screen
	case 'ajaxLockScreen':

		$_SESSION["SCREEN_LOCK"] = "LOCKED";

		break;


	/* Getting user session data. */
	case 'ajaxUnlockScreen':

		$unlockPassword = isset($_GET["unlockPassword"]) ? funCheckInput($_GET["unlockPassword"]) : "";
		// $encryptPassword = crypt($unlockPassword, '$2a$07$asxx54ahjppf45sd87a5a4dDDGsystemdev$');

		$userInfo = getUserData($_SESSION["user_id"]);

		if (password_verify($unlockPassword, $userInfo["user_password"])) {
			// if ($encryptPassword == $userInfo["user_password"]) {
			$_SESSION["SCREEN_LOCK"] = "UNLOCKED";
			$response = array("message" => "", "status" => "success");
		} else {
			$_SESSION["SCREEN_LOCK"] = "LOCKED";
			$response = array("message" => "", "status" => "error");
		}

		echo json_encode($response);

		break;


	case 'ajax_ChangeUserInterfaceLanguage':

		$lang = isset($_POST["lang"]) ? funCheckInput($_POST["lang"]) : "";
		$sql = "UPDATE tb_users SET user_language = '$lang' WHERE user_id = {$session_user_id};";
		$result = executeQueryPDO($sql, "success", "error");
		echo json_encode($result);

		break;


	case 'ajaxUsersList':

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

		$customWhere = "";
		if ($session_user_profile != "ROOT") $customWhere = "AND user_profile NOT IN ('ROOT')";
		if ($session_user_profile != "ROOT" && $session_user_profile != "Owner") $customWhere = "AND user_profile NOT IN ('ROOT','Owner')";

		$sql = "SELECT user_id,user_ent_id,user_pos_id,user_firstname,user_lastname,user_document,user_document_number,user_birthday,user_name,user_password,user_address,user_phone,user_email,user_email_report,user_image,user_profile,user_branch_access
		,(SELECT pos_name FROM tb_pos WHERE pos_id = user_pos_id) AS pos_name
		,DATE_FORMAT(user_last_activity, '%Y-%m-%d %H:%i:%s') AS user_last_activity
		,DATE_FORMAT(user_last_login, '%d-%b-%Y %H:%i:%s') AS user_last_login
		,user_status
		FROM tb_users
		WHERE user_ent_id = {$ent_id} AND user_pos_id = {$pos_id} AND user_status = '{$status}' $customWhere;";

		// exit($sql);
		$rows = executePDOFetchAllAPI($sql);
		echo json_encode($rows);

		break;


	case 'ajaxSwitchEmailReportStatus':

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

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

		break;


	case 'ajaxSwitchStatus':

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

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

		break;


	case 'ajaxShowUserData':

		$user_id = isset($_POST["user_id"]) ? funCheckInput($_POST["user_id"]) : "";
		$sql = "SELECT * FROM tb_users WHERE user_id = {$user_id};";
		$resUserInfo = executePDOFetchOne($sql, $translate['could_not_show_data']);

		$userImagePath = "assets/images/anonymous.png";
		if (!empty($resUserInfo['user_image'])) $userImagePath = $resUserInfo['user_image'];

		$userArrayInfo = array('user_firstname' => $resUserInfo['user_firstname'], 'user_lastname' => $resUserInfo['user_lastname'], 'user_profile' => $resUserInfo['user_profile'], 'user_password' => $resUserInfo['user_password'], 'user_phone' => $resUserInfo['user_phone'], 'user_email' => $resUserInfo['user_email'], 'user_address' => $resUserInfo['user_address'], 'user_city' => $resUserInfo['user_city'], 'user_name' => $resUserInfo['user_name'], 'user_image' => $resUserInfo['user_image'], 'userImagePath' => $userImagePath);

		echo json_encode($userArrayInfo);

		break;


	case 'ajaxGetUsersList':
		$ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
		$profile = isset($_GET["profile"]) ? funCheckInput($_GET["profile"]) : "";

		// $whereProfile = "";
		// if ($profile == "!Waiter") $whereProfile = "AND user_profile != 'Waiter'";

		$sql = "SELECT
		user_id
		,CONCAT(user_firstname,' ',user_lastname) AS user_full_name
		FROM tb_users
		WHERE user_ent_id = {$ent_id}
		AND user_status = 'Enabled'
		ORDER BY user_full_name ASC;";
		// exit($sql);

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

		break;


	case 'ajax_encrypt_password':

		echo $hashedPassword = password_hash($_POST["confirm_old_user_password"], PASSWORD_DEFAULT);

		break;
}
