<?php
declare(strict_types=1);

function start_admin_session(): void
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

function is_admin_logged_in(): bool
{
    start_admin_session();
    return !empty($_SESSION['admin_id']);
}

function require_admin_login(bool $jsonResponse = false): void
{
    if (is_admin_logged_in()) {
        return;
    }

    if ($jsonResponse) {
        http_response_code(401);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Sesi login tidak valid. Silakan login ulang.',
        ]);
    } else {
        header('Location: login.php');
    }

    exit;
}

function current_admin_name(): string
{
    start_admin_session();
    return (string)($_SESSION['admin_name'] ?? $_SESSION['admin_username'] ?? 'Admin');
}

function ensure_admin_table(PDO $pdo): void
{
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS admins (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(50) NOT NULL UNIQUE,
            password_hash VARCHAR(255) NOT NULL,
            nama VARCHAR(100) NOT NULL DEFAULT 'Administrator',
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");

    $count = (int)$pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();
    if ($count === 0) {
        $stmt = $pdo->prepare("INSERT INTO admins (username, password_hash, nama) VALUES (?, ?, ?)");
        $stmt->execute([
            'admin',
            password_hash('admin123', PASSWORD_DEFAULT),
            'Administrator',
        ]);
    }
}
