<?php
// ============================================================
// FILE LOCATION: C:\xampp\htdocs\NRMS\include\auth_guard.php
// ============================================================

require_once __DIR__ . '/PermissionManager.php';
require_once __DIR__ . '/db_connection.php';

// Detect AJAX request
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
$is_api_call = (strpos($_SERVER['REQUEST_URI'], '/api/') !== false) || 
               (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] === 'application/json');

// ── 1. Start session if not already started ───────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ── 2. Must be logged in ──────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'], $_SESSION['usertype'])) {
    if ($is_ajax || $is_api_call) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Session expired. Please login again.']);
        exit();
    }
    header('Location: /login');
    exit();
}

// ── 3. Always rebuild permissions fresh from DB ───────────────────────────────
try {
    $_auth_perm_manager = new PermissionManager($conn);
    $_auth_perms = $_auth_perm_manager->getUserPermissions((int)$_SESSION['user_id']);
    $_SESSION['permissions'] = array_column($_auth_perms, 'name');
    unset($_auth_perm_manager, $_auth_perms);
} catch (Exception $e) {
    if ($is_ajax || $is_api_call) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Permission check failed: ' . $e->getMessage()]);
        exit();
    }
    error_log("Permission initialization error: " . $e->getMessage());
}

// ── Helper functions ──────────────────────────────────────────────────────────

function requirePermission(string $permission, string $redirect = '/app/403'): void
{
    if (!PermissionManager::sessionCan($permission)) {
        error_log("Access denied — user #{$_SESSION['user_id']} missing permission: $permission");
        
        // Check if this is an AJAX request
        $is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
                   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
        
        if ($is_ajax) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Permission denied: ' . $permission]);
            exit();
        }
        
        header('Location: ' . $redirect);
        exit();
    }
}

function requireAnyPermission(array $permissions, string $redirect = '/app/403'): void
{
    if (!PermissionManager::sessionCanAny($permissions)) {
        error_log("Access denied — user #{$_SESSION['user_id']} missing all of: " . implode(', ', $permissions));
        
        $is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
                   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
        
        if ($is_ajax) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Permission denied']);
            exit();
        }
        
        header('Location: ' . $redirect);
        exit();
    }
}

function requireUsertype(array $allowedTypes, string $redirect = '/app/403'): void
{
    if (!in_array($_SESSION['usertype'] ?? '', $allowedTypes, true)) {
        error_log("Access denied — usertype '{$_SESSION['usertype']}' not in allowed list");
        
        $is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
                   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
        
        if ($is_ajax) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Access denied: Invalid user type']);
            exit();
        }
        
        header('Location: ' . $redirect);
        exit();
    }
}
?>