<?php
/**
 * session.php — Shared "require an authenticated admin session" logic.
 *
 * Used by both includes/auth.php (form-submission handlers that may need
 * to redirect before any HTML output) and includes/header.php (page
 * layout). Both previously duplicated this exact block; consolidated
 * here so there is one place that defines what "logged in" means for
 * this single-admin panel.
 *
 * Requires $db and $sessionTimeout to already be set (functions.php sets
 * both before including this file's caller).
 */

/**
 * Redirects to index.php and exits unless the current session belongs to
 * the panel's one admin user. Also handles ?logout and session timeout,
 * since both are part of "is this session still valid" rather than
 * separate concerns.
 */
function require_login(): void {
    global $db, $sessionTimeout;

    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $admin = get_admin_user($db);
    $loggedInUsername = $admin['username'] ?? null;

    if (!isset($_SESSION['name']) || $_SESSION['name'] !== $loggedInUsername) {
        header('Location: index.php');
        exit;
    }

    if (isset($_REQUEST['logout'])) {
        session_destroy();
        setcookie(session_name(), '', time() - 3600, '/');
        header('Location: index.php');
        exit;
    }

    $timeoutDuration = $sessionTimeout ?? 900;
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeoutDuration) {
        session_unset();
        session_destroy();
        header('Location: index.php');
        exit;
    }
    $_SESSION['LAST_ACTIVITY'] = $_SERVER['REQUEST_TIME'];
}

/**
 * Returns the panel's single admin user row, or null if it doesn't exist
 * yet (shouldn't normally happen — functions.php seeds it on first run).
 * Centralizes the "id = 1, there is only ever one admin" assumption
 * instead of repeating `$db->select('user', '*', 'id = :id', '', [':id' => 1])`
 * at every call site.
 */
function get_admin_user(object $db): ?array {
    $rows = $db->select('user', '*', 'id = :id', '', [':id' => 1]);
    return $rows[0] ?? null;
}
