<?php

require_once __DIR__ . '/config.php';

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

function auth_bootstrap(): void
{
    static $auth_bootstrap_done = false;

    if ($auth_bootstrap_done) {
        return;
    }

    $pdo = db();
    $pdo->exec(
        "CREATE TABLE IF NOT EXISTS tbl_auth (
            cl_auth_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            cl_auth_user VARCHAR(190) NOT NULL UNIQUE,
            cl_auth_pass VARCHAR(255) NOT NULL,
            cl_auth_right ENUM('admin', 'member') NOT NULL DEFAULT 'member'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );

    $sql_count_admin = "SELECT COUNT(*) FROM tbl_auth WHERE cl_auth_right = 'admin'";
    $stmt_count_admin = $pdo->query($sql_count_admin);
    $cl_auth_admin_total = (int) $stmt_count_admin->fetchColumn();

    if ($cl_auth_admin_total === 0) {
        [$cl_auth_user, $plain_default_password] = auth_default_admin_credentials();
        $cl_auth_pass = password_hash($plain_default_password, PASSWORD_DEFAULT);
        $cl_auth_right = 'admin';

        $stmt_insert_admin = $pdo->prepare(
            'INSERT INTO tbl_auth (cl_auth_user, cl_auth_pass, cl_auth_right) VALUES (:cl_auth_user, :cl_auth_pass, :cl_auth_right)'
        );
        $stmt_insert_admin->execute([
            'cl_auth_user' => $cl_auth_user,
            'cl_auth_pass' => $cl_auth_pass,
            'cl_auth_right' => $cl_auth_right,
        ]);
    }

    $auth_bootstrap_done = true;
}

function auth_default_admin_credentials(): array
{
    return ['admin', 'ReactAdmin!2026'];
}

function auth_csrf_token(): string
{
    auth_start_session();

    if (empty($_SESSION['csrf_token']) || !is_string($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['csrf_token'];
}

function auth_validate_csrf(?string $csrf_token): bool
{
    auth_start_session();

    if (!isset($_SESSION['csrf_token']) || !is_string($_SESSION['csrf_token'])) {
        return false;
    }

    if ($csrf_token === null) {
        return false;
    }

    return hash_equals($_SESSION['csrf_token'], $csrf_token);
}

function auth_is_logged_in(): bool
{
    auth_start_session();

    return isset($_SESSION['user']) && isset($_SESSION['role']);
}

function auth_is_admin(): bool
{
    auth_start_session();

    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function auth_flash_set(string $flash_type, string $flash_message): void
{
    auth_start_session();
    $_SESSION['flash'] = [
        'type' => $flash_type,
        'message' => $flash_message,
    ];
}

function auth_flash_get(): ?array
{
    auth_start_session();

    if (!isset($_SESSION['flash']) || !is_array($_SESSION['flash'])) {
        return null;
    }

    $flash = $_SESSION['flash'];
    unset($_SESSION['flash']);

    return $flash;
}