@extends('layouts.app')

@section('title', 'Exam PINs')

@section('content')
<div class="mx-auto max-w-xl">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Exam PINs</h1>
        <p class="mt-1 text-sm text-gray-500">Purchase WAEC, NECO, JAMB, and NBAIS exam PINs.</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="exampinForm" class="space-y-6">

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-3">Select Exam Type</label>
                <div class="grid grid-cols-2 gap-3">
                    @foreach($types as $type)
                    <label class="relative cursor-pointer">
                        <input type="radio" name="exam_type" value="{{ $type->code }}" class="peer sr-only" required onchange="loadExamVariations('{{ $type->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($type->icon)
                                <img src="{{ $type->icon }}" alt="{{ $type->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-orange-100 text-orange-700 text-sm font-bold">{{ substr($type->name, 0, 1) }}</div>
                            @else
                                <div class="h-10 w-10 flex items-center justify-center rounded bg-orange-100 text-orange-700 text-sm font-bold">{{ substr($type->name, 0, 1) }}</div>
                            @endif
                            <span class="text-sm font-semibold text-gray-700">{{ $type->name }}</span>
                        </div>
                    </label>
                    @endforeach
                </div>
            </div>

            <div id="variations-section" class="hidden">
                <label class="block text-sm font-medium text-gray-700 mb-3">Select PIN Type</label>
                <div id="variations-container" class="space-y-2"></div>
                <input type="hidden" name="variation_code" id="variation_code">
            </div>

            <div id="profile-section" class="hidden">
                <label for="profile_id" class="block text-sm font-medium text-gray-700 mb-1">JAMB Profile ID</label>
                <div class="flex gap-2">
                    <input type="text" name="profile_id" id="profile_id" 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 your JAMB Profile ID">
                    <button type="button" id="verifyProfileBtn" onclick="verifyProfile()" 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 id="profile-info" class="hidden mt-2 rounded-lg bg-green-50 p-3 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="profile-name"></p>
                    </div>
                </div>
            </div>

            <input type="hidden" name="quantity" value="1">

            <div class="rounded-lg bg-gray-50 p-4">
                <div class="flex justify-between text-sm">
                    <span class="text-gray-500">Price per PIN</span>
                    <span id="pricePerPin" class="font-medium text-gray-900">₦0.00</span>
                </div>
                <div class="flex justify-between text-sm mt-1">
                    <span class="text-gray-500">Quantity</span>
                    <span id="qtyDisplay" class="font-medium text-gray-900">1</span>
                </div>
                <div class="flex justify-between text-sm mt-1">
                    <span class="text-gray-500">Service Charge</span>
                    <span id="serviceChargeDisplay" 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" disabled>
                Purchase Exam PIN
            </button>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
let selectedPrice = 0;
let selectedFee = 0;
let selectedExamType = '';
let profileVerified = false;

const jambTypes = @json($types->pluck('code')->filter(fn($c) => str_contains(strtolower($c), 'jamb'))->values());
const serviceCharges = @json($serviceCharges);

function calculateFee(amount, serviceCode) {
    return parseFloat(serviceCharges[serviceCode]) || 0;
}

async function loadExamVariations(type) {
    selectedExamType = type;
    profileVerified = false;
    const section = document.getElementById('variations-section');
    const container = document.getElementById('variations-container');
    const profileSection = document.getElementById('profile-section');
    const profileInfo = document.getElementById('profile-info');
    const submitBtn = document.getElementById('submitBtn');

    section.classList.remove('hidden');
    container.innerHTML = '<p class="text-sm text-gray-500">Loading...</p>';
    submitBtn.disabled = true;
    document.getElementById('variation_code').value = '';

    profileInfo.classList.add('hidden');
    document.getElementById('profile_id').value = '';

    if (jambTypes.includes(type)) {
        profileSection.classList.remove('hidden');
        document.getElementById('verifyProfileBtn').disabled = false;
    } else {
        profileSection.classList.add('hidden');
    }

    try {
        const response = await fetch(`/exam-pins/variations/${type}`);
        const data = await response.json();

        if (data.variations && data.variations.length > 0) {
            container.innerHTML = data.variations.map(v => `
                <label class="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="${v.code}" class="text-green-950 focus:ring-green-950" onchange="selectVariation(${v.amount || 0}, '${v.name}')">
                        <div>
                            <p class="text-sm font-medium text-gray-900">${v.name}</p>
                            ${v.amount ? `<p class="text-xs text-gray-500">₦${parseFloat(v.amount).toFixed(2)}</p>` : ''}
                        </div>
                    </div>
                </label>
            `).join('');
        }
    } catch (e) {
        container.innerHTML = '<p class="text-sm text-red-500">Error loading variations.</p>';
    }
}

function selectVariation(amount, name) {
    selectedPrice = amount;
    selectedFee = calculateFee(amount, selectedExamType);
    document.getElementById('variation_code').value = document.querySelector('input[name="variation_code"]:checked')?.value || '';
    document.getElementById('pricePerPin').textContent = '₦' + amount.toFixed(2);
    checkSubmitReady();
    updateTotal();
}

function checkSubmitReady() {
    const isJamb = jambTypes.includes(selectedExamType);
    const variationSelected = !!document.getElementById('variation_code').value;
    const profileOk = isJamb ? profileVerified : true;
    document.getElementById('submitBtn').disabled = !(variationSelected && profileOk);
}

async function verifyProfile() {
    const profileId = document.getElementById('profile_id').value.trim();
    const variationCode = document.getElementById('variation_code').value;

    if (!profileId || !selectedExamType) return;

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

    try {
        const response = await fetch('{{ route("exampin.validate-profile") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: JSON.stringify({
                profile_id: profileId,
                service_code: selectedExamType,
                variation_code: variationCode,
            }),
        });

        const data = await response.json();

        if (data.valid) {
            profileVerified = true;
            document.getElementById('profile-name').textContent = data.customer_name || 'Verified';
            document.getElementById('profile-info').classList.remove('hidden');
            checkSubmitReady();
        } else {
            profileVerified = false;
            showToast(data.message || 'Invalid Profile ID. Please check and try again.', 'error');
            document.getElementById('profile-info').classList.add('hidden');
            document.getElementById('submitBtn').disabled = true;
        }
    } catch (e) {
        profileVerified = false;
        showToast('Verification failed. Please try again.', 'error');
        document.getElementById('profile-info').classList.add('hidden');
        document.getElementById('submitBtn').disabled = true;
    } finally {
        btn.disabled = false;
        btn.textContent = 'Verify';
    }
}

function updateTotal() {
    const total = selectedPrice + selectedFee;
    document.getElementById('serviceChargeDisplay').textContent = '₦' + selectedFee.toFixed(2);
    document.getElementById('displayTotal').textContent = '₦' + total.toFixed(2);
}

document.getElementById('exampinForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = e.target;
    const variationCode = form.variation_code.value;
    const variationEl = document.querySelector('input[name="variation_code"]:checked');
    const variationName = variationEl ? variationEl.closest('label')?.querySelector('p')?.textContent || variationCode : variationCode;
    const total = selectedPrice + selectedFee;

    const lines = [
        { label: 'PIN Type', value: variationName },
        { label: 'Price', value: '₦' + selectedPrice.toFixed(2) },
        { label: 'Service Charge', value: '₦' + selectedFee.toFixed(2) },
        { label: 'Total', value: '₦' + total.toFixed(2) },
    ];

    const profileId = form.profile_id?.value?.trim();
    if (profileId) {
        lines.splice(1, 0, { label: 'Profile ID', value: profileId });
    }

    const confirmed = await showConfirm('Confirm Exam PIN Purchase', lines);
    if (!confirmed) return;

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

    const data = { variation_code: variationCode, quantity: 1 };
    if (profileId) { data.profile_id = profileId; }

    try {
        const response = await fetch('{{ route("exampin.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(data),
        });

        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 Exam PIN';
        }
    } catch (err) {
        showToast('A network error occurred. Please try again.', 'error');
        btn.disabled = false;
        btn.textContent = 'Purchase Exam PIN';
    }
});
</script>
@endpush
