<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../src/mysql.php';

use function App\get_mysql_db;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Metodo no permitido']);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw ?: '[]', true);
if (!is_array($body)) {
    $body = [];
}

$token = trim((string)($body['token'] ?? $_POST['token'] ?? ''));
$consume = (int)($body['consume'] ?? $_POST['consume'] ?? 1);
$consume = max(1, $consume);

if ($token === '') {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'token requerido']);
    exit;
}

$pdo = get_mysql_db();

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare('SELECT id, event_id, full_name, pass_count, check_in_count FROM guests WHERE qr_token = ? FOR UPDATE');
    $stmt->execute([$token]);
    $guest = $stmt->fetch();

    if (!$guest) {
        $pdo->rollBack();
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'QR invalido']);
        exit;
    }

    $available = (int)$guest['pass_count'] - (int)$guest['check_in_count'];
    if ($available < $consume) {
        $pdo->rollBack();
        http_response_code(409);
        echo json_encode([
            'ok' => false,
            'error' => 'Pases insuficientes',
            'remaining' => max(0, $available),
        ]);
        exit;
    }

    $upd = $pdo->prepare('UPDATE guests SET check_in_count = check_in_count + ?, check_in_time = IF(check_in_time IS NULL, NOW(), check_in_time) WHERE id = ?');
    $upd->execute([$consume, $guest['id']]);

    $log = $pdo->prepare('INSERT INTO event_logs(event_id, guest_id, log_type, meta, ip, user_agent) VALUES (?, ?, ?, JSON_OBJECT("consume", ?), ?, ?)');
    $log->execute([
        $guest['event_id'],
        $guest['id'],
        'checkin',
        $consume,
        $_SERVER['REMOTE_ADDR'] ?? null,
        substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255),
    ]);

    $pdo->commit();

    echo json_encode([
        'ok' => true,
        'guest' => [
            'id' => (int)$guest['id'],
            'name' => $guest['full_name'],
        ],
        'consumed' => $consume,
        'remaining' => $available - $consume,
    ]);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Error interno']);
}
