<?php
require_once __DIR__ . '/../includes/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') json_error('Método no permitido.', 405);

$body = body_json();
$email = trim($body['email'] ?? '');
$password = (string) ($body['password'] ?? '');

if ($email === '' || $password === '') json_error('Correo y contraseña son requeridos.', 422);

$stmt = $pdo->prepare('SELECT id, email, password_hash FROM admin_users WHERE email = ? LIMIT 1');
$stmt->execute([$email]);
$admin = $stmt->fetch();

if (!$admin || !password_verify($password, $admin['password_hash'])) {
    json_error('Credenciales inválidas.', 401);
}

$token = jwt_encode(['sub' => $admin['id'], 'email' => $admin['email']], $config['jwt_secret']);

json_ok([
    'token' => $token,
    'user' => ['id' => $admin['id'], 'email' => $admin['email']],
]);
