<?php
namespace Core;

class Session {
    public static function start(): void {
        if (session_status() === PHP_SESSION_NONE) {
            ini_set('session.cookie_httponly', 1);
            ini_set('session.use_strict_mode', 1);
            ini_set('session.cookie_samesite', 'Lax');
            session_name('EDUSMART_SESS');
            session_set_cookie_params([
                'lifetime' => 0,
                'path'     => '/cbe/sms/public',
                'httponly' => true,
                'samesite' => 'Lax',
            ]);
            session_start();
        }
    }

    // ── Inactivity timeout (15 minutes) ──────────────────
    private const TIMEOUT = 900; // 15 minutes in seconds

    public static function checkInactivity(): bool {
        if (!isset($_SESSION['user'])) return false;
        $last = $_SESSION['_last_activity'] ?? time();
        if ((time() - $last) > self::TIMEOUT) {
            session_destroy();
            return true; // timed out
        }
        $_SESSION['_last_activity'] = time();
        return false;
    }

    public static function touchActivity(): void {
        $_SESSION['_last_activity'] = time();
    }

    public static function secondsUntilTimeout(): int {
        $last = $_SESSION['_last_activity'] ?? time();
        $elapsed = time() - $last;
        return max(0, self::TIMEOUT - $elapsed);
    }

    public static function set(string $key, mixed $val): void { $_SESSION[$key] = $val; }
    public static function get(string $key, mixed $default = null): mixed { return $_SESSION[$key] ?? $default; }
    public static function has(string $key): bool { return isset($_SESSION[$key]); }
    public static function remove(string $key): void { unset($_SESSION[$key]); }
    public static function destroy(): void { session_destroy(); }
    public static function regenerate(): void { session_regenerate_id(true); }

    public static function flash(string $key, mixed $val): void { $_SESSION['_flash'][$key] = $val; }
    public static function getFlash(string $key, mixed $default = null): mixed {
        $val = $_SESSION['_flash'][$key] ?? $default;
        unset($_SESSION['_flash'][$key]);
        return $val;
    }

    public static function peekFlash(string $key, mixed $default = null): mixed {
        return $_SESSION['_flash'][$key] ?? $default;
    }

    public static function csrf(): string {
        if (!isset($_SESSION['_csrf'])) {
            $_SESSION['_csrf'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['_csrf'];
    }

    public static function verifyCsrf(): bool {
        $token = $_POST['_csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
        return hash_equals($_SESSION['_csrf'] ?? '', $token);
    }
}
