<?php
// get_guest_admin.php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');

try {
    require 'db.php';

    $input = json_decode(file_get_contents('php://input'), true);
    $qrCode = $input['qr_code'] ?? '';

    if (empty($qrCode)) {
        echo json_encode(['status' => 'error', 'message' => 'brak kodu QR']);
        exit;
    }

    // Attempt selection, if columns are missing it will throw Exception caught below
    $stmt = $pdo->prepare("SELECT id, name, points, vodka_ml, whisky_ml, liqueur_ml FROM guests WHERE qr_code = ?");
    $stmt->execute([$qrCode]);
    $guest = $stmt->fetch();

    if ($guest) {
        echo json_encode([
            'status' => 'success',
            'guest_id' => $guest['id'],
            'guest_name' => $guest['name'],
            'points' => (int) $guest['points'],
            'alcohol' => [
                'vodka' => (int) ($guest['vodka_ml'] ?? 0),
                'whisky' => (int) ($guest['whisky_ml'] ?? 0),
                'liqueur' => (int) ($guest['liqueur_ml'] ?? 0)
            ]
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Nieznany gość']);
    }
} catch (Exception $e) {
    // If we catch an error, it might be due to missing columns. 
    // We return a specific message suggesting the update.
    echo json_encode([
        'status' => 'error',
        'message' => 'Błąd bazy danych. Czy uruchomiono browser_update_db.php?',
        'debug' => $e->getMessage()
    ]);
}
?>