<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();

$cid = (int)($_GET['cid'] ?? 0);
if ($cid <= 0) redirect('/dashboard/campaigns');

$pageTitle = 'Checkout';
$activeNav = 'campaigns';
$extraCss  = ['campaigns'];
$showSearch = false;
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<div class="page-header">
    <div class="page-header-left">
        <h4>Checkout</h4>
        <p>Review your order and complete payment to publish your campaign</p>
    </div>
</div>

<div class="content-wrapper">
    <div id="checkoutRoot">
        <div class="text-center py-5 text-muted">
            <div class="spinner-border me-2"></div> Loading checkout…
        </div>
    </div>
</div>

<style>
.checkout-grid {
    display: grid;
    grid-template-columns: 1fr 380px;
    gap: 20px;
}
@media (max-width: 992px) { .checkout-grid { grid-template-columns: 1fr; } }

.summary-card {
    background: white;
    border-radius: 18px;
    padding: 22px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    margin-bottom: 16px;
}
.os-package-label {
    background: linear-gradient(135deg,#1B7A43,#2D9B5A);
    color: white;
    padding: 12px 18px;
    border-radius: 12px;
    font-weight: 700;
    display: inline-flex; align-items: center; gap: 8px;
    margin-bottom: 12px;
}
.os-package-price { font-size: 32px; font-weight: 800; color: var(--primary); margin-bottom: 8px; }
.os-divider { border-top: 1px dashed var(--card-border); margin: 14px 0; }
.os-line-item { display: flex; justify-content: space-between; font-size: 14px; padding: 4px 0; color: var(--text-secondary); }
.os-line-item span:last-child { font-weight: 600; color: var(--text-primary); }
.os-total { display: flex; justify-content: space-between; font-size: 18px; font-weight: 800; color: var(--primary); padding-top: 4px; }

.payment-method-card {
    display: flex; align-items: center; gap: 12px;
    padding: 14px; border-radius: 14px;
    border: 2px solid var(--card-border);
    margin-bottom: 10px; cursor: pointer;
    transition: all 0.15s ease;
    background: white;
}
.payment-method-card:hover { border-color: var(--primary); }
.payment-method-card.selected { border-color: var(--primary); background: var(--bg-light-green); }
.payment-radio { accent-color: var(--primary); }
.payment-icon { font-size: 22px; }
.payment-name { font-weight: 600; font-size: 14px; flex: 1; }
.payment-desc { font-size: 11px; color: var(--text-muted); }

.terms-checkbox-group {
    display: flex; align-items: flex-start; gap: 10px;
    margin-bottom: 10px; font-size: 13px; color: var(--text-secondary);
}
.terms-checkbox-group input { margin-top: 3px; flex-shrink: 0; accent-color: var(--primary); }
.terms-checkbox-group a { color: var(--primary); text-decoration: none; font-weight: 600; }

.user-info-row { display: flex; gap: 12px; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--card-border); }
.user-info-row:last-child { border-bottom: none; }
.user-info-row .lbl { font-size: 12px; color: var(--text-muted); width: 100px; flex-shrink: 0; }
.user-info-row .val { font-size: 14px; font-weight: 600; }
</style>

<script>
(async function () {
    const cid = <?= $cid ?>;
    const root = document.getElementById('checkoutRoot');

    function escapeHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c =>
            ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    let selectedGateway = null;

    try {
        const resp = await window.api('/api/campaign/checkout-summary?cid=' + cid);
        if (resp.status !== 'success') {
            if (resp.data && resp.data.redirect) {
                window.location.href = resp.data.redirect;
                return;
            }
            throw new Error(resp.message);
        }
        const c = resp.data.campaign;
        const p = resp.data.pricing;
        const u = resp.data.publisher;
        const gateways = resp.data.gateways;

        const initial = c.app_title ? c.app_title.charAt(0).toUpperCase() : '?';
        const iconHtml = c.app_logo
            ? `<img src="${escapeHtml(c.app_logo)}" alt="" style="width:64px;height:64px;border-radius:14px;object-fit:cover">`
            : `<div style="width:64px;height:64px;border-radius:14px;background:linear-gradient(135deg,#1B7A43,#2D9B5A);color:white;display:flex;align-items:center;justify-content:center;font-size:26px;font-weight:800">${initial}</div>`;

        const gatewaysHtml = gateways.length
            ? gateways.map((g, i) => `
                <div class="payment-method-card ${i === 0 ? 'selected' : ''}" data-gw="${escapeHtml(g.key)}">
                    <input type="radio" name="payment" class="payment-radio" ${i === 0 ? 'checked' : ''}>
                    <div class="payment-icon">${g.icon}</div>
                    <div style="flex:1">
                        <div class="payment-name">${escapeHtml(g.label)}</div>
                        <div class="payment-desc">${escapeHtml(g.desc)}</div>
                    </div>
                    <i class="bi bi-check-circle-fill" style="color:var(--primary);opacity:0;transition:opacity 0.15s" data-check></i>
                </div>`).join('')
            : `<div class="text-center text-muted" style="padding:20px;font-size:13px">
                    <i class="bi bi-exclamation-circle"></i> No payment methods available for ${escapeHtml(p.currency)}.
                    Please contact support.
               </div>`;

        if (gateways.length) selectedGateway = gateways[0].key;

        root.innerHTML = `
            <div class="checkout-grid">
                <!-- Left -->
                <div>
                    <!-- Campaign summary -->
                    <div class="summary-card">
                        <div style="display:flex;gap:14px;align-items:center;margin-bottom:14px">
                            ${iconHtml}
                            <div>
                                <div style="font-weight:700;font-size:18px">${escapeHtml(c.app_title)}</div>
                                <div style="font-size:13px;color:var(--text-secondary)">${escapeHtml(c.app_developer)}</div>
                                <div style="font-size:12px;color:var(--text-muted);margin-top:2px"><code>${escapeHtml(c.app_pkg)}</code></div>
                            </div>
                            <a href="/dashboard/campaigns/add" style="margin-left:auto;color:var(--primary);font-size:13px;text-decoration:none">
                                <i class="bi bi-pencil"></i> Edit
                            </a>
                        </div>
                        <div style="font-size:13px;color:var(--text-secondary);line-height:1.7">
                            <strong>Plan:</strong> ${escapeHtml(c.plan_name)} ·
                            <strong>${c.total_users} testers</strong> ·
                            ${c.plan_testing_days} days ·
                            ${c.per_user_coins} coins per tester
                        </div>
                    </div>

                    <!-- User info -->
                    <div class="summary-card">
                        <div class="card-header-title" style="margin-bottom:14px">Billing Information</div>
                        <div class="user-info-row">
                            <div class="lbl">Name</div><div class="val">${escapeHtml(u.name)}</div>
                        </div>
                        <div class="user-info-row">
                            <div class="lbl">Email</div><div class="val">${escapeHtml(u.email)}</div>
                        </div>
                        <div class="user-info-row">
                            <div class="lbl">Phone</div><div class="val">${escapeHtml(u.phone || '—')}</div>
                        </div>
                        <div class="user-info-row">
                            <div class="lbl">Country</div><div class="val">${escapeHtml(u.country)}</div>
                        </div>
                    </div>

                    <!-- T&C -->
                    <div class="summary-card">
                        <div class="terms-checkbox-group">
                            <input type="checkbox" id="termsCheck1">
                            <label for="termsCheck1">
                                I agree to DroidTester's <a href="/terms-condition" target="_blank">Terms of Use</a>
                                and <a href="/privacy-policy" target="_blank">Privacy Policy</a>.
                            </label>
                        </div>
                        <div class="terms-checkbox-group">
                            <input type="checkbox" id="termsCheck2">
                            <label for="termsCheck2">
                                I accept the Refund Policy and understand that the campaign goes for admin review after payment.
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Right — Order Summary -->
                <div>
                    <div class="summary-card">
                        <div class="os-package-label">
                            <i class="bi bi-star-fill" style="color:#FFD700"></i> ${escapeHtml(c.plan_name).toUpperCase()}
                        </div>
                        <div class="os-package-price">${p.currency_symbol}${p.subtotal.toFixed(2)}</div>
                        <hr class="os-divider">
                        <div class="os-line-item"><span>Subtotal</span><span>${p.currency_symbol}${p.subtotal.toFixed(2)}</span></div>
                        ${p.gst_amount > 0 ? `<div class="os-line-item"><span>${escapeHtml(p.gst_label)}</span><span>${p.currency_symbol}${p.gst_amount.toFixed(2)}</span></div>` : ''}
                        <div class="os-line-item"><span>Platform Fee</span><span>${p.currency_symbol}${p.platform_fee.toFixed(2)}</span></div>
                        <hr class="os-divider">
                        <div class="os-total"><span>Total</span><span>${p.currency_symbol}${p.total.toFixed(2)}</span></div>
                    </div>

                    <div class="summary-card">
                        <div class="card-header-title" style="margin-bottom:12px;font-size:14px">Payment Method</div>
                        ${gatewaysHtml}
                    </div>

                    <button class="btn-primary-custom w-100" id="payBtn" disabled
                            style="padding:14px;font-size:15px;justify-content:center;border-radius:30px;opacity:0.5;cursor:not-allowed">
                        <i class="bi bi-lock-fill"></i> Pay ${p.currency_symbol}${p.total.toFixed(2)}
                    </button>

                    <p style="font-size:11px;color:var(--text-muted);text-align:center;margin-top:10px;line-height:1.6">
                        <i class="bi bi-shield-check"></i> Secure checkout · 256-bit SSL · No card details stored
                    </p>
                </div>
            </div>
        `;

        // ── Wire up ──
        const cb1 = document.getElementById('termsCheck1');
        const cb2 = document.getElementById('termsCheck2');
        const payBtn = document.getElementById('payBtn');

        function updatePayBtn() {
            const ready = cb1.checked && cb2.checked && selectedGateway && gateways.length > 0;
            payBtn.disabled = !ready;
            payBtn.style.opacity = ready ? '1' : '0.5';
            payBtn.style.cursor = ready ? 'pointer' : 'not-allowed';
        }
        cb1.addEventListener('change', updatePayBtn);
        cb2.addEventListener('change', updatePayBtn);

        // Gateway selection
        document.querySelectorAll('.payment-method-card').forEach(card => {
            card.addEventListener('click', function () {
                document.querySelectorAll('.payment-method-card').forEach(c => {
                    c.classList.remove('selected');
                    const r = c.querySelector('.payment-radio');
                    if (r) r.checked = false;
                });
                this.classList.add('selected');
                const r = this.querySelector('.payment-radio');
                if (r) r.checked = true;
                selectedGateway = this.dataset.gw;
                updatePayBtn();
            });
        });

        payBtn.addEventListener('click', async function () {
            // Phase 5 will replace this with the real /api/payment/initiate flow.
            window.Toast.fire({
                icon: 'info',
                title: 'Payment integration arrives in Phase 5 (Cashfree first).',
                timer: 4000
            });
        });

    } catch (err) {
        root.innerHTML = `
            <div class="text-center py-5">
                <div style="font-size:48px">⚠️</div>
                <p class="text-muted mt-2">Could not load checkout. ${escapeHtml(err.message || '')}</p>
                <a href="/dashboard/campaigns/add" class="btn-primary-custom" style="display:inline-flex;margin-top:12px">
                    <i class="bi bi-arrow-left"></i> Back
                </a>
            </div>`;
    }
})();
</script>

<?php require __DIR__ . '/../includes/partials/dashboard-foot.php'; ?>
