@extends('layouts.app')

@section('title', 'Electricity')

@section('content')
<div class="mx-auto max-w-xl">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Electricity</h1>
        <p class="mt-1 text-sm text-gray-500">Pay your electricity bills and get tokens instantly.</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="electricityForm" 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-2 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-yellow-100 text-yellow-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-yellow-100 text-yellow-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>
                <label class="block text-sm font-medium text-gray-700 mb-2">Meter Type</label>
                <div class="grid grid-cols-2 gap-3">
                    <label class="relative cursor-pointer">
                        <input type="radio" name="meter_type" value="prepaid" class="peer sr-only" required onchange="onMeterTypeChange()">
                        <div class="flex items-center justify-center 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">
                            <span class="text-sm font-medium text-gray-700">Prepaid</span>
                        </div>
                    </label>
                    <label class="relative cursor-pointer">
                        <input type="radio" name="meter_type" value="postpaid" class="peer sr-only" required onchange="onMeterTypeChange()">
                        <div class="flex items-center justify-center 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">
                            <span class="text-sm font-medium text-gray-700">Postpaid</span>
                        </div>
                    </label>
                </div>
            </div>

            <div>
                <label for="meter_number" class="block text-sm font-medium text-gray-700 mb-1">Meter Number</label>
                <div class="flex gap-2">
                    <input type="text" name="meter_number" id="meter_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 meter number">
                    <button type="button" id="validateBtn" onclick="validateMeter()" 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="meter-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="meter-name"></p>
                </div>
                <p class="text-xs text-green-950 mt-1" id="meter-address"></p>
            </div>

            <input type="hidden" name="variation_code" id="variation_code">

            <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="100" 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. 2000">
            </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">Meter</span>
                    <span id="summaryMeter" 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>
                Pay Electricity Bill
            </button>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
let serviceCharge = 0;

function onProviderSelect(code) {
    document.getElementById('validateBtn').disabled = false;
    document.getElementById('meter-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 = '';

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

function onMeterTypeChange() {
    const meterType = document.querySelector('input[name="meter_type"]:checked')?.value;
    if (meterType) {
        document.getElementById('variation_code').value = meterType;
    }
}

async function validateMeter() {
    const provider = document.querySelector('input[name="provider"]:checked')?.value;
    const meterType = document.querySelector('input[name="meter_type"]:checked')?.value;
    const meterNumber = document.getElementById('meter_number').value.trim();

    if (!provider || !meterType || !meterNumber) return;

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

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

        const data = await response.json();

        if (data.valid) {
            const content = data.customer_data?.content || data.customer_data || {};
            const name = content.Customer_Name || content.customer_name || content.name || 'Verified';
            const address = content.Customer_Address || content.customer_address || content.address || '';
            const meter = content.Meter_Number || content.meter_number || meterNumber;

            document.getElementById('meter-name').textContent = name;
            document.getElementById('meter-address').textContent = address || `Meter: ${meter}`;
            document.getElementById('meter-info').classList.remove('hidden');

            document.getElementById('variation_code').value = meterType;
            document.getElementById('submitBtn').disabled = false;

            const total = serviceCharge;
            document.getElementById('summaryMeter').textContent = meterNumber;
            document.getElementById('summaryAmount').textContent = '₦0.00';
            document.getElementById('summaryCharge').textContent = '₦' + serviceCharge.toFixed(2);
            document.getElementById('summaryTotal').textContent = '₦' + total.toFixed(2);
            document.getElementById('summary-section').classList.remove('hidden');
        } else {
            showToast(data.message || 'Invalid meter 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('amount')?.addEventListener('input', function() {
    const amount = parseFloat(this.value) || 0;
    const total = amount + serviceCharge;
    document.getElementById('summaryAmount').textContent = '₦' + amount.toFixed(2);
    document.getElementById('summaryTotal').textContent = '₦' + total.toFixed(2);
    document.getElementById('summary-section').classList.remove('hidden');
});

document.getElementById('electricityForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = e.target;
    const meterNumber = form.meter_number.value;
    const meterType = form.meter_type.value;
    const provider = form.provider.value;
    const variationCode = form.variation_code.value;
    const amount = parseFloat(form.amount.value) || 0;
    const total = amount + serviceCharge;

    const confirmed = await showConfirm('Confirm Electricity Payment', [
        { label: 'Meter Number', value: meterNumber },
        { label: 'Meter Type', value: meterType.charAt(0).toUpperCase() + meterType.slice(1) },
        { 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("electricity.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({ meter_number: meterNumber, meter_type: meterType, 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 = 'Pay Electricity Bill';
        }
    } catch (err) {
        showToast('A network error occurred. Please try again.', 'error');
        btn.disabled = false;
        btn.textContent = 'Pay Electricity Bill';
    }
});
</script>
@endpush
