@extends('layouts.app')

@section('title', 'Cable TV Subscription')

@section('content')
<div class="mx-auto max-w-xl">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Cable TV Subscription</h1>
        <p class="mt-1 text-sm text-gray-500">Subscribe to your favorite cable TV provider.</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="cableForm" class="space-y-6">

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

            <div id="bouquets-section" class="hidden">
                <label class="block text-sm font-medium text-gray-700 mb-3">Select Bouquet</label>
                <input type="text" id="bouquet-search" placeholder="Search bouquets..." 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" oninput="filterBouquets(this.value)">
                <div id="bouquets-container" class="space-y-2 max-h-64 overflow-y-auto"></div>
                <input type="hidden" name="variation_code" id="variation_code">
                <input type="hidden" name="amount" id="amount">
            </div>

            <div>
                <label for="smartcard_number" class="block text-sm font-medium text-gray-700 mb-1">Smartcard Number</label>
                <div class="flex gap-2">
                    <input type="text" name="smartcard_number" id="smartcard_number" 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="Enter smartcard number">
                    <button type="button" id="validateBtn" onclick="validateSmartcard()" class="whitespace-nowrap rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                        Verify
                    </button>
                </div>
            </div>

            <div id="customer-info" class="hidden rounded-lg bg-green-50 p-4 border border-green-200">
                <div class="flex items-center gap-2">
                    <svg class="h-5 w-5 text-green-950" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
                    <p class="text-sm font-medium text-green-800" id="customer-name"></p>
                </div>
                <p class="text-xs text-green-950 mt-1" id="customer-details"></p>
            </div>

            <div class="rounded-lg bg-gray-50 p-4 hidden" id="summary-section">
                <div class="flex justify-between text-sm">
                    <span class="text-gray-500">Bouquet</span>
                    <span id="summaryBouquet" class="font-medium text-gray-900">-</span>
                </div>
                <div class="flex justify-between text-sm mt-1">
                    <span class="text-gray-500">Amount</span>
                    <span id="summaryAmount" 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="summaryCharge" 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="summaryTotal" 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" disabled>
                Subscribe Now
            </button>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
let serviceCharge = 0;
let validated = false;
let allBouquets = [];

function onProviderSelect(code) {
    validated = false;
    document.getElementById('validateBtn').disabled = false;
    document.getElementById('customer-info').classList.add('hidden');
    document.getElementById('summary-section').classList.add('hidden');
    document.getElementById('submitBtn').disabled = true;
    document.getElementById('variation_code').value = '';
    document.getElementById('amount').value = '';
    document.getElementById('bouquet-search').value = '';

    const providers = @json($providers);
    const provider = providers.find(p => p.code === code);
    serviceCharge = provider ? parseFloat(provider.service_charge) : 0;

    loadBouquets(code);
}

async function loadBouquets(provider) {
    const section = document.getElementById('bouquets-section');
    const container = document.getElementById('bouquets-container');
    section.classList.remove('hidden');
    container.innerHTML = '<p class="text-sm text-gray-500">Loading bouquets...</p>';

    try {
        const response = await fetch(`/cable/bouquets/${provider}`);
        const data = await response.json();

        if (data.bouquets && data.bouquets.length > 0) {
            allBouquets = data.bouquets;
            renderBouquets(allBouquets);
        } else {
            container.innerHTML = '<p class="text-sm text-gray-500">No bouquets available.</p>';
        }
    } catch (e) {
        container.innerHTML = '<p class="text-sm text-red-500">Error loading bouquets.</p>';
    }
}

function renderBouquets(bouquets) {
    const container = document.getElementById('bouquets-container');
    container.innerHTML = bouquets.map(b => `
        <label class="bouquet-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="${b.code}" class="text-green-950 focus:ring-green-950" onchange="selectBouquet('${b.code}', ${b.amount || 0}, '${b.name.replace(/'/g, "\\'")}')">
                <div>
                    <p class="text-sm font-medium text-gray-900 bouquet-name">${b.name}</p>
                    ${b.amount ? `<p class="text-xs text-gray-500">₦${parseFloat(b.amount).toFixed(2)}</p>` : ''}
                </div>
            </div>
        </label>
    `).join('');
}

function filterBouquets(query) {
    const filtered = allBouquets.filter(b => b.name.toLowerCase().includes(query.toLowerCase()));
    renderBouquets(filtered);
}

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

    const total = amount + serviceCharge;
    document.getElementById('summaryBouquet').textContent = name;
    document.getElementById('summaryAmount').textContent = '₦' + amount.toFixed(2);
    document.getElementById('summaryCharge').textContent = '₦' + serviceCharge.toFixed(2);
    document.getElementById('summaryTotal').textContent = '₦' + total.toFixed(2);
    document.getElementById('summary-section').classList.remove('hidden');
}

async function validateSmartcard() {
    const provider = document.querySelector('input[name="provider"]:checked')?.value;
    const smartcard = document.getElementById('smartcard_number').value.trim();

    if (!provider || !smartcard) return;

    const btn = document.getElementById('validateBtn');
    btn.disabled = true;
    btn.textContent = 'Verifying...';

    try {
        const response = await fetch('{{ route("cable.validate") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ provider, smartcard_number: smartcard })
        });

        const data = await response.json();

        if (data.valid) {
            validated = true;
            const customerData = data.customer_data?.content || data.customer_data || {};
            const name = customerData.Customer_Name || customerData.customer_name || customerData.name || 'Verified';
            const dueDate = customerData.Due_Date || customerData.due_date || '';

            document.getElementById('customer-name').textContent = name;
            document.getElementById('customer-details').textContent = dueDate ? `Valid until: ${dueDate}` : 'Smartcard verified successfully';
            document.getElementById('customer-info').classList.remove('hidden');
        } else {
            showToast(data.message || 'Invalid smartcard number. Please check and try again.', 'error');
        }
    } catch (e) {
        showToast('Verification failed. Please try again.', 'error');
    } finally {
        btn.disabled = false;
        btn.textContent = 'Verify';
    }
}

document.getElementById('cableForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = e.target;
    const provider = form.provider.value;
    const smartcard = form.smartcard_number.value;
    const variationCode = form.variation_code.value;
    const amount = parseFloat(form.amount.value) || 0;
    const bouquetName = document.getElementById('summaryBouquet').textContent || variationCode;
    const total = amount + serviceCharge;

    const confirmed = await showConfirm('Confirm Cable Subscription', [
        { label: 'Smartcard', value: smartcard },
        { label: 'Bouquet', value: bouquetName },
        { label: 'Amount', value: '₦' + amount.toFixed(2) },
        { label: 'Service Charge', value: '₦' + serviceCharge.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("cable.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({ smartcard_number: smartcard, provider, 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 = 'Subscribe Now';
        }
    } catch (err) {
        showToast('A network error occurred. Please try again.', 'error');
        btn.disabled = false;
        btn.textContent = 'Subscribe Now';
    }
});
</script>
@endpush
