@extends('layouts.app')

@section('title', 'New Application')

@section('content')
<div class="space-y-5" x-data="applicationDesk()">
    @include('tenant.partials.typist-page-nav')

    <section class="overflow-hidden rounded-[28px] border border-orange-100 bg-gradient-to-br from-white via-orange-50 to-sky-50 p-6 shadow-sm sm:p-8">
        <div class="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">
            <div>
                <span class="inline-flex rounded-full bg-orange-100 px-3 py-1 text-[11px] font-bold uppercase tracking-[0.18em] text-orange-700">Guided intake desk</span>
                <h1 class="mt-3 text-2xl font-bold tracking-tight text-slate-950 sm:text-3xl">Create a new application</h1>
                <p class="mt-2 max-w-2xl text-sm leading-6 text-slate-600">Find the customer, choose the government service and review the fee before opening the job.</p>
            </div>
            <div class="grid grid-cols-3 gap-2 text-center">
                @foreach([['01','Customer'], ['02','Service'], ['03','Review']] as [$number, $label])
                    <div class="rounded-2xl border border-white bg-white/90 px-4 py-3 shadow-sm">
                        <strong class="block text-sm text-orange-600">{{ $number }}</strong>
                        <span class="text-[10px] font-bold uppercase tracking-wider text-slate-500">{{ $label }}</span>
                    </div>
                @endforeach
            </div>
        </div>
    </section>

    @if($errors->any())
        <div class="rounded-2xl border border-red-200 bg-red-50 px-5 py-4 text-sm text-red-700">
            <strong>Please check the application details.</strong>
            <ul class="mt-2 list-disc space-y-1 pl-5">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul>
        </div>
    @endif

    <form method="POST" action="{{ route('app.applications.store') }}" class="grid gap-5 xl:grid-cols-[minmax(0,1fr)_360px]">
        @csrf
        <input type="hidden" name="customer_id" :value="selectedCustomer?.id || ''">
        <input type="hidden" name="company_id" :value="applicantType === 'corporate_employee' ? companyId : ''">

        <div class="space-y-5">
            <section class="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
                <div class="mb-5 flex items-start gap-3">
                    <span class="grid h-10 w-10 shrink-0 place-items-center rounded-2xl bg-sky-100 text-sm font-extrabold text-sky-700">01</span>
                    <div><h2 class="font-bold text-slate-950">Customer lookup</h2><p class="mt-1 text-xs text-slate-500">Search by name, mobile, customer code, passport or Emirates ID.</p></div>
                </div>

                <template x-if="!selectedCustomer">
                    <div class="relative">
                        <div class="flex gap-2">
                            <div class="relative flex-1">
                                <svg class="absolute left-4 top-3.5 h-5 w-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-width="2" d="m21 21-4.4-4.4m2.4-5.1a7.5 7.5 0 1 1-15 0 7.5 7.5 0 0 1 15 0Z"/></svg>
                                <input x-model="searchQuery" @input.debounce.350ms="searchCustomers" type="search" class="w-full rounded-2xl border-slate-200 bg-slate-50 py-3 pl-12 pr-4 text-sm focus:border-orange-400 focus:ring-orange-200" placeholder="Start typing at least 3 characters">
                            </div>
                            <a href="{{ route('app.customers.create') }}" class="inline-flex items-center rounded-2xl border border-orange-200 bg-orange-50 px-4 text-xs font-bold text-orange-700 hover:bg-orange-100">New customer</a>
                        </div>
                        <div x-show="loading" class="mt-3 text-xs font-semibold text-sky-600">Searching customer records...</div>
                        <div x-show="results.length" x-transition class="absolute z-30 mt-2 max-h-72 w-full overflow-y-auto rounded-2xl border border-slate-200 bg-white p-2 shadow-xl">
                            <template x-for="customer in results" :key="customer.id">
                                <button type="button" @click="chooseCustomer(customer)" class="flex w-full items-center justify-between rounded-xl px-4 py-3 text-left hover:bg-sky-50">
                                    <span><strong class="block text-sm text-slate-900" x-text="customer.full_name_en"></strong><small class="mt-1 block text-slate-500" x-text="(customer.contact?.primary_mobile || 'No mobile') + ' · ' + customer.customer_code"></small></span>
                                    <span class="rounded-full bg-sky-100 px-2 py-1 text-[10px] font-bold text-sky-700">Select</span>
                                </button>
                            </template>
                        </div>
                        <p x-show="searched && !loading && !results.length" class="mt-3 rounded-xl bg-amber-50 px-4 py-3 text-xs text-amber-700">No matching customer found. Create a customer profile to continue.</p>
                    </div>
                </template>

                <template x-if="selectedCustomer">
                    <div class="flex flex-col gap-4 rounded-2xl border border-emerald-200 bg-emerald-50/70 p-4 sm:flex-row sm:items-center sm:justify-between">
                        <div class="flex items-center gap-3">
                            <span class="grid h-12 w-12 place-items-center rounded-2xl bg-white text-lg font-bold text-emerald-700 shadow-sm" x-text="initials(selectedCustomer.full_name_en)"></span>
                            <div><div class="flex items-center gap-2"><strong class="text-sm text-slate-950" x-text="selectedCustomer.full_name_en"></strong><span x-show="selectedCustomer.is_vip" class="rounded-full bg-orange-100 px-2 py-0.5 text-[9px] font-bold text-orange-700">VIP</span></div><p class="mt-1 text-xs text-slate-600" x-text="customerMobile(selectedCustomer) + ' · ' + selectedCustomer.customer_code"></p></div>
                        </div>
                        <button type="button" @click="clearCustomer" class="rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-bold text-slate-600 hover:text-orange-600">Change customer</button>
                    </div>
                </template>
            </section>

            <section class="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6">
                <div class="mb-5 flex items-start gap-3">
                    <span class="grid h-10 w-10 shrink-0 place-items-center rounded-2xl bg-orange-100 text-sm font-extrabold text-orange-700">02</span>
                    <div><h2 class="font-bold text-slate-950">Service and processing</h2><p class="mt-1 text-xs text-slate-500">Select the request type and processing priority.</p></div>
                </div>
                <div class="grid gap-4 md:grid-cols-2">
                    <label class="text-xs font-bold text-slate-700 md:col-span-2">Government service
                        <select name="service_id" x-model="serviceId" @change="loadFees" required class="mt-2 w-full rounded-2xl border-slate-200 bg-slate-50 px-4 py-3 text-sm focus:border-orange-400 focus:ring-orange-200">
                            <option value="">Choose a service</option>
                            @foreach($services as $service)
                                <option value="{{ $service->id }}">{{ $service->name_en }}{{ $service->authority ? ' — '.$service->authority->name_en : '' }}</option>
                            @endforeach
                        </select>
                    </label>
                    <label class="text-xs font-bold text-slate-700">Applicant type
                        <select name="applicant_type" x-model="applicantType" @change="if (applicantType !== 'corporate_employee') companyId = ''; loadFees()" class="mt-2 w-full rounded-2xl border-slate-200 bg-slate-50 px-4 py-3 text-sm focus:border-orange-400 focus:ring-orange-200">
                            <option value="individual">Individual</option><option value="family_member">Family member</option><option value="corporate_employee">Corporate employee</option>
                        </select>
                    </label>
                    <label class="text-xs font-bold text-slate-700">Priority
                        <select name="priority" x-model="priority" @change="loadFees" class="mt-2 w-full rounded-2xl border-slate-200 bg-slate-50 px-4 py-3 text-sm focus:border-orange-400 focus:ring-orange-200">
                            <option value="normal">Normal</option><option value="high">High</option><option value="urgent">Urgent</option><option value="vip">VIP</option>
                        </select>
                    </label>
                    <label x-show="applicantType === 'corporate_employee'" x-transition class="text-xs font-bold text-slate-700 md:col-span-2">Corporate account
                        <select x-model="companyId" @change="loadFees" class="mt-2 w-full rounded-2xl border-slate-200 bg-slate-50 px-4 py-3 text-sm focus:border-orange-400 focus:ring-orange-200">
                            <option value="">Choose company</option>@foreach($companies as $company)<option value="{{ $company->id }}">{{ $company->name_en ?? $company->name }}</option>@endforeach
                        </select>
                    </label>
                    <label class="text-xs font-bold text-slate-700 md:col-span-2">Desk notes
                        <textarea name="notes" rows="3" class="mt-2 w-full rounded-2xl border-slate-200 bg-slate-50 px-4 py-3 text-sm focus:border-orange-400 focus:ring-orange-200" placeholder="Optional notes for the typist and processing team">{{ old('notes') }}</textarea>
                    </label>
                </div>
            </section>
        </div>

        <aside class="h-fit rounded-3xl border border-slate-200 bg-white p-5 shadow-sm xl:sticky xl:top-24">
            <div class="flex items-center justify-between"><div><span class="text-[10px] font-bold uppercase tracking-[0.16em] text-orange-600">Live calculation</span><h2 class="mt-1 font-bold text-slate-950">Fee summary</h2></div><span x-show="feeLoading" class="text-xs text-sky-600">Updating...</span></div>
            <div class="mt-5 space-y-3 rounded-2xl bg-slate-50 p-4 text-sm">
                <div class="flex justify-between text-slate-600"><span>Government fee</span><strong class="text-slate-900" x-text="money(fees.gov_fee)"></strong></div>
                <div class="flex justify-between text-slate-600"><span>Typing fee</span><strong class="text-slate-900" x-text="money(fees.typing_fee)"></strong></div>
                <div class="flex justify-between text-slate-600"><span>Service charge</span><strong class="text-slate-900" x-text="money(fees.service_charge)"></strong></div>
                <div class="flex justify-between text-slate-600"><span>VAT</span><strong class="text-slate-900" x-text="money(fees.vat_amount)"></strong></div>
                <div class="border-t border-slate-200 pt-3"><div class="flex items-end justify-between"><span class="font-bold text-slate-900">Total payable</span><strong class="text-xl text-orange-600" x-text="money(fees.total_price)"></strong></div></div>
            </div>
            <div class="mt-4 rounded-2xl border border-sky-100 bg-sky-50 p-4 text-xs leading-5 text-sky-800">The application records the staff member who attended the customer. Typist ownership is recorded when the job is claimed or processed.</div>
            <button :disabled="!selectedCustomer || !serviceId || feeLoading" class="mt-5 w-full rounded-2xl bg-gradient-to-r from-orange-500 to-orange-600 px-5 py-3.5 text-sm font-bold text-white shadow-lg shadow-orange-100 transition hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-50">Create application</button>
            <a href="{{ route('app.work_queue') }}" class="mt-2 block rounded-2xl px-5 py-3 text-center text-xs font-bold text-slate-500 hover:bg-slate-50">Cancel and return to queue</a>
        </aside>
    </form>
</div>

<script>
function applicationDesk() {
    return {
        searchQuery: '', results: [], searched: false, loading: false,
        selectedCustomer: @json($selectedCustomer), serviceId: @json(old('service_id', '')),
        priority: @json(old('priority', 'normal')), applicantType: @json(old('applicant_type', 'individual')),
        companyId: @json(old('company_id', '')), feeLoading: false,
        fees: { gov_fee: 0, typing_fee: 0, service_charge: 0, vat_amount: 0, total_price: 0 },
        async searchCustomers() {
            if (this.searchQuery.trim().length < 3) { this.results = []; this.searched = false; return; }
            this.loading = true;
            try { const response = await fetch(`{{ route('app.applications.search_customer') }}?query=${encodeURIComponent(this.searchQuery)}`); const data = await response.json(); this.results = data.customers || []; this.searched = true; } finally { this.loading = false; }
        },
        chooseCustomer(customer) { this.selectedCustomer = customer; this.results = []; this.searchQuery = ''; },
        clearCustomer() { this.selectedCustomer = null; this.searched = false; },
        customerMobile(customer) { return customer.primary_mobile || customer.contact?.primary_mobile || 'No mobile'; },
        initials(name) { return (name || 'C').split(' ').slice(0, 2).map(part => part[0]).join('').toUpperCase(); },
        money(value) { return `AED ${Number(value || 0).toLocaleString('en-AE', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`; },
        async loadFees() {
            if (!this.serviceId) { this.fees = { gov_fee: 0, typing_fee: 0, service_charge: 0, vat_amount: 0, total_price: 0 }; return; }
            this.feeLoading = true;
            try {
                const response = await fetch(`{{ route('app.applications.calculate_fees') }}`, { method: 'POST', headers: {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}'}, body: JSON.stringify({ service_id: this.serviceId, priority: this.priority, company_id: this.applicantType === 'corporate_employee' ? this.companyId : null }) });
                if (response.ok) this.fees = await response.json();
            } finally { this.feeLoading = false; }
        }
    }
}
</script>
@endsection
