@extends('layouts.app')
@section('title',$customer->exists?'Edit Customer':'Register Customer')
@section('content')
@php $address=$customer->address; $kin=$customer->nextOfKin?->firstWhere('is_primary',true); @endphp
<x-ui.form-shell
    :title="$customer->exists?'Edit Customer':'Register Customer'"
    description="Capture customer identity, contact, employment, residential and next-of-kin information in a structured KYC record."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Customers','url'=>route('customers.index')],['label'=>$customer->exists?'Edit Customer':'Register Customer']]"
>
    @if($errors->has('duplicate'))
        <div class="mb-4 rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{{ $errors->first('duplicate') }}</div>
    @endif

    <form method="POST" enctype="multipart/form-data" action="{{ $customer->exists?route('customers.update',$customer):route('customers.store') }}" class="mf-form">
        @csrf
        @if($customer->exists)@method('PUT')@endif

        <x-ui.form-section title="Registration & identity" description="Branch ownership, identification method and primary legal identity details.">
            <x-ui.form-grid>
                <div class="mf-col-3"><label class="mf-field-label">Branch</label><select class="mf-input" name="branch_id" required>@foreach($branches as $branch)<option value="{{ $branch->id }}" @selected(old('branch_id',$customer->branch_id)==$branch->id)>{{ $branch->name }}</option>@endforeach</select></div>
                <div class="mf-col-2"><label class="mf-field-label">Registration mode</label><select id="identity_mode" class="mf-input" name="identity_mode"><option value="without_nin" @selected(old('identity_mode',$customer->identity_mode)==='without_nin')>Without NIN</option><option value="with_nin" @selected(old('identity_mode',$customer->identity_mode)==='with_nin')>With NIN</option></select></div>
                <div class="mf-col-4">
                    <div class="flex items-center justify-between gap-2">
                        <label class="mf-field-label">NIN</label>
                        <span class="mf-badge {{ $ninLookupEnabled ? 'mf-badge-success' : 'mf-badge-muted' }}">{{ $ninLookupEnabled ? 'Verification on' : 'Manual entry' }}</span>
                    </div>
                    <div class="mf-form-inline">
                        <input id="nin" class="mf-input" name="nin" inputmode="numeric" autocomplete="off" maxlength="{{ $ninLookupEnabled ? 20 : 100 }}" value="{{ old('nin',$customer->nin) }}" placeholder="{{ $ninLookupEnabled ? '20-digit NIN' : 'Enter NIN number' }}">
                        @if($ninLookupEnabled)
                            <button id="nin_lookup" type="button" class="mf-btn">Fetch</button>
                        @endif
                    </div>
                    <p id="nin_result" class="mf-field-help">
                        {{ $ninLookupEnabled ? 'Enter the 20-digit NIN and use Fetch to load available identity details.' : 'NIN verification is disabled. The number will be saved as entered without an external lookup or 20-digit validation.' }}
                    </p>
                </div>
                <div class="mf-col-3"><label class="mf-field-label">Customer status</label><select class="mf-input" name="status">@foreach(['active','inactive','deceased'] as $v)<option value="{{ $v }}" @selected(old('status',$customer->status ?: 'active')===$v)>{{ ucfirst($v) }}</option>@endforeach</select></div>
                <div class="mf-col-4"><label class="mf-field-label">First name</label><input id="first_name" class="mf-input" name="first_name" value="{{ old('first_name',$customer->first_name) }}" required></div>
                <div class="mf-col-4"><label class="mf-field-label">Middle name</label><input id="middle_name" class="mf-input" name="middle_name" value="{{ old('middle_name',$customer->middle_name) }}"></div>
                <div class="mf-col-4"><label class="mf-field-label">Last name</label><input id="last_name" class="mf-input" name="last_name" value="{{ old('last_name',$customer->last_name) }}" required></div>
                <div class="mf-col-2"><label class="mf-field-label">Gender</label><select id="gender" class="mf-input" name="gender"><option value="">Select</option>@foreach(['male','female','other'] as $v)<option value="{{ $v }}" @selected(old('gender',$customer->gender)===$v)>{{ ucfirst($v) }}</option>@endforeach</select></div>
                <div class="mf-col-3"><label class="mf-field-label">Date of birth</label><input id="date_of_birth" type="date" class="mf-input" name="date_of_birth" value="{{ old('date_of_birth',optional($customer->date_of_birth)->format('Y-m-d')) }}"></div>
                <div class="mf-col-5"><label class="mf-field-label">Customer photograph</label><input class="mf-input" type="file" name="photo" accept="image/png,image/jpeg,image/webp"><p class="mf-field-help">JPEG, PNG or WebP. Stored privately as part of the customer KYC record.</p></div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-section title="Contact & economic profile" description="Communication channels and information used to understand employment and repayment capacity.">
            <x-ui.form-grid>
                <div class="mf-col-3"><label class="mf-field-label">Primary phone</label><input id="phone" class="mf-input" name="phone" value="{{ old('phone',$customer->phone) }}" required></div>
                <div class="mf-col-3"><label class="mf-field-label">Alternative phone</label><input class="mf-input" name="alternative_phone" value="{{ old('alternative_phone',$customer->alternative_phone) }}"></div>
                <div class="mf-col-6"><label class="mf-field-label">Email</label><input type="email" class="mf-input" name="email" value="{{ old('email',$customer->email) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Occupation</label><input id="occupation" class="mf-input" name="occupation" value="{{ old('occupation',$customer->occupation) }}"></div>
                <div class="mf-col-4"><label class="mf-field-label">Employer / Business</label><input class="mf-input" name="employer_business" value="{{ old('employer_business',$customer->employer_business) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Monthly income</label><input type="number" step="0.01" min="0" class="mf-input" name="monthly_income" value="{{ old('monthly_income',$customer->monthly_income) }}"></div>
                <div class="mf-col-2"><label class="mf-field-label">Marital status</label><select id="marital_status" class="mf-input" name="marital_status"><option value="">Select</option>@foreach(['single','married','divorced','widowed','other'] as $v)<option value="{{ $v }}" @selected(old('marital_status',$customer->marital_status)===$v)>{{ ucfirst($v) }}</option>@endforeach</select></div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-section title="Residential address" description="Administrative location and optional GPS coordinates for field verification.">
            <x-ui.form-grid>
                <div class="mf-col-3"><label class="mf-field-label">Region</label><input id="region" class="mf-input" name="region" value="{{ old('region',$address?->region) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">District</label><input id="district" class="mf-input" name="district" value="{{ old('district',$address?->district) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Ward</label><input id="ward" class="mf-input" name="ward" value="{{ old('ward',$address?->ward) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">House number</label><input id="house_number" class="mf-input" name="house_number" value="{{ old('house_number',$address?->house_number) }}"></div>
                <div class="mf-col-6"><label class="mf-field-label">Street / Village</label><input id="street_village" class="mf-input" name="street_village" value="{{ old('street_village',$address?->street_village) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Latitude</label><input type="number" step="0.0000001" class="mf-input" name="latitude" value="{{ old('latitude',$address?->latitude) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Longitude</label><input type="number" step="0.0000001" class="mf-input" name="longitude" value="{{ old('longitude',$address?->longitude) }}"></div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-section title="Primary next of kin" description="The principal emergency or family contact associated with this customer.">
            <x-ui.form-grid>
                <div class="mf-col-4"><label class="mf-field-label">Full name</label><input class="mf-input" name="next_of_kin_name" value="{{ old('next_of_kin_name',$kin?->full_name) }}"></div>
                <div class="mf-col-2"><label class="mf-field-label">Relationship</label><input class="mf-input" name="next_of_kin_relationship" value="{{ old('next_of_kin_relationship',$kin?->relationship) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Phone</label><input class="mf-input" name="next_of_kin_phone" value="{{ old('next_of_kin_phone',$kin?->phone) }}"></div>
                <div class="mf-col-3"><label class="mf-field-label">Address</label><input class="mf-input" name="next_of_kin_address" value="{{ old('next_of_kin_address',$kin?->address) }}"></div>
            </x-ui.form-grid>
        </x-ui.form-section>

        <x-ui.form-actions>
            <a class="mf-btn" href="{{ $customer->exists?route('customers.show',$customer):route('customers.index') }}">Cancel</a>
            <button class="mf-btn mf-btn-primary">{{ $customer->exists?'Save changes':'Register customer' }}</button>
        </x-ui.form-actions>
    </form>
</x-ui.form-shell>

@if($ninLookupEnabled)
<script>
const ninLookupButton = document.getElementById('nin_lookup');
const ninResult = document.getElementById('nin_result');

ninLookupButton?.addEventListener('click', async () => {
    const nin = document.getElementById('nin').value.trim();
    if (!/^\d{20}$/.test(nin)) {
        ninResult.textContent = 'Enter a valid 20-digit NIN first.';
        return;
    }

    document.getElementById('identity_mode').value = 'with_nin';
    ninLookupButton.disabled = true;
    ninLookupButton.textContent = 'Fetching…';
    ninResult.textContent = 'Checking NIDA…';

    try {
        const response = await fetch(@json(route('customers.nin-lookup')), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': @json(csrf_token()),
            },
            body: JSON.stringify({nin}),
        });
        const payload = await response.json();

        if (!response.ok) {
            ninResult.textContent = payload.errors?.nin?.[0] || payload.message || 'NIDA lookup could not be completed.';
            return;
        }

        ninResult.textContent = payload.message || 'Lookup completed.';
        if (payload.found && payload.data) {
            const fields = ['first_name','middle_name','last_name','gender','date_of_birth','phone','occupation','marital_status','region','district','ward','street_village','house_number'];
            fields.forEach((key) => {
                const input = document.getElementById(key);
                if (input && payload.data[key]) input.value = payload.data[key];
            });
        }
    } catch (error) {
        ninResult.textContent = 'NIDA lookup is currently unavailable. You can continue with manual entry.';
    } finally {
        ninLookupButton.disabled = false;
        ninLookupButton.textContent = 'Fetch';
    }
});
</script>
@endif
@endsection
