<?php

require_once __DIR__ . '/../db/config.php';

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

function admin_is_logged_in(): bool {
    admin_session_start_if_needed();
    return isset($_SESSION['admin_user_id']) && (int) $_SESSION['admin_user_id'] > 0 && (($_SESSION['user'] ?? null) === 'admin');
}

function admin_require_login(): void {
    if (!admin_is_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function admin_logout(): void {
    admin_session_start_if_needed();
    unset($_SESSION['admin_user_id'], $_SESSION['admin_email'], $_SESSION['admin_name'], $_SESSION['user']);
}

function admin_set_flash(string $message): void {
    admin_session_start_if_needed();
    $_SESSION['message'] = $message;
}

function admin_get_flash(): string {
    admin_session_start_if_needed();
    $message = isset($_SESSION['message']) ? (string) $_SESSION['message'] : '';
    unset($_SESSION['message']);
    return $message;
}

function admin_count_users(): int {
    $stmt = db()->query('SELECT COUNT(*) FROM admin_users');
    return (int) $stmt->fetchColumn();
}

function admin_get_by_email(string $email): ?array {
    $stmt = db()->prepare('SELECT id, email, password_hash, display_name, created_at FROM admin_users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    return $admin ?: null;
}

function admin_create_user(string $email, string $password, string $displayName = 'Admin'): int {
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = db()->prepare('INSERT INTO admin_users (email, password_hash, display_name) VALUES (?, ?, ?)');
    $stmt->execute([$email, $passwordHash, $displayName]);
    return (int) db()->lastInsertId();
}

function admin_login_user(array $admin): void {
    admin_session_start_if_needed();
    $_SESSION['user'] = 'admin';
    $_SESSION['admin_user_id'] = (int) $admin['id'];
    $_SESSION['admin_email'] = (string) $admin['email'];
    $_SESSION['admin_name'] = (string) ($admin['display_name'] ?? 'Admin');
}

function admin_current_name(): string {
    admin_session_start_if_needed();
    return (string) ($_SESSION['admin_name'] ?? 'Admin');
}
