<?php
// Hostiva V6 - Guest Portal Data Controller
// Accessed via: /api/?r=guest&hash=<magic_hash>
// No session auth required — uses hash-based access tied to booking reference
try {
    $db = db();

    // Accept hash from GET or POST body
    $hash = trim($_GET['hash'] ?? '');
    if (!$hash) {
        json_error('Missing guest access hash. Please use the link provided by your host.', 400);
    }

    // Look up booking by reference hash (guest_hash column) OR booking reference
    $stmt = $db->prepare("
        SELECT
            b.id, b.reference, b.guest_name, b.guest_email, b.guest_phone,
            b.check_in, b.check_out, b.adults, b.children, b.guests_count,
            b.status, b.notes, b.guest_hash,
            p.name AS property_name,
            p.address AS property_address,
            p.city,
            p.wifi_network,
            p.wifi_password,
            p.google_review_url,
            p.airbnb_url,
            p.booking_url,
            p.whatsapp_number
        FROM bookings b
        JOIN properties p ON b.property_id = p.id
        WHERE b.guest_hash = ?
          AND b.status IN ('confirmed', 'checked_in')
        LIMIT 1
    ");
    $stmt->execute([$hash]);
    $booking = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$booking) {
        json_error('No active reservation found for this link. Please contact your host.', 404);
    }

    json_ok($booking);

} catch (\PDOException $e) {
    json_error('DATABASE ERROR: ' . $e->getMessage(), 500);
} catch (\Throwable $e) {
    json_error('ERROR: ' . $e->getMessage(), 500);
}
