<?php
declare(strict_types=1);

require_once __DIR__ . '/common.php';

function ensure_session_started(): void
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

function create_platform_admin_session(array $admin): void
{
    ensure_session_started();

    $token = bin2hex(random_bytes(32));
    $expiresAt = (new DateTimeImmutable('now +' . SESSION_TTL_SECONDS . ' seconds'))->format('Y-m-d H:i:s');

    $stmt = db()->prepare(
        'INSERT INTO app_sessions (user_type, user_id, family_id, session_token, expires_at) VALUES ("platform_admin", :user_id, NULL, :token, :expires_at)'
    );
    $stmt->execute([
        ':user_id' => $admin['id'],
        ':token' => $token,
        ':expires_at' => $expiresAt,
    ]);

    setcookie(SESSION_COOKIE_NAME, $token, [
        'expires' => strtotime($expiresAt),
        'path' => '/',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    $_SESSION['platform_admin_id'] = (int) $admin['id'];
    $_SESSION['platform_admin_name'] = $admin['full_name'];
}

function current_platform_admin(): ?array
{
    ensure_session_started();

    if (!empty($_SESSION['platform_admin_id'])) {
        return [
            'id' => (int) $_SESSION['platform_admin_id'],
            'full_name' => $_SESSION['platform_admin_name'] ?? 'Admin',
        ];
    }

    $token = $_COOKIE[SESSION_COOKIE_NAME] ?? '';
    if ($token === '') {
        return null;
    }

    $stmt = db()->prepare(
        'SELECT s.user_id, a.full_name
         FROM app_sessions s
         INNER JOIN platform_admins a ON a.id = s.user_id
         WHERE s.session_token = :token
           AND s.user_type = "platform_admin"
           AND s.expires_at > NOW()
           AND a.is_active = 1
         LIMIT 1'
    );
    $stmt->execute([':token' => $token]);
    $row = $stmt->fetch();

    if (!$row) {
        return null;
    }

    $_SESSION['platform_admin_id'] = (int) $row['user_id'];
    $_SESSION['platform_admin_name'] = $row['full_name'];

    db()->prepare('UPDATE app_sessions SET last_seen_at = NOW() WHERE session_token = :token')->execute([':token' => $token]);

    return [
        'id' => (int) $row['user_id'],
        'full_name' => $row['full_name'],
    ];
}

function require_platform_admin(): array
{
    $admin = current_platform_admin();
    if (!$admin) {
        redirect(base_url('admin/index.php'));
    }
    return $admin;
}

function attempt_platform_admin_login(string $username, string $password): bool
{
    $stmt = db()->prepare('SELECT * FROM platform_admins WHERE username = :username AND is_active = 1 LIMIT 1');
    $stmt->execute([':username' => $username]);
    $admin = $stmt->fetch();

    if (!$admin || !password_verify($password, $admin['password_hash'])) {
        return false;
    }

    db()->prepare('UPDATE platform_admins SET last_login_at = NOW() WHERE id = :id')->execute([':id' => $admin['id']]);
    create_platform_admin_session($admin);
    return true;
}

function logout_platform_admin(): void
{
    ensure_session_started();
    $token = $_COOKIE[SESSION_COOKIE_NAME] ?? '';
    if ($token !== '') {
        db()->prepare('DELETE FROM app_sessions WHERE session_token = :token')->execute([':token' => $token]);
    }

    setcookie(SESSION_COOKIE_NAME, '', [
        'expires' => time() - 3600,
        'path' => '/',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    unset($_SESSION['platform_admin_id'], $_SESSION['platform_admin_name']);
}
