<?php


require_once __DIR__ . '/../common.php';
require_once __DIR__ . '/../includes/auth-center.php';


ac_self_check_or_fail();






function admin_current_user(): ?array
{
    static $cache = null;
    if ($cache !== null) {
        return $cache;
    }

    $uid = current_user_id();
    if (!$uid) {
        $cache = null;
        return null;
    }

    try {
        $stmt = db()->prepare("
            SELECT id, email, nickname, role, status, email_verified
            FROM users
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $uid]);
        $user = $stmt->fetch();
        if (!$user) {
            $cache = null;
            return null;
        }

        if ($user['role'] !== 'admin') {
            $cache = null;
            return null;
        }

        if ($user['status'] !== 'active' || (int)$user['email_verified'] !== 1) {
            $cache = null;
            return null;
        }

        $cache = $user;
        return $user;
    } catch (Throwable $e) {
        $cache = null;
        return null;
    }
}




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




function admin_csrf_token(): string
{
    if (empty($_SESSION['admin_csrf_token']) || !is_string($_SESSION['admin_csrf_token'])) {
        $_SESSION['admin_csrf_token'] = bin2hex(random_bytes(16));
    }
    return $_SESSION['admin_csrf_token'];
}




function admin_csrf_check(?string $token): bool
{
    if (empty($_SESSION['admin_csrf_token']) || !is_string($_SESSION['admin_csrf_token'])) {
        return false;
    }
    if (!is_string($token) || $token === '') {
        return false;
    }
    return hash_equals($_SESSION['admin_csrf_token'], $token);
}






function admin_log(string $action, string $details = '', ?int $userId = null): void
{
    try {
        $pdo = db();

        
        static $inited = false;
        if (!$inited) {
            $pdo->exec("
CREATE TABLE IF NOT EXISTS admin_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    admin_id INTEGER,
    action TEXT NOT NULL,
    details TEXT,
    ip TEXT,
    created_at INTEGER NOT NULL
)
");
            $inited = true;
        }

        if ($userId === null) {
            $admin = admin_current_user();
            if ($admin && isset($admin['id'])) {
                $userId = (int)$admin['id'];
            }
        }

        $ip  = $_SERVER['REMOTE_ADDR'] ?? '';
        $now = time();

        $stmt = $pdo->prepare("
            INSERT INTO admin_logs (admin_id, action, details, ip, created_at)
            VALUES (:admin_id, :action, :details, :ip, :created_at)
        ");
        $stmt->execute([
            ':admin_id'   => $userId,
            ':action'     => $action,
            ':details'    => $details,
            ':ip'         => $ip,
            ':created_at' => $now,
        ]);
    } catch (Throwable $e) {
        
    }
}
