@extends('layouts.app')

@section('title', 'Buy Airtime')

@section('content')
<div class="mx-auto max-w-xl">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Buy Airtime</h1>
        <p class="mt-1 text-sm text-gray-500">Purchase airtime for any network.</p>
        <div class="mt-3 inline-flex items-center gap-2 rounded-full bg-green-50 border border-green-200 px-3 py-1.5">
            <span class="text-xs font-medium text-green-700">Wallet Balance:</span>
            <span class="text-sm font-bold text-green-900" id="walletBalance">₦{{ number_format($walletBalance, 2) }}</span>
            <a href="{{ route('wallet.index') }}" class="text-xs text-green-950 hover:text-green-700 underline">Fund</a>
        </div>
    </div>

    <div class="rounded-xl bg-white p-6 shadow-sm border border-gray-100">
        <form id="airtimeForm" class="space-y-6">

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-3">Select Network</label>
                <div class="grid grid-cols-4 gap-3">
                    @foreach($networks as $network)
                    <label class="relative cursor-pointer">
                        <input type="radio" name="network" value="{{ $network->code }}" class="peer sr-only" required onchange="selectNetwork(this)">
                        <div class="flex flex-col items-center gap-2 rounded-lg border-2 border-gray-200 p-3 hover:border-green-300 peer-checked:border-green-500 peer-checked:bg-green-50 transition-all">
                            @if($network->icon)
                                <img src="{{ $network->icon }}" alt="{{ $network->name }}" class="h-8 w-8 object-contain rounded" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                <div class="hidden h-8 w-8 items-center justify-center rounded bg-green-100 text-green-700 text-xs font-bold">{{ substr($network->name, 0, 1) }}</div>
                            @else
                                <div class="h-8 w-8 flex items-center justify-center rounded bg-green-100 text-green-700 text-xs font-bold">{{ substr($network->name, 0, 1) }}</div>
                            @endif
                            <span class="text-xs font-semibold text-gray-700">{{ $network->name }}</span>
                        </div>
                    </label>
                    @endforeach
                </div>
            </div>

            <div>
                <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">Phone Number</label>
                <input type="text" name="phone" id="phone" required class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-green-950 focus:ring-green-950 sm:text-sm px-3 py-2.5 border" placeholder="e.g. 08012345678">
            </div>

            <div>
                <label for="amount" class="block text-sm font-medium text-gray-700 mb-1">Amount (₦)</label>
                <input type="number" name="amount" id="amount" min="50" max="50000" required class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-green-950 focus:ring-green-950 sm:text-sm px-3 py-2.5 border" placeholder="e.g. 500">
            </div>

            <div id="quick-amounts" class="hidden">
                <label class="block text-sm font-medium text-gray-700 mb-2">Quick Select</label>
                <div class="grid grid-cols-3 gap-2">
                    <button type="button" onclick="pickAmount(100)" class="quick-amt rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-700 hover:border-green-300 hover:bg-green-50 transition">₦100</button>
                    <button type="button" onclick="pickAmount(200)" class="quick-amt rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-700 hover:border-green-300 hover:bg-green-50 transition">₦200</button>
                    <button type="button" onclick="pickAmount(500)" class="quick-amt rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-700 hover:border-green-300 hover:bg-green-50 transition">₦500</button>
                    <button type="button" onclick="pickAmount(1000)" class="quick-amt rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-700 hover:border-green-300 hover:bg-green-50 transition">₦1,000</button>
                    <button type="button" onclick="pickAmount(2000)" class="quick-amt rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-700 hover:border-green-300 hover:bg-green-50 transition">₦2,000</button>
                    <button type="button" onclick="pickAmount(5000)" class="quick-amt rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-700 hover:border-green-300 hover:bg-green-50 transition">₦5,000</button>
                </div>
            </div>

            <div class="rounded-lg bg-gray-50 p-4">
                <div class="flex justify-between text-sm">
                    <span class="text-gray-500">Amount</span>
                    <span id="displayAmount" class="font-medium text-gray-900">₦0.00</span>
                </div>
                <div class="flex justify-between text-sm mt-1">
                    <span class="text-gray-500">Service Charge</span>
                    <span id="serviceCharge" class="font-medium text-gray-900">₦0.00</span>
                </div>
                <div class="border-t border-gray-200 mt-2 pt-2 flex justify-between">
                    <span class="text-sm font-semibold text-gray-900">Total</span>
                    <span id="displayTotal" class="text-sm font-bold text-gray-900">₦0.00</span>
                </div>
            </div>

            <button type="submit" id="submitBtn" class="w-full rounded-lg bg-green-950 px-4 py-3 text-sm font-semibold text-white shadow-sm hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed">
                Purchase Airtime
            </button>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
const serviceCharges = @json($networks->pluck('service_charge', 'code'));
let selectedCharge = 0;

function selectNetwork(radio) {
    document.getElementById('quick-amounts').classList.remove('hidden');
    selectedCharge = parseFloat(serviceCharges[radio.value]) || 0;
    document.getElementById('serviceCharge').textContent = '₦' + selectedCharge.toFixed(2);
    updateTotal();
}

function pickAmount(amount) {
    document.getElementById('amount').value = amount;
    document.querySelectorAll('.quick-amt').forEach(btn => {
        btn.classList.remove('border-green-500', 'bg-green-50', 'text-green-700');
        btn.classList.add('border-gray-200', 'text-gray-700');
    });
    event.target.classList.remove('border-gray-200', 'text-gray-700');
    event.target.classList.add('border-green-500', 'bg-green-50', 'text-green-700');
    updateTotal();
}

document.getElementById('amount')?.addEventListener('input', updateTotal);

function updateTotal() {
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    const total = amount + selectedCharge;
    document.getElementById('displayAmount').textContent = '₦' + amount.toFixed(2);
    document.getElementById('displayTotal').textContent = '₦' + total.toFixed(2);
}

document.getElementById('airtimeForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = e.target;
    const networkName = form.network.value;
    const phone = form.phone.value;
    const amount = parseFloat(form.amount.value) || 0;
    const total = amount + selectedCharge;

    const confirmed = await showConfirm('Confirm Airtime Purchase', [
        { label: 'Network', value: networkName.toUpperCase() },
        { label: 'Phone Number', value: phone },
        { label: 'Amount', value: '₦' + amount.toFixed(2) },
        { label: 'Service Charge', value: '₦' + selectedCharge.toFixed(2) },
        { label: 'Total', value: '₦' + total.toFixed(2) },
    ]);

    if (!confirmed) return;

    const btn = document.getElementById('submitBtn');
    btn.disabled = true;
    btn.textContent = 'Processing...';

    try {
        const response = await fetch('{{ route("airtime.purchase") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'Idempotency-Key': crypto.randomUUID(),
            },
            body: JSON.stringify({ network: networkName, phone, amount }),
        });

        const result = await response.json();

        if (result.success) {
            showToast(result.message, 'success');
            setTimeout(() => { window.location.href = result.redirect; }, 1000);
        } else {
            showToast(result.message || 'Something went wrong. Please try again.', 'error');
            btn.disabled = false;
            btn.textContent = 'Purchase Airtime';
        }
    } catch (err) {
        showToast('A network error occurred. Please try again.', 'error');
        btn.disabled = false;
        btn.textContent = 'Purchase Airtime';
    }
});
</script>
@endpush
