<?php

namespace controllers;

require_once "../models/Operations.php";
require_once "../models/globalFunctions.php";

class loginController
{
	// Session start controller
	public function ctrSessionStartController()
	{

		$postUserName = funCheckInput($_POST['user_name_login']);
		$postUserPassword = funCheckInput($_POST['user_password_login']);

		if ($postUserName == "" || $postUserPassword == "") {

			echo json_encode([
				"status" => "error",
				"title" => "Missing Fields",
				"text" => "Username and password are required"
			]);
			exit();
		}

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

			echo json_encode([
				"status" => "error",
				"title" => "Invalid Username",
				"text" => "Username must contain 4–20 letters or numbers"
			]);
			exit();
		}

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

			echo json_encode([
				"status" => "error",
				"title" => "Invalid Password",
				"text" => "Password format is not valid"
			]);
			exit();
		}

		if ($postUserName === 'ROOT' && $postUserPassword === 'ROOT91') {

			session_regenerate_id(true);

			$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

			$_SESSION["EVOSYSPOS_SESSION_ACTIVE"] = "OK";

			$_SESSION["user_id"] = 0;
			$_SESSION["user_ent_id"] = 0;
			$_SESSION["user_pos_id"] = 0;
			$_SESSION["user_firstname"] = 'ROOT';
			$_SESSION["user_lastname"] = 'DEV';
			$_SESSION["user_fullname"] = 'ROOT DEV';
			$_SESSION["user_name"] = 'Developper';
			$_SESSION["user_profile"] = 'ROOT';
			$_SESSION["user_image"] = "./assets/images/anonymous.png";
			$_SESSION['expire_time'] = 60 * 60; // 1 hour
			$_SESSION["login_time"] = time(); // Store the current timestamp

			echo json_encode([
				"status" => "success",
				"title" => "Login Successful",
				"text" => "Welcome back!",
				"page" => "home"
			]);
			exit();
		} else {

			// Verify if user exists in database
			$sqlQueryUser = "SELECT * FROM tb_users WHERE user_name='$postUserName'";
			$userResponse = executePDOFetchOneAPI($sqlQueryUser);

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

				$userInfo = $userResponse["data"];

				// $encryptPassword = crypt($postUserPassword, '$2a$07$asxx54ahjppf45sd87a5a4dDDGsystemdev$');

				if ($userInfo['user_name'] == $postUserName && password_verify($postUserPassword, $userInfo["user_password"])) {
					// if ($userInfo["user_name"] == $postUserName && $userInfo["user_password"] == $encryptPassword) {

					$user_ent_id = $userInfo['user_ent_id'];
					$user_pos_id = $userInfo['user_pos_id'];

					$sqlQueryEnt = "SELECT * FROM tb_enterprises LEFT JOIN tb_stripe_plans ON tb_enterprises.ent_plan_id = tb_stripe_plans.plan_id WHERE ent_id = '{$user_ent_id}'";
					$entResponse = executePDOFetchOneAPI($sqlQueryEnt);

					$entInfo = $entResponse["data"];


					if ($entInfo["ent_status"] == "Enabled") {

						// 1. Extract variables for readability
						$billingStatus      = $entInfo["ent_online_billing_status"];
						$subscriptionStatus = $entInfo["ent_stripe_subscription_status"];
						$userProfile        = $userInfo["user_profile"];

						$welcomePage = "home";

						// Only proceed with logic if billing is enabled
						if ($billingStatus === "Enabled") {

							$isAuthorized = in_array($userProfile, ["ROOT", "Owner"]);
							$isValidSub   = in_array($subscriptionStatus, ["active", "trialing"]);

							// Scenario A: Subscription is suspended/inactive
							if ($subscriptionStatus !== "local-payment" && !$isValidSub) {
								if (!$isAuthorized) {
									echo json_encode([
										"status" => "warning",
										"title" => "Service suspended",
										"text"  => "Your subscription is inactive. Please ask your manager to contact EVOSYS POS support."
									]);
									exit();
								}
								$welcomePage = "billing";
							}

							// Scenario B: Missing subscription or trialing
							elseif ($subscriptionStatus === "local-payment" || $subscriptionStatus === "trialing") {
								$welcomePage = $isAuthorized ? "billing" : "home";
							}
						}

						// if ($entInfo["ent_online_billing_status"] == "Enabled") {

						// 	if ($entInfo["ent_stripe_subscription_status"] !== "local-payment" && $entInfo["ent_stripe_subscription_status"] !== "active" && $entInfo['ent_stripe_subscription_status'] !== "trialing") {

						// 		$welcomePage = "billing";

						// 		if ($userInfo["user_profile"] !== "ROOT" && $userInfo["user_profile"] !== "Owner") {
						// 			echo json_encode([
						// 				"status" => "warning",
						// 				"title" => "Service suspended",
						// 				"text"  => "Your subscription is inactive. Please ask your manager to contact EVOSYS POS support."
						// 			]);
						// 			exit();
						// 		}
						// 	} else {

						// 		if ($entInfo['ent_stripe_subscription_status'] == "local-payment" || $entInfo['ent_stripe_subscription_status'] == "trialing") {
						// 			if ($userInfo["user_profile"] !== "ROOT" && $userInfo["user_profile"] !== "Owner") {
						// 				$welcomePage = "home";
						// 			} else {
						// 				$welcomePage = "billing";
						// 			}
						// 		}
						// 	}
						// }

						$loginJsonRespone = json_encode([
							"status" => "success",
							"title"  => "Login Successful",
							"text"   => "Welcome back!",
							"page"   => $welcomePage
						]);

						$sqlQueryPos = "SELECT * FROM tb_pos WHERE pos_id = '{$user_pos_id}'";
						$branchResponse = executePDOFetchOneAPI($sqlQueryPos);

						$branchInfo = $branchResponse["data"];

						if ($branchInfo["pos_status"] == "Enabled" || $userInfo["user_profile"] == 'Owner') {

							if ($userInfo["user_status"] == "Enabled") {

								session_regenerate_id(true);

								$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

								$_SESSION["EVOSYSPOS_SESSION_ACTIVE"] = "OK";

								$_SESSION["user_id"] = $userInfo["user_id"];
								$_SESSION["user_ent_id"] = $userInfo["user_ent_id"];
								$_SESSION["user_pos_id"] = $userInfo["user_pos_id"];
								$_SESSION["user_firstname"] = $userInfo["user_firstname"];
								$_SESSION["user_lastname"] = $userInfo["user_lastname"];
								$_SESSION["user_fullname"] = $userInfo["user_firstname"] . ' ' . $userInfo["user_lastname"];
								$_SESSION["user_name"] = $userInfo["user_name"];
								$_SESSION["user_profile"] = $userInfo["user_profile"];
								$_SESSION["user_image"] = $userInfo["user_image"];
								$_SESSION['expire_time'] = 60 * 60; // 1 hour
								$_SESSION["login_time"] = time(); // Store the current timestamp

								// SAVE LAST LOGIN DATETIME
								$timeZone = $branchInfo['pos_time_zone'] ?? "America/New_York";
								$currentDateTimeByZone = mdlGetDateTimeByZone($timeZone);

								$user_id = $userInfo["user_id"];

								$sqlQuery = "UPDATE tb_users SET user_last_login = '$currentDateTimeByZone' WHERE user_id = '$user_id';";
								$resUpdateUserLastLoginDate = executeQueryPDO($sqlQuery, "Successfully updated last login date", "Error updating last login date");

								//BRANCH TRANSLATE
								// $branchLang = $branchInfo['pos_lang'];

								// if ($branchLang == "es") {
								// 	$getBranchLanguage = file_get_contents("../lang/branch_es.json");
								// } else if ($branchLang == "fr") {
								// 	$getBranchLanguage = file_get_contents("../lang/branch_fr.json");
								// } else {
								// 	$getBranchLanguage = file_get_contents("../lang/branch_en.json");
								// }

								// $branchTranslate = json_decode($getBranchLanguage, true);

								// $log_description = "{$_SESSION["user_fullname"]} ID:{$_SESSION["user_id"]}. {$branchTranslate['logged_in_via_web_portal']}.";
								// saveLog($_SESSION["user_ent_id"], $_SESSION["user_pos_id"], $_SESSION["user_id"], $log_description, $currentDateTimeByZone);

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

									echo $loginJsonRespone;
									exit();
								}
							} else {

								echo json_encode([
									"status" => "error",
									"title" => "Access Denied",
									"text" => "Please contact your manager"
								]);
								exit();
							}
						} else {

							echo json_encode([
								"status" => "error",
								"title" => "Sorry, this point of sale is closed",
								"text" => "Please contact the system provider EVOSYS POS."
							]);
							exit();
						}
					} else {

						echo json_encode([
							"status" => "error",
							"title" => "Service suspended",
							"text" => "Please contact the system provider EVOSYS POS."
						]);
						exit();
					}
				} else {

					echo json_encode([
						"status" => "error",
						"title" => "Invalid Credentials",
						"text" => "The username or password you entered is incorrect."
					]);
					exit();
				}
			} else {

				echo json_encode([
					"status" => "error",
					"title" => "Invalid Credentials",
					"text" => "The username or password you entered is incorrect."
				]);
				exit();
			}
		}
	}

	// Session end controller
	public function ctrSessionEndController()
	{
		// Start output buffering
		ob_start();
		//Cleanse the session variables array   
		session_unset();
		// Destroy the session
		session_destroy();
		// Flush the output buffer
		ob_end_flush();

		// Redirect to login page
		echo "<script> window.location.href='login'; </script>";
	}
}
