@extends('layouts.app')

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

@section('content')
<div class="mx-auto max-w-xl">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Buy Data</h1>
        <p class="mt-1 text-sm text-gray-500">Purchase data bundles 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="dataForm" 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="fetchPlans(this.value)">
                        <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-blue-100 text-blue-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-blue-100 text-blue-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 class="block text-sm font-medium text-gray-700 mb-3">Select Plan</label>
                <input type="text" id="plan-search" placeholder="Search plans..." 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 mb-2 hidden" oninput="filterPlans(this.value)">
                <div id="plans-container" class="space-y-2">
                    <p class="text-sm text-gray-500">Please select a network first.</p>
                </div>
                <input type="hidden" name="variation_code" id="variation_code">
                <input type="hidden" name="amount" id="amount">
            </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" disabled>
                Purchase Data
            </button>
        </form>
    </div>
</div>
@endsection

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

async function fetchPlans(network) {
    const container = document.getElementById('plans-container');
    const search = document.getElementById('plan-search');
    container.innerHTML = '<p class="text-sm text-gray-500">Loading plans...</p>';
    document.getElementById('submitBtn').disabled = true;
    document.getElementById('variation_code').value = '';
    document.getElementById('amount').value = '';
    search.value = '';
    search.classList.add('hidden');

    try {
        const response = await fetch(`/data/plans/${network}`);
        const data = await response.json();

        if (data.plans && data.plans.length > 0) {
            allPlans = data.plans;
            renderPlans(allPlans);
            search.classList.remove('hidden');
        } else {
            container.innerHTML = '<p class="text-sm text-gray-500">No plans available for this network.</p>';
        }
    } catch (e) {
        container.innerHTML = '<p class="text-sm text-red-500">Error loading plans. Please try again.</p>';
    }
}

function renderPlans(plans) {
    const container = document.getElementById('plans-container');
    container.innerHTML = plans.map(plan => `
        <label class="plan-item flex items-center justify-between rounded-lg border border-gray-200 p-3 hover:border-green-300 cursor-pointer has-[:checked]:border-green-500 has-[:checked]:bg-green-50">
            <div class="flex items-center gap-3">
                <input type="radio" name="variation_code" value="${plan.code}" class="text-green-950 focus:ring-green-950" onchange="selectPlan('${plan.code}', ${plan.amount || 0}, '${plan.name.replace(/'/g, "\\'")}')">
                <div>
                    <p class="text-sm font-medium text-gray-900 plan-name">${plan.name}</p>
                    ${plan.amount ? `<p class="text-xs text-gray-500">₦${parseFloat(plan.amount).toFixed(2)}</p>` : ''}
                </div>
            </div>
        </label>
    `).join('');
}

function filterPlans(query) {
    const filtered = allPlans.filter(p => p.name.toLowerCase().includes(query.toLowerCase()));
    renderPlans(filtered);
}

function selectPlan(code, amount, name) {
    document.getElementById('variation_code').value = code;
    document.getElementById('amount').value = amount;
    document.getElementById('submitBtn').disabled = false;
}

document.getElementById('dataForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = e.target;
    const network = form.network.value;
    const phone = form.phone.value;
    const variationCode = form.variation_code.value;
    const amount = parseFloat(form.amount.value) || 0;
    const planEl = document.querySelector('input[name="variation_code"]:checked');
    const planName = planEl ? planEl.closest('label')?.querySelector('.plan-name')?.textContent || variationCode : variationCode;
    const charge = parseFloat(serviceCharges[network]) || 0;
    const total = amount + charge;

    const confirmed = await showConfirm('Confirm Data Purchase', [
        { label: 'Network', value: network.toUpperCase() },
        { label: 'Phone Number', value: phone },
        { label: 'Plan', value: planName },
        { label: 'Amount', value: '₦' + amount.toFixed(2) },
        { label: 'Service Charge', value: '₦' + charge.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("data.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, phone, variation_code: variationCode, 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 Data';
        }
    } catch (err) {
        showToast('A network error occurred. Please try again.', 'error');
        btn.disabled = false;
        btn.textContent = 'Purchase Data';
    }
});
</script>
@endpush
