<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../core/Response.php';

session_name(SESSION_NAME);
session_start();

/**
 * 1. Authentication
 */
if (empty($_SESSION['employee_id'])) {
    Response::error('Unauthorized', 401);
}

/**
 * 2. Session expiry
 */
if (
    empty($_SESSION['expires_at']) ||
    time() > $_SESSION['expires_at']
) {
    session_unset();
    session_destroy();

    Response::error('Session expired', 401);
}

/**
 * 3. User-Agent validation
 */
if (
    empty($_SESSION['user_agent']) ||
    $_SESSION['user_agent'] !== ($_SERVER['HTTP_USER_AGENT'] ?? '')
) {
    session_unset();
    session_destroy();

    Response::error('Session integrity violation', 401);
}

/**
 * 4. IP validation
 */
$currentIp = $_SERVER['REMOTE_ADDR'] ?? '';

if (
    empty($_SESSION['ip_address']) ||
    $_SESSION['ip_address'] !== $currentIp
) {
    session_unset();
    session_destroy();

    Response::error('Session IP mismatch', 401);
}

/**
 * 5. Role authorization
 * Usage:
 * define('REQUIRED_ROLE', 'super_admin');
 */
if (
    defined('REQUIRED_ROLE') &&
    ($_SESSION['role'] ?? '') !== REQUIRED_ROLE
) {
    Response::error('Forbidden', 403);
}
