<?php

//POS INFO
$posInfo = getBranchData($_SESSION["user_pos_id"]);

//Establecemos la fecha actual
$timeZone = $posInfo['pos_time_zone'] ?? "America/New_York";
$currentDateTimeByZone = mdlGetDateTimeByZone($timeZone);

date_default_timezone_set($timeZone);

if ($_SESSION["user_id"] > 0) {

	$user_id = $_SESSION["user_id"];

	$sql = "UPDATE tb_users SET user_last_login = '$currentDateTimeByZone',user_last_activity = '$currentDateTimeByZone' WHERE user_id = '$user_id';";
	$result = executeQueryPDO($sql, "ok", " ");

	$session_user_id = $user_id;
	$session_user_ent_id = $_SESSION["user_ent_id"];
	$session_user_pos_id = $_SESSION["user_pos_id"];
	$user_fullName = $_SESSION["user_fullname"];

	//POS TRANSLATE
	$posLang = $posInfo['pos_lang'];

	if ($posLang == "es") {
		$getPosLanguage = file_get_contents("lang/pos_es.json");
	} else if ($posLang == "fr") {
		$getPosLanguage = file_get_contents("lang/pos_fr.json");
	} else {
		$getPosLanguage = file_get_contents("lang/pos_en.json");
	}
	$posTranslate = json_decode($getPosLanguage, true);


	if (isset($_SESSION["login_time"])) {
		$login_time = $_SESSION["login_time"];
		$logout_time = time();
		$session_duration = $logout_time - $login_time; // Duration in seconds

		// Convert seconds to days, hours, minutes, and seconds
		$days = floor($session_duration / 86400); // 86400 seconds in a day
		$hours = floor(($session_duration % 86400) / 3600);
		$minutes = floor(($session_duration % 3600) / 60);
		$seconds = $session_duration % 60;

		// Build a readable message
		$duration_message = "{$posTranslate['session_duration']}: ";

		if ($days > 0) {
			$duration_message .= "$days {$posTranslate['days']}, ";
		}

		if ($hours > 0) {
			$duration_message .= "$hours {$posTranslate['hours']}, ";
		}

		if ($minutes > 0) {
			$duration_message .= "$minutes {$posTranslate['minutes']} {$posTranslate['and']} ";
		}

		$duration_message .= "$seconds {$posTranslate['seconds']}.";
	}

	$log_description = "{$user_fullName} ID:{$session_user_id}. {$posTranslate['logged_out_via_web_portal']}. {$duration_message}";
	// saveLog($session_user_ent_id, $session_user_pos_id, $session_user_id, $log_description, $currentDateTimeByZone);
}

ob_start(); // Start output buffering

//Limpiamos las variables de sesión   
session_unset();
//Destruìmos la sesión
session_destroy();
ob_end_flush(); // Flush the output buffer

//Redireccionamos al login
echo '<script>window.location="login";</script>';
