<?php
// app/Views/admin/subscription/payment.php
?>
<div class="max-w-3xl mx-auto space-y-8 animate-fade-in pb-12">
    <!-- Header -->
    <div>
        <a href="/admin/subscription" class="inline-flex items-center gap-1.5 text-xs text-slate-400 hover:text-white transition mb-3">
            <i class="fas fa-chevron-left text-3xs"></i> Back to Subscription
        </a>
        <h2 class="text-xl font-bold text-white">Complete Your Subscription Purchase</h2>
        <p class="text-slate-400 text-sm mt-1">Please make the offline payment using one of the channels below and submit your payment details for verification.</p>
    </div>

    <!-- Error/Notice Alerts -->
    <?php if (isset($_GET['error'])): ?>
    <div class="flex items-center gap-3 px-5 py-4 rounded-2xl border border-red-500/30 bg-red-500/10 text-red-400 text-sm">
        <i class="fas fa-circle-exclamation text-lg"></i>
        <div>
            <p class="font-bold">Payment Submission Failed</p>
            <p class="text-xs text-red-400/80 mt-0.5"><?php echo htmlspecialchars($_GET['error']); ?></p>
        </div>
    </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        
        <!-- Payment Details Form (Left / Col-7) -->
        <div class="lg:col-span-7 rounded-2xl border border-white/5 p-6 space-y-6" style="background: rgba(255,255,255,0.02);">
            <div class="border-b border-white/5 pb-3">
                <h3 class="font-bold text-white text-base">Payment Method &amp; Reference</h3>
                <p class="text-xs text-slate-400 mt-1">Select your gateway and provide details of the completed transaction.</p>
            </div>

            <!-- Tab Selectors -->
            <div class="grid grid-cols-3 gap-3">
                <button type="button" onclick="selectGateway('bkash')" id="tab-bkash"
                        class="gateway-tab py-3.5 rounded-xl border font-bold text-xs flex flex-col items-center gap-2 transition active:scale-[0.98]">
                    <i class="fas fa-mobile-screen-button text-base text-pink-400"></i>
                    <span>bKash</span>
                </button>
                <button type="button" onclick="selectGateway('nagad')" id="tab-nagad"
                        class="gateway-tab py-3.5 rounded-xl border font-bold text-xs flex flex-col items-center gap-2 transition active:scale-[0.98]">
                    <i class="fas fa-mobile-screen-button text-base text-orange-400"></i>
                    <span>Nagad</span>
                </button>
                <button type="button" onclick="selectGateway('bank')" id="tab-bank"
                        class="gateway-tab py-3.5 rounded-xl border font-bold text-xs flex flex-col items-center gap-2 transition active:scale-[0.98]">
                    <i class="fas fa-building-columns text-base text-blue-400"></i>
                    <span>Bank Transfer</span>
                </button>
            </div>

            <!-- Instruction Cards -->
            <div class="rounded-xl border border-white/5 p-4 text-xs space-y-3" style="background: rgba(255,255,255,0.015);">
                <!-- bKash Instructions -->
                <div id="instr-bkash" class="gateway-instruction space-y-2.5 hidden">
                    <div class="flex items-center gap-2">
                        <span class="w-2.5 h-2.5 rounded-full bg-pink-500"></span>
                        <h4 class="font-bold text-white">bKash Send Money Instruction</h4>
                    </div>
                    <p class="text-slate-400 leading-relaxed">
                        Please send money of <strong class="text-white"><?php echo htmlspecialchars($pkg['currency'] ?? '$') . number_format($pkg['price'], 2); ?></strong> to our personal bKash number below:
                    </p>
                    <div class="p-3 rounded-lg border border-pink-500/20 bg-pink-500/5 flex items-center justify-between">
                        <div>
                            <span class="text-slate-500 text-3xs uppercase tracking-wider block font-bold">bKash Personal Number</span>
                            <span class="text-base font-extrabold text-white">01850211813</span>
                        </div>
                        <button type="button" onclick="copyText('01850211813')" class="px-2.5 py-1.5 rounded-md bg-white/5 hover:bg-white/10 text-slate-300 font-semibold transition flex items-center gap-1">
                            <i class="fas fa-copy text-3xs"></i> Copy
                        </button>
                    </div>
                    <ul class="list-disc list-inside text-slate-400 space-y-1 mt-2 text-3xs">
                        <li>Send Money only. Do not cash out or pay.</li>
                        <li>Keep the Transaction ID (TxID) to fill the form below.</li>
                    </ul>
                </div>

                <!-- Nagad Instructions -->
                <div id="instr-nagad" class="gateway-instruction space-y-2.5 hidden">
                    <div class="flex items-center gap-2">
                        <span class="w-2.5 h-2.5 rounded-full bg-orange-500"></span>
                        <h4 class="font-bold text-white">Nagad Send Money Instruction</h4>
                    </div>
                    <p class="text-slate-400 leading-relaxed">
                        Please send money of <strong class="text-white"><?php echo htmlspecialchars($pkg['currency'] ?? '$') . number_format($pkg['price'], 2); ?></strong> to our personal Nagad number below:
                    </p>
                    <div class="p-3 rounded-lg border border-orange-500/20 bg-orange-500/5 flex items-center justify-between">
                        <div>
                            <span class="text-slate-500 text-3xs uppercase tracking-wider block font-bold">Nagad Personal Number</span>
                            <span class="text-base font-extrabold text-white">01850211813</span>
                        </div>
                        <button type="button" onclick="copyText('01850211813')" class="px-2.5 py-1.5 rounded-md bg-white/5 hover:bg-white/10 text-slate-300 font-semibold transition flex items-center gap-1">
                            <i class="fas fa-copy text-3xs"></i> Copy
                        </button>
                    </div>
                    <ul class="list-disc list-inside text-slate-400 space-y-1 mt-2 text-3xs">
                        <li>Send Money only. Do not cash out or pay.</li>
                        <li>Ensure you note down the Transaction Reference/TxID.</li>
                    </ul>
                </div>

                <!-- Bank Transfer Instructions -->
                <div id="instr-bank" class="gateway-instruction space-y-2.5 hidden">
                    <div class="flex items-center gap-2">
                        <span class="w-2.5 h-2.5 rounded-full bg-blue-500"></span>
                        <h4 class="font-bold text-white">Bank Account Details</h4>
                    </div>
                    <p class="text-slate-400 leading-relaxed">
                        Please wire the subscription fee of <strong class="text-white"><?php echo htmlspecialchars($pkg['currency'] ?? '$') . number_format($pkg['price'], 2); ?></strong> to our bank account:
                    </p>
                    <div class="p-4 rounded-lg border border-blue-500/20 bg-blue-500/5 space-y-2.5">
                        <div class="grid grid-cols-2 gap-2 text-2xs">
                            <div>
                                <span class="text-slate-500 font-semibold uppercase tracking-wider block">Bank Name</span>
                                <span class="font-bold text-white">AB Bank</span>
                            </div>
                            <div>
                                <span class="text-slate-500 font-semibold uppercase tracking-wider block">Account Name</span>
                                <span class="font-bold text-white">Norul Hossan</span>
                            </div>
                            <div class="col-span-2 border-t border-white/5 pt-2 flex items-center justify-between">
                                <div>
                                    <span class="text-slate-500 font-semibold uppercase tracking-wider block">Account Number</span>
                                    <span class="text-base font-extrabold text-white">1111313268308</span>
                                </div>
                                <button type="button" onclick="copyText('1111313268308')" class="px-2.5 py-1.5 rounded-md bg-white/5 hover:bg-white/10 text-slate-300 font-semibold transition flex items-center gap-1">
                                    <i class="fas fa-copy text-3xs"></i> Copy
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Form -->
            <form action="/admin/subscription/payment/submit" method="POST" class="space-y-4">
                <input type="hidden" name="package_id" value="<?php echo $pkg['id']; ?>">
                <input type="hidden" name="payment_method" id="selected-method" value="">
                <input type="hidden" name="coupon_code" id="applied-coupon-code" value="">

                <!-- Account / Sender details -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="space-y-1.5">
                        <label id="lbl-sender-number" class="text-xs font-semibold text-slate-400">Sender Number / Account</label>
                        <input type="text" name="sender_number" placeholder="e.g. 017XXXXXXXX or Account No" required
                               class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500 transition">
                    </div>
                    <div class="space-y-1.5">
                        <label id="lbl-account-name" class="text-xs font-semibold text-slate-400">Account / Sender Name</label>
                        <input type="text" name="account_name" placeholder="e.g. John Doe" required
                               class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500 transition">
                    </div>
                </div>

                <!-- TxID -->
                <div class="space-y-1.5">
                    <label id="lbl-trans-ref" class="text-xs font-semibold text-slate-400">Transaction ID / Reference Number</label>
                    <input type="text" name="transaction_reference" placeholder="e.g. TR12345678 or Bank Ref" required
                           class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-500 transition">
                </div>

                <button type="submit" class="w-full py-3 px-5 rounded-xl text-xs font-extrabold text-white transition hover:brightness-110 flex items-center justify-center gap-2"
                        style="background: linear-gradient(135deg, #a855f7, #7c3aed); box-shadow: 0 4px 15px rgba(124, 58, 237, 0.25);">
                    <i class="fas fa-circle-check"></i> Submit Payment for Approval
                </button>
            </form>
        </div>

        <!-- Summary & Package Card (Right / Col-5) -->
        <div class="lg:col-span-5 rounded-2xl border border-white/5 p-6 space-y-6" style="background: rgba(255,255,255,0.015);">
            <div class="border-b border-white/5 pb-3">
                <h3 class="font-bold text-white text-base">Package Summary</h3>
            </div>

            <!-- Details List -->
            <div class="space-y-4">
                <div class="flex justify-between items-center text-xs">
                    <span class="text-slate-400">Plan Name</span>
                    <span class="font-bold text-white uppercase px-2 py-0.5 rounded bg-white/5 border border-white/10"><?php echo htmlspecialchars($pkg['name']); ?></span>
                </div>
                <div class="flex justify-between items-center text-xs">
                    <span class="text-slate-400">Billing Duration</span>
                    <span class="font-semibold text-slate-300"><?php echo $pkg['duration_days']; ?> Days</span>
                </div>
                <div class="flex justify-between items-center text-xs">
                    <span class="text-slate-400">Price Rate</span>
                    <span class="font-semibold text-slate-300"><?php echo htmlspecialchars($pkg['currency'] ?? '$') . number_format($pkg['price'], 2); ?></span>
                </div>

                <!-- Discount Row -->
                <div id="discount-row" class="flex justify-between items-center text-xs text-emerald-400 hidden">
                    <span>Discount</span>
                    <span id="discount-val">-<?php echo htmlspecialchars($pkg['currency'] ?? '$'); ?>0.00</span>
                </div>

                <div class="border-t border-white/5 pt-4 flex justify-between items-baseline">
                    <span class="text-slate-300 font-bold text-sm">Total Due</span>
                    <span id="total-due-val" class="text-2xl font-extrabold text-purple-400"><?php echo htmlspecialchars($pkg['currency'] ?? '$') . number_format($pkg['price'], 2); ?></span>
                </div>
            </div>

            <!-- Coupon Code Field -->
            <div class="border-t border-white/5 pt-4 space-y-2">
                <label class="block text-xs font-semibold text-slate-400">Promo / Coupon Code</label>
                <div class="flex gap-2">
                    <input type="text" id="coupon-code-input" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white uppercase placeholder-slate-650" placeholder="e.g. SAVE10">
                    <button type="button" onclick="applyCoupon()" class="px-4 py-2 rounded-xl text-xs font-bold text-white bg-purple-600 hover:bg-purple-700 transition">Apply</button>
                </div>
                <p id="coupon-msg" class="text-3xs font-medium hidden"></p>
            </div>

            <!-- Security info -->
            <div class="rounded-xl p-3 bg-purple-500/5 border border-purple-500/10 text-3xs text-purple-300/80 leading-relaxed flex gap-2">
                <i class="fas fa-shield-halved text-sm text-purple-400 mt-0.5"></i>
                <p>
                    All offline transactions are checked manually. Your restaurant profile will remain active as before once approved by the Super Admin. Typically verified within 1-4 hours.
                </p>
            </div>
        </div>
        
    </div>
</div>

<script>
    // Tab gateway switching
    function selectGateway(method) {
        // Clear active classes
        document.querySelectorAll('.gateway-tab').forEach(tab => {
            tab.className = tab.className.replace(/border-purple-500.*bg-purple-500\/5/g, '').trim();
            tab.className += ' border-white/5 bg-transparent text-slate-400 hover:bg-white/5';
        });
        document.querySelectorAll('.gateway-instruction').forEach(el => el.classList.add('hidden'));

        // Set active tab
        const activeTab = document.getElementById('tab-' + method);
        activeTab.className = activeTab.className.replace(/border-white\/5|bg-transparent|text-slate-400/g, '').trim();
        activeTab.className += ' border-purple-500 bg-purple-500/5 text-purple-300';

        // Display correct instructions
        document.getElementById('instr-' + method).classList.remove('hidden');

        // Update inputs labels & placeholders dynamically
        const lblSender = document.getElementById('lbl-sender-number');
        const lblName = document.getElementById('lbl-account-name');
        const lblRef = document.getElementById('lbl-trans-ref');

        if (method === 'bank') {
            lblSender.innerText = 'Sender Bank Account Number';
            lblName.innerText = 'Account Holder Name';
            lblRef.innerText = 'Reference Number / TxID';
        } else {
            lblSender.innerText = 'Sender Mobile Number';
            lblName.innerText = 'Sender Account Name';
            lblRef.innerText = 'Transaction ID (TxID)';
        }

        // Set input value
        document.getElementById('selected-method').value = method;
    }

    // Copy to clipboard helper
    function copyText(text) {
        navigator.clipboard.writeText(text).then(() => {
            alert('Copied to clipboard: ' + text);
        }).catch(err => {
            // fallback
            const input = document.createElement('input');
            input.value = text;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            alert('Copied to clipboard: ' + text);
        });
    }

    // Default select bKash
    document.addEventListener('DOMContentLoaded', () => {
        selectGateway('bkash');
    });

    function applyCoupon() {
        const codeInput = document.getElementById('coupon-code-input');
        const code = codeInput.value.trim().toUpperCase();
        const msgEl = document.getElementById('coupon-msg');
        
        if (!code) {
            msgEl.className = "text-3xs font-medium text-red-400";
            msgEl.innerText = "Please enter a coupon code.";
            msgEl.classList.remove('hidden');
            return;
        }

        const formData = new FormData();
        formData.append('code', code);
        formData.append('package_id', '<?php echo $pkg['id']; ?>');

        fetch('/admin/subscription/payment/validate-coupon', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            msgEl.classList.remove('hidden');
            if (data.success) {
                msgEl.className = "text-3xs font-medium text-emerald-400";
                msgEl.innerText = data.message;
                
                // Show discount row
                const discRow = document.getElementById('discount-row');
                discRow.classList.remove('hidden');
                document.getElementById('discount-val').innerText = '-' + '<?php echo htmlspecialchars($pkg['currency'] ?? '$'); ?>' + parseFloat(data.discount).toFixed(2);
                
                // Update total due
                document.getElementById('total-due-val').innerText = '<?php echo htmlspecialchars($pkg['currency'] ?? '$'); ?>' + parseFloat(data.new_price).toFixed(2);
                
                // Set hidden input value
                document.getElementById('applied-coupon-code').value = data.code;
            } else {
                msgEl.className = "text-3xs font-medium text-red-400";
                msgEl.innerText = data.message;
                
                // Hide discount row and reset total
                document.getElementById('discount-row').classList.add('hidden');
                document.getElementById('total-due-val').innerText = '<?php echo htmlspecialchars($pkg['currency'] ?? '$') . number_format($pkg['price'], 2); ?>';
                document.getElementById('applied-coupon-code').value = '';
            }
        })
        .catch(err => {
            console.error(err);
            msgEl.className = "text-3xs font-medium text-red-400";
            msgEl.innerText = "Error validating coupon. Please try again.";
            msgEl.classList.remove('hidden');
        });
    }
</script>
