<?php 
require_once 'includes/header.php'; 

$booking_ref = trim($_GET['booking_ref'] ?? '');
$booking_type = trim($_GET['type'] ?? 'tour'); // Get booking type from URL

if (empty($booking_ref)) { die("Error: No booking reference provided."); }

// Dynamically select from the correct booking table
$table_map = ['tour' => 'bookings', 'hotel' => 'hotel_bookings', 'flight' => 'flight_bookings', 'ferry' => 'ferry_bookings'];
$table_name = $table_map[$booking_type] ?? 'bookings';

$stmt = $conn->prepare("SELECT * FROM `$table_name` WHERE booking_ref = ?");
$stmt->bind_param("s", booking_ref);
$stmt->execute();
$booking = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$booking) { die("Error: Booking not found."); }

// Get title for display (requires different joins)
$booking_title = 'Your Booking';
if ($booking_type === 'tour') {
    $stmt_title = $conn->prepare("SELECT title FROM tours WHERE id = ?");
    $stmt_title->bind_param("i", $booking['tour_id']);
    $stmt_title->execute();
    $booking_title = $stmt_title->get_result()->fetch_assoc()['title'];
} // Add similar logic for hotel, flight, ferry titles if needed

$page_title = 'Booking Confirmation: ' . htmlspecialchars($booking_ref);
$paypal_client_id = $site_settings['paypal_client_id'] ?? '';
$paypal_currency = $site_settings['paypal_currency'] ?? 'PHP';
?>

<div class="container my-5"><div class="row justify-content-center"><div class="col-lg-8">
    <div class="card shadow-sm border-0 text-center mb-4"><div class="card-body p-4"><i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i><h2 class="mt-3">Thank You! Your Booking is Reserved.</h2><p class="lead text-muted">Please complete your payment to finalize your trip.</p></div></div>
    <div class="card shadow-sm border-0">
        <div class="card-header bg-light border-0 pt-3"><h5 class="mb-0">Booking Summary</h5></div>
        <div class="card-body"><ul class="list-group list-group-flush"><li class="list-group-item d-flex justify-content-between"><span>Reference:</span><strong class="text-primary"><?php echo htmlspecialchars($booking['booking_ref']); ?></strong></li><li class="list-group-item d-flex justify-content-between"><span>Item:</span><strong><?php echo htmlspecialchars($booking_title); ?></strong></li><li class="list-group-item d-flex justify-content-between fs-4"><span>Total Due:</span><strong class="text-primary"><?php echo format_price($booking['total_price']); ?></strong></li></ul></div>
        <div class="card-header bg-light border-0 border-top pt-3"><h5 class="mb-0">Payment Options</h5></div>
        <div class="card-body">
            <?php if ($booking['payment_status'] === 'Paid'): ?>
                <div class="alert alert-success text-center">This booking has been fully paid. Thank you!</div>
            <?php else: ?>
                <div class="accordion" id="paymentAccordion">
                    <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#online-panel">Pay with PayPal</button></h2><div id="online-panel" class="accordion-collapse collapse show" data-bs-parent="#paymentAccordion"><div class="accordion-body text-center"><p>Click the button below to pay securely with PayPal.</p><div id="paypal-button-container"></div></div></div></div>
                    <div class="accordion-item"><h2 class="accordion-header"><button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#manual-panel">Manual Bank Transfer</button></h2><div id="manual-panel" class="accordion-collapse collapse" data-bs-parent="#paymentAccordion"><div class="accordion-body"><p>Please transfer the total amount to the account below and upload a screenshot of your receipt.</p><p><strong>Bank:</strong> BDO Unibank<br><strong>Account Name:</strong> DXP Travel & Tours<br><strong>Account No:</strong> 0012 3456 7890</p><hr><form action="upload-proof.php" method="POST" enctype="multipart/form-data"><input type="hidden" name="booking_ref" value="<?php echo $booking['booking_ref']; ?>"><div class="mb-3"><label for="receipt" class="form-label">Upload Receipt</label><input class="form-control" type="file" id="receipt" name="receipt" required></div><button type="submit" class="btn btn-primary">Submit Proof of Payment</button></form></div></div></div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div></div></div>

<script src="https://www.paypal.com/sdk/js?client-id=<?php echo htmlspecialchars($paypal_client_id); ?>&currency=<?php echo htmlspecialchars($paypal_currency); ?>"></script>
<script>
    paypal.Buttons({
        createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '<?php echo $booking["total_price"]; ?>' }, custom_id: '<?php echo $booking["booking_ref"]; ?>' }] }); },
        onApprove: function(data, actions) {
            return actions.order.capture().then(function(details) {
                fetch('/api/paypal-capture-order.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ orderID: data.orderID, booking_ref: '<?php echo $booking["booking_ref"]; ?>', booking_type: '<?php echo $booking_type; ?>' })
                })
                .then(response => response.json())
                .then(data => { if (data.status === 'success') { window.location.href = 'payment-success.php?ref=' + data.booking_ref; } else { alert('An error occurred. Please contact support.'); } });
            });
        }
    }).render('#paypal-button-container');
</script>

<?php 
require_once 'includes/footer.php'; 
?>
