<?php
declare(strict_types=1);

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

session_name(SESSION_NAME);
session_start();

/**
 * 1. Authentication check
 */
if (empty($_SESSION['employee_id'])) {
    header('Location: ' . ADMIN_BASE_URL . 'index.php');
    exit;
}

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

    header('Location: ' . ADMIN_BASE_URL . 'index.php');
    exit;
}

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

    header('Location: ' . ADMIN_BASE_URL . 'index.php');
    exit;
}

/**
 * 4. IP binding (soft check)
 */
$currentIp = $_SERVER['REMOTE_ADDR'] ?? '';

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

    header('Location: ' . ADMIN_BASE_URL . 'index.php');
    exit;
}

/**
 * 5. Optional role restriction
 * Usage:
 * define('REQUIRED_ROLE', 'admin');
 */
if (
    defined('REQUIRED_ROLE') &&
    ($_SESSION['role'] ?? '') !== REQUIRED_ROLE
) {
    header('Location: ' . ADMIN_BASE_URL . 'unauthorized.php');
    exit;
}
