<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

function eaq_session_admin(): ?array {
  return $_SESSION['admin'] ?? null;
}

function eaq_require_admin(array $cfg): void {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  $admin = eaq_session_admin();
  if (!$admin || !($admin['is_admin'] ?? false)) {
    $base = $cfg['base_url'] ?? '';
    eaq_redirect($base . '/app/login.php');
  }
}

function eaq_current_user(array $cfg): ?array {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  $admin = eaq_session_admin();
  if (!$admin) return null;
  return $admin;
}

function eaq_verify_admin_login(array $cfg, string $username, string $password): bool {
  $username = trim($username);
  if ($username === '') return false;

  $mode = eaq_db_mode($cfg);
  if ($mode === 'mysql') {
    $pdo = eaq_pdo($cfg);
    if (!$pdo) return false;
    $stmt = $pdo->prepare('SELECT id, username, password_hash FROM admin_users WHERE username = ? LIMIT 1');
    $stmt->execute([$username]);
    $row = $stmt->fetch();
    if (!$row) return false;
    return password_verify($password, $row['password_hash'] ?? '');
  }

  // mock mode: guarda admin em storage/admin_mock.json
  $adminMock = eaq_read_json('admin_mock.json', []);
  $stored = $adminMock[$username] ?? null;
  if (!$stored || empty($stored['password_hash'])) return false;
  return password_verify($password, $stored['password_hash']);
}

function eaq_set_admin_session(array $cfg, string $username): void {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  $_SESSION['admin'] = [
    'username' => $username,
    'is_admin' => true,
  ];
}

