<?php
// /htdocs/pages/checkout.php — Secure checkout with method-aware panels
if (!defined('APP_START')) { http_response_code(403); exit('Direct access denied'); }
if (!isLoggedIn()) { redirect('/?page=login'); exit; }

$db     = db();
$user   = getUser();
$userId = (int)($user['id'] ?? $_SESSION['user_id'] ?? 0);

if (!$user || $userId <= 0) {
    setMessage('User not found', 'error');
    redirect('/?page=logout');
}

$slugBooking   = 'booking';
$slugBookings  = 'bookings';
$slugSupport   = 'support';
$slugInsurance = 'insurance';

$__type        = (string)($_GET['type'] ?? 'booking');
$__isInsurance = ($__type === 'insurance');

if ($__isInsurance) {
    redirect('/?page=insurance');
    return;
}

// ============================================
// BOOKING CHECKOUT
// ============================================
$bookingId  = (int)($_GET['booking_id'] ?? 0);
$bookingRef = trim((string)($_GET['ref'] ?? ''));

$booking = null;
try {
    if ($bookingId > 0) {
        $booking = getBooking($bookingId);
    } elseif ($bookingRef !== '') {
        $booking = $db->fetchOne("SELECT * FROM bookings WHERE booking_reference = ?", [$bookingRef]);
        if ($booking) $bookingId = (int)$booking['id'];
    }
} catch (Throwable $e) {}

if (!$booking || (int)($booking['user_id'] ?? 0) !== $userId) {
    echo '<div style="padding:100px 20px;text-align:center;color:white;background:#0f0c29;min-height:100vh;">Booking not found</div>';
    return;
}
$bookingId = (int)$booking['id'];

$property = null;
try {
    if (!empty($booking['property_id'])) {
        $property = function_exists('getPropertyById')
            ? getPropertyById($booking['property_id'])
            : $db->fetchOne("SELECT * FROM properties WHERE id = ?", [(int)$booking['property_id']]);
    }
} catch (Throwable $e) {}

$propTitle = $booking['property_name'] ?? ($property['name'] ?? 'Property');
$propImage = '';
try {
    $media = $db->fetchOne(
        "SELECT file_path FROM property_media WHERE property_id = ? AND is_primary = 1 LIMIT 1",
        [(int)($booking['property_id'] ?? 0)]
    );
    if (!empty($media['file_path'])) {
        $p = (string)$media['file_path'];
        if (strpos($p, 'http') === 0) $propImage = $p;
        elseif (strpos($p, 'properties/') === 0) $propImage = '/uploads/' . $p;
        else $propImage = '/uploads/properties/' . basename($p);
    }
} catch (Throwable $e) {}

$checkInTs   = !empty($booking['check_in'])  ? strtotime($booking['check_in'])  : 0;
$checkOutTs  = !empty($booking['check_out']) ? strtotime($booking['check_out']) : 0;
$nights      = (int)($booking['total_nights'] ?? ($checkInTs && $checkOutTs ? max(0, round(($checkOutTs - $checkInTs) / 86400)) : 0));
$guests      = (int)($booking['guests'] ?? 1);
$rooms       = (int)($booking['rooms'] ?? 1);
$subtotal    = (float)($booking['subtotal'] ?? 0);
$extraCharges= (float)($booking['extra_charges'] ?? 0);
$cleaningFee = (float)($booking['cleaning_fee'] ?? 0);
$serviceFee  = (float)($booking['service_fee'] ?? 0);
$taxAmount   = (float)($booking['tax_amount'] ?? 0);
$totalAmount = (float)($booking['total_amount'] ?? 0);
$reference   = $booking['booking_reference'] ?? '';
$payStatus   = strtolower($booking['payment_status'] ?? 'pending');
$isPaid      = ($payStatus === 'paid');
$currencyCode = $booking['currency'] ?? $booking['base_currency'] ?? ($user['currency'] ?? 'USD');

$taxLines = [];
if (!empty($booking['tax_breakdown'])) {
    $decoded = json_decode((string)$booking['tax_breakdown'], true);
    if (is_array($decoded) && !empty($decoded['taxes']) && is_array($decoded['taxes'])) {
        foreach ($decoded['taxes'] as $t) {
            $amt = (float)($t['amount'] ?? 0);
            if ($amt > 0) $taxLines[] = ['label' => (string)($t['label'] ?? 'Tax'), 'amount' => $amt];
        }
    }
}
if (empty($taxLines) && $taxAmount > 0) $taxLines[] = ['label' => 'Taxes', 'amount' => $taxAmount];

require_once __DIR__ . '/../includes/header.php';
?>

<style>
:root { --grad: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --glass: rgba(255,255,255,0.03); --border: rgba(255,255,255,0.08);
    --text-dim: #a0aec0; --text-hi: #a3bffa; --green: #00b894; --red: #f5576c;
    --orange: #f6ad55; --blue: #00d4ff; --purple: #b794f4; }
.co-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.co-page .container { max-width: 1400px; margin: 0 auto; padding: 0 20px; }
.co-head { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 16px; margin-bottom: 22px; }
.co-head-left { flex: 1; min-width: 240px; }
.co-breadcrumb { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 11px; color: var(--text-dim); margin-bottom: 8px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; }
.co-breadcrumb a { color: var(--text-hi); text-decoration: none; }
.co-head h1 { font-size: 28px; font-weight: 800; margin-bottom: 4px; display: flex; align-items: center; gap: 10px; }
.co-head h1 .grad { background: var(--grad); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.co-head .sub { color: var(--text-dim); font-size: 13px; }
.btn-sb { padding: 10px 18px; border-radius: 10px; font-weight: 700; font-size: 12px; cursor: pointer; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; font-family: inherit; }
.btn-sb-outline { background: rgba(255,255,255,0.05); color: #cbd5e0; border: 1px solid var(--border); }
.btn-sb-block { width: 100%; justify-content: center; }
.btn-sb-primary { background: var(--grad); color: white; }
.co-security-bar { padding: 12px 20px; background: linear-gradient(135deg, rgba(0,184,148,0.1), rgba(0,212,255,0.05)); border: 1px solid rgba(0,184,148,0.3); border-radius: 14px; display: flex; align-items: center; gap: 12px; margin-bottom: 22px; font-size: 12px; color: #81e6d9; }
.co-security-bar i { font-size: 16px; color: var(--green); }
.co-layout { display: grid; grid-template-columns: 1fr 400px; gap: 24px; align-items: flex-start; }
@media (max-width: 1000px) { .co-layout { grid-template-columns: 1fr; } .co-summary { order: -1; } }
.co-card { background: var(--glass); border: 1px solid var(--border); border-radius: 16px; padding: 22px; margin-bottom: 20px; }
.co-card h2 { font-size: 15px; font-weight: 800; margin-bottom: 18px; display: flex; align-items: center; gap: 8px; }
.co-card h2 .badge { font-size: 10px; font-weight: 800; padding: 3px 10px; border-radius: 50px; background: rgba(102,126,234,0.15); color: var(--text-hi); text-transform: uppercase; letter-spacing: 0.05em; margin-left: auto; }
.co-prop { display: flex; gap: 14px; align-items: center; padding: 14px; background: rgba(0,0,0,0.15); border: 1px solid var(--border); border-radius: 12px; }
.co-prop-img { width: 72px; height: 72px; border-radius: 10px; background: var(--grad); background-size: cover; background-position: center; display: flex; align-items: center; justify-content: center; font-size: 26px; color: rgba(255,255,255,0.5); flex-shrink: 0; }
.co-prop-body h3 { font-size: 15px; font-weight: 800; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.co-prop-body .meta { font-size: 11px; color: var(--text-dim); display: flex; gap: 12px; flex-wrap: wrap; margin-top: 4px; }
.co-methods { display: grid; gap: 10px; margin-bottom: 20px; }
.co-method { padding: 16px 18px; background: rgba(0,0,0,0.15); border: 2px solid var(--border); border-radius: 12px; cursor: pointer; display: grid; grid-template-columns: 40px 1fr auto; gap: 14px; align-items: center; font-family: inherit; color: inherit; text-align: left; width: 100%; }
.co-method:hover { border-color: rgba(102,126,234,0.4); }
.co-method.selected { border-color: #667eea; background: linear-gradient(135deg, rgba(102,126,234,0.1), rgba(118,75,162,0.05)); box-shadow: 0 0 0 3px rgba(102,126,234,0.15); }
.co-method-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 18px; flex-shrink: 0; }
.co-method-icon.rampex { background: linear-gradient(135deg, rgba(240,147,251,0.15), rgba(245,87,108,0.15)); color: var(--orange); }
.co-method-icon.paypal { background: rgba(0,48,135,0.2); color: #4a90e2; }
.co-method-icon.mobile { background: rgba(0,184,148,0.15); color: var(--green); }
.co-method-icon.bank   { background: rgba(183,148,244,0.15); color: var(--purple); }
.co-method-icon.hotel  { background: rgba(246,173,85,0.15); color: var(--orange); }
.co-method-info .label { font-size: 14px; font-weight: 800; margin-bottom: 3px; }
.co-method-info .desc { font-size: 11px; color: var(--text-dim); line-height: 1.5; }
.co-method-check { width: 22px; height: 22px; border-radius: 50%; border: 2px solid var(--border); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.co-method.selected .co-method-check { border-color: #667eea; background: var(--grad); }
.co-method.selected .co-method-check::after { content: '✓'; color: white; font-weight: 900; font-size: 12px; }

.co-panel {
    display: none;
    padding: 20px;
    margin-bottom: 20px;
    background: linear-gradient(135deg, rgba(102,126,234,0.06), rgba(118,75,162,0.04));
    border: 1px solid rgba(102,126,234,0.28);
    border-radius: 12px;
}
.co-panel.active { display: block; }
.co-panel h4 { font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-hi); margin: 0 0 14px; display: flex; align-items: center; gap: 8px; }
.co-panel p.co-lead { font-size: 13px; color: #cbd5e0; line-height: 1.65; margin: 0 0 14px; }

.co-field { margin-bottom: 14px; }
.co-field:last-child { margin-bottom: 0; }
.co-field label { display: block; font-size: 11px; font-weight: 800; color: var(--text-hi); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 6px; }
.co-field label .req { color: var(--red); }
.co-field label .hint { color: var(--text-dim); font-weight: 400; text-transform: none; margin-left: 6px; }
.co-field input, .co-field select { width: 100%; padding: 11px 14px; background: rgba(255,255,255,0.05); border: 1px solid var(--border); border-radius: 10px; color: white; font-size: 13px; font-family: inherit; outline: none; box-sizing: border-box; }
.co-field select option { background: #1a1a2e; color: white; }
.co-field input:focus, .co-field select:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.2); }
.co-help { font-size: 11.5px; color: var(--text-dim); margin-top: 6px; line-height: 1.55; }

.co-bank-box { background: rgba(0,0,0,0.25); border: 1px solid var(--border); border-radius: 10px; padding: 14px; margin-bottom: 14px; }
.co-bank-row { display: flex; justify-content: space-between; padding: 7px 0; font-size: 12.5px; border-bottom: 1px solid rgba(255,255,255,0.05); }
.co-bank-row:last-child { border-bottom: none; }
.co-bank-row .l { color: var(--text-dim); }
.co-bank-row .v { font-family: 'SF Mono', Monaco, monospace; font-weight: 700; }
.co-bank-row .v.hl { color: var(--orange); }

.co-row { display: flex; justify-content: space-between; padding: 10px 0; font-size: 13px; border-bottom: 1px solid rgba(255,255,255,0.04); }
.co-row:last-child { border-bottom: none; }
.co-row .value { font-family: 'SF Mono', Monaco, monospace; font-weight: 700; }
.co-row.total { padding-top: 16px; border-top: 2px solid rgba(102,126,234,0.3); font-size: 17px; font-weight: 800; }
.co-row.total .value { font-size: 22px; color: var(--text-hi); }
.co-pay-btn { width: 100%; padding: 16px; background: var(--grad); color: white; border: none; border-radius: 12px; font-weight: 900; font-size: 15px; cursor: pointer; font-family: inherit; display: inline-flex; align-items: center; justify-content: center; gap: 8px; letter-spacing: 0.02em; box-shadow: 0 10px 30px rgba(102,126,234,0.3); }
.co-pay-btn:hover:not(:disabled) { transform: translateY(-2px); }
.co-pay-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.co-pay-note { text-align: center; color: var(--text-dim); font-size: 11px; margin-top: 12px; }
.co-trust { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 18px; padding-top: 18px; border-top: 1px solid rgba(255,255,255,0.05); }
.co-trust-item { text-align: center; }
.co-trust-item i { font-size: 18px; color: var(--text-hi); display: block; margin-bottom: 6px; }
.co-trust-item .v { font-size: 12px; font-weight: 800; }
.co-trust-item .l { font-size: 9px; color: var(--text-dim); text-transform: uppercase; font-weight: 800; }
.co-paid { padding: 20px 24px; background: linear-gradient(135deg, rgba(0,184,148,0.12), rgba(0,212,255,0.06)); border: 1px solid rgba(0,184,148,0.4); border-radius: 16px; display: flex; gap: 14px; align-items: center; margin-bottom: 20px; }
.co-paid i { font-size: 28px; color: var(--green); }
.co-paid h3 { font-size: 16px; font-weight: 800; margin-bottom: 4px; }
.co-paid p { font-size: 12px; color: #cbd5e0; line-height: 1.6; }
</style>

<div class="co-page">
    <div class="container">

        <div class="co-head">
            <div class="co-head-left">
                <div class="co-breadcrumb">
                    <a href="/?page=<?php echo htmlspecialchars($slugBookings); ?>">My Bookings</a>
                    <i class="fas fa-chevron-right"></i><span style="color: white;">Secure Checkout</span>
                </div>
                <h1>🔒 <span class="grad">Secure Checkout</span></h1>
                <p class="sub">Complete your booking safely</p>
            </div>
            <a href="/?page=<?php echo htmlspecialchars($slugBooking); ?>&id=<?php echo (int)$bookingId; ?>" class="btn-sb btn-sb-outline">
                <i class="fas fa-arrow-left"></i> Back to Booking
            </a>
        </div>

        <div class="co-security-bar">
            <i class="fas fa-shield-alt"></i>
            <div><strong>256-bit SSL encryption</strong> · Your payment details are never stored on our servers.</div>
        </div>

        <?php if ($isPaid): ?>
            <div class="co-paid">
                <i class="fas fa-check-circle"></i>
                <div>
                    <h3>This booking is already paid</h3>
                    <p>Reference: <strong style="font-family: monospace; color: white;"><?php echo htmlspecialchars($reference); ?></strong></p>
                </div>
            </div>
        <?php endif; ?>

        <div class="co-layout">

            <main>
                <div class="co-card">
                    <h2><i class="fas fa-hotel" style="color: var(--purple);"></i> Booking Summary
                        <?php if ($reference): ?><span class="badge">#<?php echo htmlspecialchars($reference); ?></span><?php endif; ?>
                    </h2>
                    <div class="co-prop">
                        <div class="co-prop-img" style="<?php echo $propImage ? 'background-image: url(' . htmlspecialchars($propImage, ENT_QUOTES) . ');' : ''; ?>">
                            <?php if (!$propImage): ?><i class="fas fa-hotel"></i><?php endif; ?>
                        </div>
                        <div class="co-prop-body">
                            <h3><?php echo htmlspecialchars($propTitle); ?></h3>
                            <div class="meta">
                                <?php if ($checkInTs && $checkOutTs): ?>
                                    <span><i class="fas fa-calendar"></i> <?php echo date('M j', $checkInTs); ?> → <?php echo date('M j, Y', $checkOutTs); ?></span>
                                <?php endif; ?>
                                <?php if ($nights > 0): ?>
                                    <span><i class="fas fa-moon"></i> <?php echo $nights; ?> night<?php echo $nights === 1 ? '' : 's'; ?></span>
                                <?php endif; ?>
                                <?php if ($guests > 0): ?>
                                    <span><i class="fas fa-users"></i> <?php echo $guests; ?> guest<?php echo $guests === 1 ? '' : 's'; ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!$isPaid): ?>
                <div class="co-card">
                    <h2><i class="fas fa-credit-card" style="color: var(--blue);"></i> Payment Method</h2>

                    <div class="co-methods" id="coMethodList">

                        <button type="button" class="co-method selected" data-method="card" onclick="coSelectMethod(this)">
                            <div class="co-method-icon rampex"><i class="fas fa-bolt"></i></div>
                            <div class="co-method-info">
                                <div class="label">Credit / Debit Card · Crypto</div>
                                <div class="desc">Visa · Mastercard · Amex · Bitcoin · USDC — secured by Rampex</div>
                            </div>
                            <div class="co-method-check"></div>
                        </button>

                        <button type="button" class="co-method" data-method="paypal" onclick="coSelectMethod(this)">
                            <div class="co-method-icon paypal"><i class="fab fa-paypal"></i></div>
                            <div class="co-method-info">
                                <div class="label">PayPal</div>
                                <div class="desc">Pay with your PayPal balance or linked card</div>
                            </div>
                            <div class="co-method-check"></div>
                        </button>

                        <button type="button" class="co-method" data-method="mobile_money" onclick="coSelectMethod(this)">
                            <div class="co-method-icon mobile"><i class="fas fa-mobile-alt"></i></div>
                            <div class="co-method-info">
                                <div class="label">Mobile Money</div>
                                <div class="desc">M-Pesa · Airtel Money · Tigo Pesa</div>
                            </div>
                            <div class="co-method-check"></div>
                        </button>

                        <button type="button" class="co-method" data-method="bank_transfer" onclick="coSelectMethod(this)">
                            <div class="co-method-icon bank"><i class="fas fa-university"></i></div>
                            <div class="co-method-info">
                                <div class="label">Bank Transfer</div>
                                <div class="desc">Transfer to our account — upload proof for verification</div>
                            </div>
                            <div class="co-method-check"></div>
                        </button>

                    </div>

                    <div class="co-panel active" id="coPanel-card">
                        <h4><i class="fas fa-bolt"></i> Card &amp; Crypto Payment via Rampex</h4>
                        <p class="co-lead">
                            Clicking <strong>Pay</strong> will redirect you to a secure Rampex payment page
                            where you can complete the payment with <strong>Visa, Mastercard, Amex, Bitcoin
                            or USDC (Polygon)</strong>. No card details are entered on Revenda.
                        </p>
                        <div class="co-help" style="padding: 12px; background: rgba(0,0,0,0.2); border-radius: 8px;">
                            <i class="fas fa-lock"></i>
                            You'll be redirected to <strong>rampex.io</strong> to pay securely.
                        </div>
                    </div>

                    <div class="co-panel" id="coPanel-paypal">
                        <h4><i class="fab fa-paypal"></i> PayPal Payment</h4>
                        <div class="co-field">
                            <label>PayPal email <span class="req">*</span></label>
                            <input type="email" name="paypal_email" id="coPaypalEmail" placeholder="you@example.com" autocomplete="email">
                            <div class="co-help">We'll redirect you to PayPal to log in and approve the payment.</div>
                        </div>
                    </div>

                    <div class="co-panel" id="coPanel-mobile_money">
                        <h4><i class="fas fa-mobile-alt"></i> Mobile Money</h4>
                        <div class="co-field">
                            <label>Provider <span class="req">*</span></label>
                            <select name="mobile_provider" id="coMobileProvider">
                                <option value="">— Select provider —</option>
                                <option value="mpesa">M-Pesa (Vodacom)</option>
                                <option value="airtel">Airtel Money</option>
                                <option value="tigo">Tigo Pesa</option>
                                <option value="halopesa">HaloPesa</option>
                            </select>
                        </div>
                        <div class="co-field">
                            <label>Phone number <span class="req">*</span></label>
                            <input type="tel" name="mobile_phone" id="coMobilePhone" placeholder="+255 7XX XXX XXX" autocomplete="tel">
                            <div class="co-help">You'll receive a payment prompt on this number. Approve it to complete payment.</div>
                        </div>
                    </div>

                    <div class="co-panel" id="coPanel-bank_transfer">
                        <h4><i class="fas fa-university"></i> Bank Transfer</h4>
                        <p class="co-lead">Transfer the total to the account below, then upload proof. Your booking is confirmed after our team verifies it (usually within 24 hours).</p>

                        <div class="co-bank-box">
                            <div class="co-bank-row"><span class="l">Beneficiary</span><span class="v">Revenda Ltd.</span></div>
                            <div class="co-bank-row"><span class="l">Bank</span><span class="v">CRDB Bank Tanzania</span></div>
                            <div class="co-bank-row"><span class="l">Account number</span><span class="v">0150-XXXX-XXXX</span></div>
                            <div class="co-bank-row"><span class="l">SWIFT / BIC</span><span class="v">CORUTZTZ</span></div>
                            <div class="co-bank-row"><span class="l">Amount</span><span class="v"><?php echo formatCurrency($totalAmount, $currencyCode); ?></span></div>
                            <div class="co-bank-row"><span class="l">Reference</span><span class="v hl"><?php echo htmlspecialchars($reference); ?></span></div>
                        </div>

                        <div class="co-field">
                            <label>Your transfer reference <span class="hint">(optional)</span></label>
                            <input type="text" name="bank_transfer_reference" id="coBankRef" maxlength="64" placeholder="Bank txn ID or short note">
                        </div>
                        <div class="co-field">
                            <label>Upload proof of payment <span class="hint">(PDF or image, max 8MB)</span></label>
                            <input type="file" name="bank_transfer_proof" id="coBankProof" accept="image/*,application/pdf">
                        </div>
                    </div>

                </div>
                <?php endif; ?>

                <?php if (!$isPaid): ?>
                    <button type="button" class="co-pay-btn" id="coPayBtn" onclick="coProcessPayment()">
                        <i class="fas fa-lock"></i>
                        <span id="coPayLabel">Continue to Rampex — Pay <?php echo formatCurrency($totalAmount, $currencyCode); ?></span>
                    </button>
                    <p class="co-pay-note">By clicking "Pay", you agree to our <a href="/?page=terms" style="color: var(--text-hi);">Terms</a></p>
                <?php else: ?>
                    <a href="/?page=<?php echo htmlspecialchars($slugBooking); ?>&id=<?php echo (int)$bookingId; ?>"
                       class="btn-sb btn-sb-primary btn-sb-block" style="padding: 16px;">
                        <i class="fas fa-check"></i> View Booking Details
                    </a>
                <?php endif; ?>

            </main>

            <aside class="co-summary">
                <div class="co-card">
                    <h2><i class="fas fa-receipt" style="color: var(--green);"></i> Price Breakdown</h2>
                    <?php if ($subtotal > 0): ?>
                        <div class="co-row"><span>Accommodation</span><span class="value"><?php echo formatCurrency($subtotal, $currencyCode); ?></span></div>
                    <?php endif; ?>
                    <?php if ($extraCharges > 0): ?>
                        <div class="co-row"><span>Extra guests</span><span class="value"><?php echo formatCurrency($extraCharges, $currencyCode); ?></span></div>
                    <?php endif; ?>
                    <?php if ($cleaningFee > 0): ?>
                        <div class="co-row"><span>Cleaning Fee</span><span class="value"><?php echo formatCurrency($cleaningFee, $currencyCode); ?></span></div>
                    <?php endif; ?>
                    <?php if ($serviceFee > 0): ?>
                        <div class="co-row"><span>Service Fee</span><span class="value"><?php echo formatCurrency($serviceFee, $currencyCode); ?></span></div>
                    <?php endif; ?>
                    <?php foreach ($taxLines as $tl): ?>
                        <div class="co-row"><span><?php echo htmlspecialchars($tl['label']); ?></span><span class="value"><?php echo formatCurrency($tl['amount'], $currencyCode); ?></span></div>
                    <?php endforeach; ?>
                    <div class="co-row total"><span>Total</span><span class="value"><?php echo formatCurrency($totalAmount, $currencyCode); ?></span></div>

                    <div class="co-trust">
                        <div class="co-trust-item"><i class="fas fa-shield-alt"></i><div class="v">Secure</div><div class="l">Payment</div></div>
                        <div class="co-trust-item"><i class="fas fa-undo"></i><div class="v">Available</div><div class="l">Cancellation</div></div>
                        <div class="co-trust-item"><i class="fas fa-headset"></i><div class="v">24/7</div><div class="l">Support</div></div>
                    </div>
                </div>

                <div class="co-card">
                    <h2><i class="fas fa-life-ring" style="color: var(--orange);"></i> Need Help?</h2>
                    <p style="font-size: 12px; color: var(--text-dim); line-height: 1.7; margin-bottom: 14px;">
                        Having trouble completing your payment? Our support team is available 24/7.
                    </p>
                    <a href="/?page=<?php echo htmlspecialchars($slugSupport); ?>" class="btn-sb btn-sb-outline btn-sb-block">
                        <i class="fas fa-comment"></i> Contact Support
                    </a>
                </div>
            </aside>

        </div>

    </div>
</div>

<script>
var CO = {
    bookingId: <?php echo (int)$bookingId; ?>,
    amount:    <?php echo (float)$totalAmount; ?>,
    currency:  <?php echo json_encode((string)$currencyCode); ?>,
    method:    'card',
    busy:      false
};

function coSelectMethod(el) {
    document.querySelectorAll('#coMethodList .co-method').forEach(function(m) {
        m.classList.remove('selected');
    });
    el.classList.add('selected');

    var m = el.dataset.method || 'card';
    CO.method = m;

    document.querySelectorAll('.co-panel').forEach(function(p) {
        p.classList.remove('active');
    });
    var panel = document.getElementById('coPanel-' + m);
    if (panel) panel.classList.add('active');

    var labels = {
        card:          'Continue to Rampex — Pay <?php echo addslashes(formatCurrency($totalAmount, $currencyCode)); ?>',
        paypal:        'Pay with PayPal — <?php echo addslashes(formatCurrency($totalAmount, $currencyCode)); ?>',
        mobile_money:  'Pay with Mobile Money — <?php echo addslashes(formatCurrency($totalAmount, $currencyCode)); ?>',
        bank_transfer: 'Submit Bank Transfer Proof'
    };
    var lbl = document.getElementById('coPayLabel');
    if (lbl) lbl.textContent = labels[m] || labels.card;
}

function coToast(msg, type) {
    var t = document.createElement('div');
    t.style.cssText = 'position:fixed;top:24px;right:24px;z-index:99999;padding:14px 20px;border-radius:12px;' +
        'font-size:13px;font-weight:700;font-family:inherit;color:#fff;max-width:380px;line-height:1.5;' +
        'box-shadow:0 12px 40px rgba(0,0,0,0.4);';
    t.style.background = (type === 'error')
        ? 'linear-gradient(135deg,#f5576c,#c53030)'
        : 'linear-gradient(135deg,#00b894,#00cec9)';
    t.textContent = msg;
    document.body.appendChild(t);
    setTimeout(function () { t.style.opacity = '0'; t.style.transition = 'opacity .3s'; }, 4000);
    setTimeout(function () { t.remove(); }, 4500);
}

function coSetBusy(busy) {
    CO.busy = busy;
    var btn = document.getElementById('coPayBtn');
    if (!btn) return;
    if (busy) {
        btn.disabled = true;
        btn.dataset.orig = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing…';
    } else {
        btn.disabled = false;
        if (btn.dataset.orig) btn.innerHTML = btn.dataset.orig;
    }
}

function coProcessPayment() {
    if (CO.busy) return;

    if (CO.method === 'bank_transfer') {
        return coSubmitBankTransfer();
    }

    var payload = {
        action:     'create',
        booking_id: CO.bookingId,
        method:     CO.method
    };

    if (CO.method === 'mobile_money') {
        var prov  = document.getElementById('coMobileProvider');
        var phone = document.getElementById('coMobilePhone');
        if (!prov || !prov.value)  { coToast('Please choose a mobile money provider', 'error'); return; }
        if (!phone || !phone.value.trim()) { coToast('Please enter your phone number', 'error'); return; }
        payload.mobile_provider = prov.value;
        payload.mobile_phone    = phone.value.trim();
    }

    if (CO.method === 'paypal') {
        var em = document.getElementById('coPaypalEmail');
        if (!em || !em.value.trim() || em.value.indexOf('@') < 0) {
            coToast('Please enter a valid PayPal email', 'error');
            return;
        }
        payload.customer_email = em.value.trim();
    }

    coSetBusy(true);
    console.log('[checkout] POST to api-payment:', payload);

    fetch('/?page=api-payment', {
        method:      'POST',
        headers:     { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body:        JSON.stringify(payload)
    })
    .then(function (r) {
        console.log('[checkout] HTTP', r.status);
        return r.text();
    })
    .then(function (raw) {
        console.log('[checkout] response body:', raw);
        var res;
        try { res = JSON.parse(raw); } catch (e) { res = null; }

        if (res && res.success && (res.redirect || res.payment_url)) {
            coToast('Redirecting to secure payment…');
            window.location.href = res.redirect || res.payment_url;
            return;
        }
        coSetBusy(false);
        coToast((res && res.message) ? res.message : 'Payment initiation failed', 'error');
    })
    .catch(function (err) {
        coSetBusy(false);
        coToast('Network error — please try again', 'error');
        console.error('[checkout] fetch error', err);
    });
}

function coSubmitBankTransfer() {
    var refInput   = document.getElementById('coBankRef');
    var proofInput = document.getElementById('coBankProof');
    var ref      = refInput ? refInput.value.trim() : '';
    var hasProof = proofInput && proofInput.files && proofInput.files.length > 0;

    if (ref === '' && !hasProof) {
        coToast('Please add a transfer reference or upload proof of payment', 'error');
        return;
    }

    coSetBusy(true);
    var fd = new FormData();
    fd.append('action', 'bank_transfer_submit');
    fd.append('booking_id', CO.bookingId);
    if (ref) fd.append('bank_transfer_reference', ref);
    if (hasProof) fd.append('bank_transfer_proof', proofInput.files[0]);

    fetch('/?page=api-payment', {
        method: 'POST', credentials: 'same-origin', body: fd
    })
    .then(function (r) { return r.text(); })
    .then(function (raw) {
        console.log('[checkout] bank transfer response:', raw);
        var res; try { res = JSON.parse(raw); } catch (e) { res = null; }
        coSetBusy(false);
        if (res && res.success) {
            coToast('Proof received — we\'ll verify within 24 hours');
            setTimeout(function () {
                window.location.href = '/?page=booking&id=' + CO.bookingId;
            }, 1200);
        } else {
            coToast((res && res.message) ? res.message : 'Could not submit transfer details', 'error');
        }
    })
    .catch(function (err) {
        coSetBusy(false);
        coToast('Network error — please try again', 'error');
        console.error(err);
    });
}

(function () {
    var params = new URLSearchParams(window.location.search);
    if (params.get('rampex_return') === '1') {
        coToast('Payment received — verifying with Rampex…');
        var tries = 0;
        var timer = setInterval(function () {
            tries++;
            fetch('/?page=api-payment', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'same-origin',
                body: JSON.stringify({ action: 'status', booking_id: CO.bookingId })
            })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                if (res && res.payment_status === 'paid') {
                    clearInterval(timer);
                    coToast('Payment confirmed 🎉');
                    setTimeout(function () {
                        window.location.href = '/?page=booking&id=' + CO.bookingId;
                    }, 900);
                } else if (tries >= 15) {
                    clearInterval(timer);
                    coToast('Still verifying — check your booking shortly');
                }
            })
            .catch(function () {});
        }, 2000);
    }
})();
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>