{% extends "core/base.html" %}
{% load static %}
{% load currency_filters %}

{% block title %}Checkout — {{ plan.name }} — SwiftPOS{% endblock %}
{% block topbar_title %}Checkout{% endblock %}

{% block extra_css %}
<style>
.checkout-wrap { max-width: 820px; margin: 0 auto; }
.checkout-card {
    background: #fff; border-radius: 18px;
    border: 1px solid #e2e8f0; padding: 2rem;
    box-shadow: 0 4px 20px rgba(0,0,0,0.05);
}
.checkout-title { font-size: 1.3rem; font-weight: 800; color: #0f172a; margin-bottom: 1.5rem; }
.billing-option {
    display: flex; align-items: center; justify-content: space-between;
    border: 2px solid #e2e8f0;
    border-radius: 12px; padding: 1rem 1.25rem;
    margin-bottom: 0.75rem; cursor: pointer;
    transition: all 0.2s; user-select: none;
}
.billing-option:hover { border-color: #7c3aed; background: #faf5ff; }
.billing-option.selected { border-color: #7c3aed; background: #faf5ff; }
.billing-option input { margin-right: 0.75rem; accent-color: #7c3aed; width: 18px; height: 18px; }
.billing-label { font-size: 0.9rem; font-weight: 600; color: #0f172a; }
.billing-sub { font-size: 0.78rem; color: #64748b; }
.billing-price { font-size: 1rem; font-weight: 800; color: #7c3aed; }

.promo-group { display: flex; gap: 0.5rem; margin-top: 1.5rem; }
.promo-input {
    flex: 1; padding: 0.7rem 1rem; border: 1.5px solid #e2e8f0;
    border-radius: 10px; font-size: 0.9rem; font-family: inherit;
    text-transform: uppercase; letter-spacing: 0.05em;
    transition: border-color 0.2s;
}
.promo-input:focus { outline: none; border-color: #7c3aed; box-shadow: 0 0 0 3px rgba(124,58,237,0.1); }
.btn-promo {
    padding: 0.7rem 1.25rem; border-radius: 10px; border: none;
    background: #0f172a; color: #fff; font-size: 0.85rem; font-weight: 600;
    cursor: pointer; font-family: inherit; transition: background 0.2s;
    white-space: nowrap;
}
.btn-promo:hover { background: #1e293b; }

.order-summary {
    background: #f8fafc; border-radius: 14px;
    padding: 1.25rem 1.5rem; margin-top: 1.5rem;
}
.summary-row { display: flex; justify-content: space-between; font-size: 0.88rem; margin-bottom: 0.5rem; }
.summary-divider { border: none; border-top: 1px solid #e2e8f0; margin: 0.75rem 0; }
.summary-total { font-size: 1.1rem; font-weight: 800; color: #0f172a; }
.summary-discount { color: #10b981; }
.promo-result { margin-top: 0.5rem; font-size: 0.83rem; border-radius: 8px; padding: 0.5rem 0.75rem; }
.promo-success { background: #d1fae5; color: #065f46; }
.promo-error { background: #fee2e2; color: #991b1b; }

.btn-pay {
    display: flex; align-items: center; justify-content: center; gap: 0.6rem;
    width: 100%; padding: 1rem;
    background: linear-gradient(135deg, #059669, #10b981);
    color: #fff; border: none; border-radius: 14px;
    font-size: 1rem; font-weight: 800; font-family: inherit;
    cursor: pointer; margin-top: 1.5rem;
    transition: opacity 0.2s, transform 0.15s;
}
.btn-pay:hover { opacity: 0.92; transform: translateY(-1px); }
.btn-pay:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }

.action-badge { display: inline-flex; align-items: center; gap: 0.4rem;
    padding: 0.3rem 0.8rem; border-radius: 20px;
    font-size: 0.75rem; font-weight: 700; margin-bottom: 1rem; }
.badge-upgrade { background: #dbeafe; color: #1e40af; }
.badge-downgrade { background: #fef3c7; color: #92400e; }
.badge-renew { background: #d1fae5; color: #065f46; }
.badge-new { background: #ede9fe; color: #5b21b6; }

.secure-note { text-align: center; font-size: 0.76rem; color: #94a3b8; margin-top: 0.75rem; }

/* Gateway badge */
.gateway-badge {
    display: inline-flex; align-items: center; gap: 0.4rem;
    padding: 0.25rem 0.7rem; border-radius: 20px;
    font-size: 0.72rem; font-weight: 700; margin-left: 0.5rem;
    vertical-align: middle;
}
.badge-monnify { background: #dbeafe; color: #1d4ed8; }
.badge-paystack { background: #d1fae5; color: #065f46; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid py-3">
<div class="checkout-wrap">

    <div class="d-flex align-items-center gap-2 mb-3">
        <a href="{% url 'subscriptions:choose_plan' %}" class="btn btn-sm btn-outline-secondary rounded-pill">
            <i class="fas fa-arrow-left"></i> Back
        </a>
        <h1 class="fw-bold fs-5 mb-0">
            Checkout
            {% if gateway == 'paystack' %}
            <span class="gateway-badge badge-paystack"><i class="fas fa-credit-card"></i> Paystack</span>
            {% else %}
            <span class="gateway-badge badge-monnify"><i class="fas fa-university"></i> Monnify</span>
            {% endif %}
        </h1>
    </div>

    <!-- Action Badge -->
    {% if action == 'upgrade' %}
    <div class="action-badge badge-upgrade"><i class="fas fa-arrow-up"></i> Upgrading to {{ plan.name }}</div>
    {% elif action == 'downgrade' %}
    <div class="action-badge badge-downgrade"><i class="fas fa-arrow-down"></i> Downgrading to {{ plan.name }}</div>
    {% elif action == 'renew' %}
    <div class="action-badge badge-renew"><i class="fas fa-redo"></i> Renewing {{ plan.name }}</div>
    {% else %}
    <div class="action-badge badge-new"><i class="fas fa-bolt"></i> New subscription — {{ plan.name }}</div>
    {% endif %}

    {% if action == 'downgrade' %}
    <!-- DOWNGRADE: no payment needed -->
    <div class="checkout-card">
        <h2 class="checkout-title"><i class="fas fa-info-circle text-warning me-2"></i>Downgrade Notice</h2>
        <p style="font-size:.9rem;color:#64748b;line-height:1.7;">
            Downgrading to <strong>{{ plan.name }}</strong> will take effect when your <strong>{{ current_sub.plan.name }}</strong>
            subscription expires on <strong>{{ current_sub.expiry_date|date:"d M Y" }}</strong>.
        </p>
        <p style="font-size:.9rem;color:#64748b;line-height:1.7;margin-top:.75rem;">
            No payment is required for downgrades. Your current plan remains active until that date.
        </p>
        <form method="post">
            {% csrf_token %}
            <input type="hidden" name="billing_cycle" value="{{ current_sub.billing_cycle }}">
            <button type="submit" class="btn-pay" style="background: linear-gradient(135deg, #f59e0b, #d97706);">
                <i class="fas fa-calendar-check"></i> Schedule Downgrade to {{ plan.name }}
            </button>
        </form>
    </div>

    {% else %}
    <!-- UPGRADE / RENEW / NEW: payment required -->
    <form method="post" id="checkoutForm">
        {% csrf_token %}
        <div class="checkout-card">
            <h2 class="checkout-title">1. Choose Billing Cycle</h2>

            {% for opt in billing_options %}
            <label class="billing-option {% if forloop.first %}selected{% endif %}" id="opt-{{ opt.key }}">
                <div style="display:flex;align-items:center;gap:.75rem;">
                    <input type="radio" name="billing_cycle" value="{{ opt.key }}"
                           {% if forloop.first %}checked{% endif %}
                           data-price="{{ opt.price }}"
                           data-label="{{ opt.label }}"
                           onchange="updateSummary()">
                    <div>
                        <div class="billing-label">{{ opt.label }}</div>
                        <div class="billing-sub">{{ opt.key|title }} billing</div>
                    </div>
                </div>
                <div class="billing-price">₦{{ opt.price|currency:0 }}</div>
            </label>
            {% endfor %}
        </div>

        <div class="checkout-card mt-3">
            <h2 class="checkout-title">2. Have a Promo Code? (Optional)</h2>
            <div class="promo-group">
                <input type="text" class="promo-input" id="promoInput" placeholder="Enter promo code" autocomplete="off" style="text-transform:uppercase;">
                <button type="button" class="btn-promo" onclick="applyPromo()">Apply</button>
            </div>
            <input type="hidden" name="promo_code" id="promoCodeHidden" value="">
            <div id="promoResult"></div>
        </div>

        <div class="checkout-card mt-3">
            <h2 class="checkout-title">3. Order Summary</h2>
            <div class="order-summary">
                <div class="summary-row">
                    <span>Plan</span>
                    <span><strong>{{ plan.name }}</strong></span>
                </div>
                <div class="summary-row">
                    <span>Billing Cycle</span>
                    <span id="summCycle">Monthly</span>
                </div>
                <div class="summary-row">
                    <span>Subtotal</span>
                    <span>₦<span id="summBase">{{ billing_options.0.price|currency:0 }}</span></span>
                </div>
                <div class="summary-row summary-discount" id="discountRow" style="display:none;">
                    <span>Discount (promo)</span>
                    <span>-₦<span id="summDiscount">0</span></span>
                </div>
                <hr class="summary-divider">
                <div class="summary-row summary-total">
                    <span>Total Due</span>
                    <span>₦<span id="summTotal">{{ billing_options.0.price|currency:0 }}</span></span>
                </div>
            </div>

            <button type="submit" class="btn-pay" id="payBtn">
                {% if gateway == 'paystack' %}
                <i class="fas fa-lock"></i> Pay Securely via Paystack
                {% elif gateway == 'manual' %}
                <i class="fas fa-university"></i> Show Bank Details
                {% else %}
                <i class="fas fa-lock"></i> Pay Securely via Monnify
                {% endif %}
            </button>
            <p class="secure-note">
                {% if gateway == 'paystack' %}
                <i class="fas fa-shield-alt"></i> Secured by Paystack — Card, Bank Transfer & USSD accepted.
                {% elif gateway == 'manual' %}
                <i class="fas fa-info-circle"></i> You will be shown our bank details to make a manual transfer.
                {% else %}
                <i class="fas fa-shield-alt"></i> Secured by Monnify — CBN Licensed Payment Gateway. Card, Transfer, USSD accepted.
                {% endif %}
            </p>
        </div>
    </form>

    <!-- Manual Payment Details Container (Hidden initially) -->
    <div class="checkout-card mt-3" id="manualDetailsCard" style="display: none; text-align: center;">
        <h2 class="checkout-title" style="color: #059669;"><i class="fas fa-university me-2"></i>Bank Transfer Details</h2>
        <p class="text-muted" style="font-size: 0.95rem; margin-bottom: 1.5rem;">
            Please transfer the total amount to the account below. Your subscription will be activated once payment is confirmed.
        </p>
        
        <div style="background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 12px; padding: 1.5rem; text-align: left; margin-bottom: 1.5rem;">
            <div class="mb-2"><strong>Bank Name:</strong> <span id="manBankName" style="float: right; color: #334155;">{{ manual_bank_details.bank_name }}</span></div>
            <div class="mb-2"><strong>Account Number:</strong> <span id="manAccNo" style="float: right; font-weight: 800; font-size: 1.1rem; color: #0f172a;">{{ manual_bank_details.account_number }}</span></div>
            <div class="mb-2"><strong>Account Name:</strong> <span id="manAccName" style="float: right; color: #334155;">{{ manual_bank_details.account_name }}</span></div>
            <div class="mb-2"><strong>Amount to Pay:</strong> <span id="manAmount" style="float: right; font-weight: 800; font-size: 1.1rem; color: #7c3aed;"></span></div>
            
            {% if manual_bank_details.instructions %}
            <div class="mt-3 pt-3" style="border-top: 1px solid #e2e8f0;">
                <p style="font-size: 0.85rem; color: #64748b; margin: 0;"><i class="fas fa-info-circle me-1"></i> {{ manual_bank_details.instructions }}</p>
            </div>
            {% endif %}
        </div>

        <div id="manWhatsappContainer" style="margin-bottom: 1rem; display: none;">
            <a href="#" id="manWhatsappBtn" target="_blank" class="btn-pay" style="text-decoration: none; background: #25D366; color: white;">
                <i class="fab fa-whatsapp me-2" style="font-size: 1.2rem;"></i> Send Proof via WhatsApp
            </a>
        </div>

        <a href="{% url 'subscriptions:manage' %}" class="btn-pay" style="text-decoration: none; background: #1e293b;">
            <i class="fas fa-check-circle"></i> I Have Sent the Payment
        </a>
    </div>
    {% endif %}

</div>
</div>
{% endblock %}

{% block extra_js %}
{# Load only the active gateway SDK #}
{% if gateway == 'paystack' %}
<script src="https://js.paystack.co/v2/inline.js"></script>
{% else %}
<script type="text/javascript" src="https://sdk.monnify.com/plugin/monnify.js"></script>
{% endif %}

<script>
var GATEWAY       = "{{ gateway }}";
var currentBasePrice = {{ billing_options.0.price|default:0 }};
var currentDiscount  = 0;
var planId           = {{ plan.id }};

// ── Monnify config ─────────────────────────────────────────────────────────
var MONNIFY_API_KEY       = "{{ monnify_api_key }}";
var MONNIFY_CONTRACT_CODE = "{{ monnify_contract_code }}";

// ── Paystack config ────────────────────────────────────────────────────────
var PAYSTACK_PUBLIC_KEY   = "{{ paystack_public_key }}";
var PAYSTACK_CALLBACK_URL = "{{ paystack_callback_url }}";

function fmt(n) {
    return parseFloat(n).toLocaleString('en-NG', {minimumFractionDigits: 0, maximumFractionDigits: 0});
}

function updateSummary() {
    var checked = document.querySelector('input[name="billing_cycle"]:checked');
    if (!checked) return;
    currentBasePrice = parseFloat(checked.dataset.price) || 0;
    currentDiscount  = 0;
    document.getElementById('promoResult').innerHTML     = '';
    document.getElementById('promoCodeHidden').value     = '';
    document.getElementById('promoInput').value          = '';
    document.getElementById('summCycle').textContent     = checked.dataset.label;
    document.getElementById('summBase').textContent      = fmt(currentBasePrice);
    document.getElementById('discountRow').style.display = 'none';
    document.getElementById('summTotal').textContent     = fmt(currentBasePrice);
    document.querySelectorAll('.billing-option').forEach(o => o.classList.remove('selected'));
    checked.closest('.billing-option').classList.add('selected');
}

function applyPromo() {
    var code     = document.getElementById('promoInput').value.trim().toUpperCase();
    var cycle    = (document.querySelector('input[name="billing_cycle"]:checked') || {}).value || 'monthly';
    var resultEl = document.getElementById('promoResult');
    if (!code) { resultEl.innerHTML = '<div class="promo-result promo-error">Please enter a promo code.</div>'; return; }

    fetch('{% url "subscriptions:validate_promo" %}', {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}'},
        body: JSON.stringify({code, plan_id: planId, billing_cycle: cycle})
    })
    .then(r => r.json())
    .then(d => {
        if (d.ok) {
            currentDiscount = d.discount_amount;
            document.getElementById('promoCodeHidden').value        = code;
            document.getElementById('summDiscount').textContent     = fmt(currentDiscount);
            document.getElementById('discountRow').style.display    = 'flex';
            document.getElementById('summTotal').textContent        = fmt(d.final_amount);
            resultEl.innerHTML = '<div class="promo-result promo-success"><i class="fas fa-check-circle me-1"></i>' + d.message + '</div>';
        } else {
            currentDiscount = 0;
            document.getElementById('promoCodeHidden').value        = '';
            document.getElementById('discountRow').style.display    = 'none';
            document.getElementById('summTotal').textContent        = fmt(currentBasePrice);
            resultEl.innerHTML = '<div class="promo-result promo-error"><i class="fas fa-times-circle me-1"></i>' + d.message + '</div>';
        }
    })
    .catch(() => { resultEl.innerHTML = '<div class="promo-result promo-error">Network error. Try again.</div>'; });
}

document.getElementById('checkoutForm') && document.getElementById('checkoutForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var btn            = document.getElementById('payBtn');
    var originalHTML   = btn ? btn.innerHTML : '';
    if (btn) { btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Initializing...'; btn.disabled = true; }

    var formData = new FormData(this);

    // POST to backend to create the pending transaction
    fetch('', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': '{{ csrf_token }}'
        },
        body: formData
    })
    .then(function(r) {
        var ct = r.headers.get('content-type') || '';
        if (!ct.includes('application/json')) {
            // Server returned HTML (error page / redirect) — not JSON
            throw new Error('Server returned an unexpected response (status ' + r.status + '). Check server logs.');
        }
        return r.json();
    })
    .then(function(data) {
        if (!data.ok) {
            alert(data.message || 'Payment initiation failed.');
            if (btn) { btn.innerHTML = originalHTML; btn.disabled = false; }
            return;
        }

        // Free transaction — no gateway needed
        if (data.free) {
            window.location.href = data.redirect_url;
            return;
        }

        if (GATEWAY === 'manual' || data.gateway === 'manual') {
            // ── Manual Bank Transfer ────────────────────────────────
            document.getElementById('checkoutForm').style.display = 'none';
            var manualCard = document.getElementById('manualDetailsCard');
            if (manualCard) {
                manualCard.style.display = 'block';
                document.getElementById('manAmount').textContent = '₦' + fmt(data.amount);
                if (data.bank_details && Object.keys(data.bank_details).length > 0) {
                    document.getElementById('manBankName').textContent = data.bank_details.bank_name;
                    document.getElementById('manAccNo').textContent = data.bank_details.account_number;
                    document.getElementById('manAccName').textContent = data.bank_details.account_name;
                    
                    var waContainer = document.getElementById('manWhatsappContainer');
                    var waBtn = document.getElementById('manWhatsappBtn');
                    if (data.bank_details.whatsapp_number) {
                        waContainer.style.display = 'block';
                        // Clean the number (remove non-digits, keep + if present)
                        var num = data.bank_details.whatsapp_number.replace(/[^\d+]/g, '');
                        // Prepare message
                        var msg = encodeURIComponent("Hello! I have just made a manual transfer of ₦" + fmt(data.amount) + " for my SwiftPOS subscription (" + data.reference + "). Attached is my proof of payment.");
                        waBtn.href = "https://wa.me/" + num + "?text=" + msg;
                    } else {
                        waContainer.style.display = 'none';
                    }
                }
            }
            return;
        }

        if (GATEWAY === 'paystack') {
            // ── Paystack Inline v2 ───────────────────────────────────
            // new PaystackPop().newTransaction() is the correct v2 API.
            // Amount must be in KOBO (naira × 100).
            var paystack = new PaystackPop();
            paystack.newTransaction({
                key:      PAYSTACK_PUBLIC_KEY,
                email:    data.customer_email,
                amount:   Math.round(data.amount * 100),
                ref:      data.reference,
                currency: 'NGN',
                label:    data.customer_name,
                onSuccess: function(transaction) {
                    if (btn) { btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying...'; btn.disabled = true; }
                    window.location.href = PAYSTACK_CALLBACK_URL
                        + '?reference=' + encodeURIComponent(transaction.reference || data.reference);
                },
                onCancel: function() {
                    if (btn) { btn.innerHTML = originalHTML; btn.disabled = false; }
                }
            });

        } else {
            // ── Monnify Web SDK Overlay ──────────────────────────────
            MonnifySDK.initialize({
                amount:              data.amount,
                currency:            'NGN',
                reference:           data.reference,
                customerName:        data.customer_name,
                customerEmail:       data.customer_email,
                apiKey:              MONNIFY_API_KEY,
                contractCode:        MONNIFY_CONTRACT_CODE,
                paymentDescription:  'SwiftPOS Subscription',
                onComplete: function(response) {
                    if (btn) { btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verifying...'; }
                    window.location.href = "{% url 'subscriptions:payment_callback' %}?paymentReference=" + encodeURIComponent(data.reference);
                },
                onClose: function() {
                    if (btn) { btn.innerHTML = originalHTML; btn.disabled = false; }
                }
            });
        }
    })
    .catch(function(error) {
        console.error('Checkout error:', error);
        alert('A network error occurred. Please try again.');
        if (btn) { btn.innerHTML = originalHTML; btn.disabled = false; }
    });
});
</script>
{% endblock %}
