<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
require '../../vendor/autoload.php';    

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

@session_start();

$secret_key = "theWatify$2025@#";

// Check if the token exists in cookies

if (!isset($_COOKIE["auth_token"])) {
    header("Location: /auth-login.php"); // Redirect to login page
    exit();
}

$token = $_COOKIE["auth_token"];

// try {
//     // ########################################################## Decode JWT token
//     $decoded = JWT::decode($token, new Key($secret_key, 'HS256'));
//     // Store decoded user details in session to avoid repeated decoding
//     $_SESSION['user_id'] = $decoded->user_id;
//     $_SESSION['name'] = $decoded->name;
//     $_SESSION['email'] = $decoded->email;
//     // $_SESSION['role'] = $decoded->role;
//     $_SESSION['client_id'] = $decoded->client_id;
//     // $allowedPages = $decoded->page; 
//     // print_r($_SESSION['user_id']);

//     $currentPage = basename($_SERVER["SCRIPT_NAME"], ".php");
//     if ($_SESSION['role'] === "admin") {
//         return; // Admin can access everything, so exit the script here
//     }
//     // ########################################################## Decode JWT token



//     ###################################################################
//     $sql = "SELECT t2.page
//         FROM jobaaj_app_watify.users t1
//         INNER JOIN role_based_access t2 ON find_in_set(t2.role, t1.role) or t1.role='admin'
//         where t1.id=?  AND section='navbar'";
//     $stmt = $db->prepare($sql);
//     $stmt->bind_param("i", $_SESSION['user_id']);
//     $stmt->execute();
//     $pagesResult = $stmt->get_result();
//     $allowedPages = [];
//     while ($row = $pagesResult->fetch_assoc()) {
//         $allowedPages[] = $row["page"];
//     }
//     // print_r($allowedPages);
//     // exit();
//     // Restrict access if user is not allowed
//     if (!in_array($currentPage, $allowedPages)) {
//         header("Location: /" . $allowedPages[0] . ".php"); // Redirect to a default allowed page
//         exit();
//     }
//     ###################################################################
// } catch (Exception $e) {
//     // Invalid token: Redirect to login 
//     header("Location: /auth-login.php");
//     exit();
// }

try {
    if (!isset($_SESSION['user_id'])) {  
        // Decode JWT only if session is not already set
        $decoded = JWT::decode($token, new Key($secret_key, 'HS256'));

        // Store user details in session
        $_SESSION['user_id'] = $decoded->user_id;
        $_SESSION['name'] = $decoded->name;
        $_SESSION['email'] = $decoded->email;
        $_SESSION['role'] = $decoded->role;
        $_SESSION['client_id'] = $decoded->client_id;
    }

    // Fetch the latest role from the database
    $sql = "SELECT role FROM users WHERE id = ?";
    $stmt = $db->prepare($sql);
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    $userData = $result->fetch_assoc();

    if (!$userData) {
        // If user doesn't exist, logout
        header("Location: /auth-login.php");
        exit();
    }

    // If role has changed, update session and fetch new allowed pages
    if ($_SESSION['role'] !== $userData['role']) {
        $_SESSION['role'] = $userData['role'];

        // Fetch new allowed pages
        $sql = "SELECT DISTINCT t2.page 
                FROM role_based_access t2 
                WHERE FIND_IN_SET(?, t2.role) OR ? = 'admin' AND section = 'navbar'";

        $stmt = $db->prepare($sql);
        $stmt->bind_param("ss", $_SESSION['role'], $_SESSION['role']);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $_SESSION['allowed_pages'] = [];
        while ($row = $result->fetch_assoc()) {
            $_SESSION['allowed_pages'][] = $row["page"];
        }
    }

    // Access Control
    $currentPage = basename($_SERVER["SCRIPT_NAME"], ".php");

    if ($_SESSION['role'] !== "admin" && !in_array($currentPage, $_SESSION['allowed_pages'])) {
        header("Location: /" . $_SESSION['allowed_pages'][0] . ".php");
        exit();
    }
} catch (Exception $e) {
    // Invalid token: Redirect to login 
    header("Location: /auth-login.php");
    exit();
}