<?php
// check_guest.php
header('Content-Type: application/json');
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

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

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

try {
    $stmt = $pdo->prepare("SELECT id, name, riddle_question FROM guests WHERE qr_code = ?");
    $stmt->execute([$qrCode]);
    $guest = $stmt->fetch();

    if ($guest) {
        echo json_encode([
            'status' => 'success',
            'message' => 'QR Code Valid',
            'guest_id' => $guest['id'],
            'guest_name' => $guest['name'],
            'riddle_question' => $guest['riddle_question']
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'INVALID CODE - SECURITY ALERT']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'System error']);
}
?>