@extends('layouts.app')

@section('title', 'Application 360 - '.$application->application_number)

@section('content')
@php
    $stageCode = $application->currentStage?->stage_code;
    $visitedStageIds = $application->stageHistory->pluck('to_stage_id')->unique();
    $contact = $application->customer?->contact;
    $activeInvoice = $application->invoiceItems->pluck('invoice')->filter()->sortByDesc('id')->first();
@endphp
<div class="space-y-5" x-data="{ tab: 'overview', slaOpen: false }">
    @if($errors->any())
        <div class="rounded-2xl border border-rose-200 bg-rose-50 p-4 text-xs text-rose-700"><strong class="block">This action needs attention</strong><ul class="mt-2 list-disc space-y-1 pl-5">@foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach</ul></div>
    @endif

    <section class="overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-sm">
        <div class="bg-gradient-to-r from-[#081a30] via-[#0d2b4b] to-[#123d65] p-5 text-white sm:p-6">
            <div class="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                <div>
                    <div class="flex flex-wrap items-center gap-2"><span class="rounded-lg bg-orange-500 px-2.5 py-1 text-[9px] font-bold uppercase tracking-wider">{{ $application->priority }}</span><span class="rounded-lg bg-white/10 px-2.5 py-1 text-[9px] font-bold uppercase">{{ str($application->status)->replace('_',' ') }}</span><span class="rounded-lg bg-white/10 px-2.5 py-1 text-[9px] font-bold uppercase">{{ $application->service?->authority?->code ?? 'UAE Service' }}</span></div>
                    <h1 class="mt-3 text-2xl font-bold">{{ $application->application_number }}</h1>
                    <p class="mt-1 text-xs text-slate-300">{{ $application->customer?->full_name_en }} · {{ $application->service?->name_en }} · {{ $application->branch?->name ?? 'All branches' }}</p>
                </div>
                <div class="grid grid-cols-2 gap-2 sm:grid-cols-4 xl:min-w-[600px]">
                    <div class="rounded-2xl bg-white/8 p-3"><small class="block text-[9px] uppercase text-slate-400">Current Stage</small><strong class="mt-1 block text-xs text-orange-300">{{ $application->currentStage?->stage_name_en ?? 'Not configured' }}</strong></div>
                    <div class="rounded-2xl bg-white/8 p-3"><small class="block text-[9px] uppercase text-slate-400">Assigned Staff</small><strong class="mt-1 block text-xs">{{ $application->assignedUser?->name ?? 'Role queue' }}</strong></div>
                    <div class="rounded-2xl bg-white/8 p-3"><small class="block text-[9px] uppercase text-slate-400">Payment</small><strong class="mt-1 block text-xs">{{ str($application->payment_status)->replace('_',' ')->title() }}</strong></div>
                    <div class="rounded-2xl bg-white/8 p-3"><small class="block text-[9px] uppercase text-slate-400">Stage SLA</small><strong class="mt-1 block text-xs {{ $application->sla_status === 'overdue' ? 'text-rose-300' : 'text-emerald-300' }}">{{ $application->sla_paused_at ? 'Paused' : ($application->due_at?->diffForHumans() ?? 'No deadline') }}</strong></div>
                </div>
            </div>
        </div>

        <div class="border-t border-slate-100 p-4 sm:p-5">
            <p class="mb-3 text-[9px] font-bold uppercase tracking-[.18em] text-slate-400">UAE Application Lifecycle</p>
            <div class="flex gap-2 overflow-x-auto pb-2">
                @foreach($allStages as $stage)
                    @php $isCurrent = $stage->id === $application->current_stage_id; $isVisited = $visitedStageIds->contains($stage->id); @endphp
                    <div class="min-w-[145px] rounded-2xl border p-3 {{ $isCurrent ? 'border-orange-300 bg-orange-50' : ($isVisited ? 'border-emerald-200 bg-emerald-50/60' : 'border-slate-200 bg-slate-50') }}">
                        <div class="flex items-center justify-between"><span class="flex h-6 w-6 items-center justify-center rounded-full text-[9px] font-bold {{ $isCurrent ? 'bg-orange-600 text-white' : ($isVisited ? 'bg-emerald-600 text-white' : 'bg-slate-200 text-slate-500') }}">{{ $loop->iteration }}</span>@if($stage->sla_minutes)<small class="text-[8px] text-slate-400">{{ $stage->sla_minutes }}m</small>@endif</div>
                        <strong class="mt-2 block text-[10px] text-[#0b1f38]">{{ $stage->stage_name_en }}</strong><small class="mt-1 block text-[8px] uppercase text-slate-400">{{ $stage->queue_role ? str($stage->queue_role)->replace('_',' ') : $stage->stage_type }}</small>
                    </div>
                @endforeach
            </div>
        </div>
    </section>

    <div class="grid gap-5 xl:grid-cols-[1fr_320px]">
        <main class="min-w-0 space-y-5">
            <nav class="flex gap-1 overflow-x-auto rounded-2xl border border-slate-200 bg-white p-2 text-[10px] font-bold shadow-sm">
                @foreach(['overview'=>'Overview','documents'=>'Documents','government'=>'Government','outputs'=>'Outputs & Delivery','finance'=>'Fees & Tasks','timeline'=>'Timeline'] as $key=>$label)
                    <button @click="tab='{{ $key }}'" :class="tab==='{{ $key }}' ? 'bg-[#0b1f38] text-white' : 'text-slate-500 hover:bg-slate-50'" class="whitespace-nowrap rounded-xl px-3 py-2">{{ $label }}</button>
                @endforeach
            </nav>

            <section x-show="tab==='overview'" class="space-y-5">
                <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <article class="erp-kpi-card"><div class="erp-kpi-icon bg-blue-50 text-blue-600">C</div><div><p>Customer</p><strong class="!text-sm">{{ $application->customer?->full_name_en }}</strong><small>{{ $contact?->primary_mobile ?? 'No mobile' }}</small></div></article>
                    <article class="erp-kpi-card"><div class="erp-kpi-icon bg-violet-50 text-violet-600">D</div><div><p>Documents</p><strong>{{ $application->documents->where('status','verified')->count() }}/{{ $application->documents->where('is_mandatory',true)->count() }}</strong><small>{{ str($application->document_status)->replace('_',' ')->title() }}</small></div></article>
                    <article class="erp-kpi-card"><div class="erp-kpi-icon bg-emerald-50 text-emerald-600">AED</div><div><p>Total Fee</p><strong>{{ number_format((float)$application->total_price,2) }}</strong><small>Government + service + VAT</small></div></article>
                    <article class="erp-kpi-card"><div class="erp-kpi-icon bg-orange-50 text-orange-600">T</div><div><p>Open Tasks</p><strong>{{ $application->workflowTasks->whereNotIn('status',['completed','cancelled'])->count() }}</strong><small>{{ $application->workflowTasks->count() }} workflow tasks</small></div></article>
                </div>

                <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Current Stage Instructions</h2><p>{{ $application->currentStage?->instructions ?? 'Follow the configured service workflow.' }}</p></div><span class="erp-status" data-status="{{ $application->sla_status }}">{{ str($application->sla_status)->replace('_',' ')->title() }}</span></div>
                    <div class="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                        @foreach([
                            ['Mandatory documents', !$application->currentStage?->requires_documents || $application->document_status === 'verified'],
                            ['Payment arrangement', !$application->currentStage?->requires_payment || in_array($application->payment_status,['paid','credit_account','corporate_credit']) || (float)$application->total_price <= 0],
                            ['Supervisor approval', !$application->currentStage?->requires_approval || $stageApproval?->status === 'approved'],
                            ['Government submission', !$application->currentStage?->requires_submission || $application->submissions->isNotEmpty()],
                            ['Approved output', !$application->currentStage?->requires_output || $application->outputs->where('status','ready')->isNotEmpty()],
                            ['Customer notification', !$application->currentStage?->requires_notification || $application->customer_notified_at],
                        ] as [$label,$ready])
                            <div class="flex items-center gap-2 rounded-xl border {{ $ready ? 'border-emerald-200 bg-emerald-50' : 'border-amber-200 bg-amber-50' }} p-3 text-[10px] font-bold"><span class="flex h-6 w-6 items-center justify-center rounded-full {{ $ready ? 'bg-emerald-600' : 'bg-amber-500' }} text-white">{{ $ready ? '✓' : '!' }}</span>{{ $label }}</div>
                        @endforeach
                    </div>
                </section>

                <section class="erp-panel border-blue-200 bg-blue-50/30"><div class="erp-panel-heading"><div><h2>Service Accountability</h2><p>Permanent staff attribution remains visible after every workflow handoff.</p></div><span class="erp-status" data-status="verified">Audit ready</span></div>
                    <div class="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                        <div class="rounded-xl bg-white p-4 shadow-sm"><p class="text-[8px] font-bold uppercase tracking-wider text-slate-400">Customer attended by</p><strong class="mt-2 block text-xs text-[#0b1f38]">{{ $application->attendedBy?->name ?? $application->creator?->name ?? 'Not recorded' }}</strong><small class="mt-1 block text-[9px] text-slate-400">Intake / front desk</small></div>
                        <div class="rounded-xl bg-white p-4 shadow-sm"><p class="text-[8px] font-bold uppercase tracking-wider text-slate-400">Service typed by</p><strong class="mt-2 block text-xs text-[#0b1f38]">{{ $application->typedByUser?->name ?? 'Typing not started' }}</strong><small class="mt-1 block text-[9px] text-slate-400">Responsible typist</small></div>
                        <div class="rounded-xl bg-white p-4 shadow-sm"><p class="text-[8px] font-bold uppercase tracking-wider text-slate-400">Typing started</p><strong class="mt-2 block text-xs text-[#0b1f38]">{{ $application->typing_started_at?->format('d M Y, h:i A') ?? 'Not started' }}</strong><small class="mt-1 block text-[9px] text-slate-400">Latest typing cycle</small></div>
                        <div class="rounded-xl bg-white p-4 shadow-sm"><p class="text-[8px] font-bold uppercase tracking-wider text-slate-400">Typing completed</p><strong class="mt-2 block text-xs text-[#0b1f38]">{{ $application->typing_completed_at?->format('d M Y, h:i A') ?? 'In progress' }}</strong><small class="mt-1 block text-[9px] text-slate-400">Submitted for quality check</small></div>
                    </div>
                </section>
            </section>

            <section x-show="tab==='documents'" class="erp-panel">
                <div class="erp-panel-heading"><div><h2>Application Document Checklist</h2><p>Mandatory evidence must be uploaded and verified before the workflow can advance.</p></div><span class="erp-status" data-status="{{ $application->document_status }}">{{ str($application->document_status)->replace('_',' ')->title() }}</span></div>
                <div class="mt-4 overflow-x-auto"><table class="erp-table"><thead><tr><th>Requirement</th><th>Source</th><th>File</th><th>Status</th><th>Controlled Action</th></tr></thead><tbody>
                    @forelse($application->documents as $document)
                        <tr><td><strong>{{ $document->display_name }}</strong><small>{{ $document->is_mandatory ? 'Mandatory' : 'Optional' }} · {{ $document->documentType?->code }}</small></td><td><strong>{{ str($document->source_entity)->replace('_',' ')->title() }}</strong><small>{{ $document->customer_document_id ? 'Linked vault version' : 'Application upload' }}</small></td><td><strong>{{ $document->attachment_path || $document->customer_document_id ? 'Available' : 'Missing' }}</strong>@if($document->rejection_reason)<small class="text-rose-600">{{ $document->rejection_reason }}</small>@endif</td><td><span class="erp-status" data-status="{{ $document->status }}">{{ ucfirst($document->status) }}</span></td><td>
                            @if(auth()->user()->hasPermission('documents.upload'))
                                <details><summary class="cursor-pointer text-[10px] font-bold text-orange-600">Upload / Review</summary><div class="mt-2 min-w-[270px] space-y-2">
                                    <form method="POST" enctype="multipart/form-data" action="{{ route('app.applications.documents.upload',$application->id) }}" class="flex gap-1">@csrf<input type="hidden" name="application_document_id" value="{{ $document->id }}"><input required type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.webp" class="erp-input !py-1"><button class="rounded-lg bg-slate-900 px-2 text-[9px] font-bold text-white">Upload</button></form>
                                    <form method="POST" action="{{ route('app.applications.documents.review',[$application->id,$document->id]) }}" class="flex gap-1">@csrf<select name="status" class="erp-select-compact"><option value="verified">Verify</option><option value="rejected">Reject</option><option value="exception">Exception</option></select><input name="rejection_reason" placeholder="Reason if rejected" class="erp-input !py-1"><button class="rounded-lg bg-orange-600 px-2 text-[9px] font-bold text-white">Save</button></form>
                                </div></details>
                            @else<span class="text-[9px] text-slate-400">Read only</span>@endif
                        </td></tr>
                    @empty
                        <tr><td colspan="5"><div class="erp-empty"><span>✓</span><strong>No document rules configured</strong><p>This service can pass document verification without attachments.</p></div></td></tr>
                    @endforelse
                </tbody></table></div>
            </section>

            <section x-show="tab==='government'" class="space-y-5">
                @if($stageCode === 'GOVERNMENT_SUBMISSION' && auth()->user()->hasPermission('applications.submit'))
                    <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Record Government Submission</h2><p>Every portal attempt is immutable and receives its own attempt number.</p></div><span class="erp-status" data-status="submitted">Attempt {{ $application->submissions->count()+1 }}</span></div><form method="POST" enctype="multipart/form-data" action="{{ route('app.applications.submission',$application->id) }}" class="mt-4 grid gap-3 sm:grid-cols-2">@csrf
                        <input required name="authority_code" value="{{ $application->service?->authority?->code }}" placeholder="Authority code *" class="erp-input"><input name="portal_name" placeholder="Portal name" class="erp-input"><input required name="government_reference" placeholder="Government reference *" class="erp-input"><input name="request_number" placeholder="Request number" class="erp-input"><input name="transaction_number" placeholder="Transaction number" class="erp-input"><input name="receipt_number" placeholder="Government receipt" class="erp-input"><input type="number" min="0" step="0.01" name="gov_fee_paid" placeholder="Government fee paid" class="erp-input"><input type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.webp" class="erp-input"><textarea name="remarks" rows="2" placeholder="Portal remarks" class="erp-input sm:col-span-2"></textarea><button class="rounded-xl bg-orange-600 py-3 text-xs font-bold text-white sm:col-span-2">Submit Attempt & Move to Government Processing</button>
                    </form></section>
                @endif

                @if($stageCode === 'GOVERNMENT_PROCESSING')
                    <section class="grid gap-3 md:grid-cols-3">
                        @if(auth()->user()->hasPermission('applications.approve'))<form method="POST" action="{{ route('app.applications.approval',$application->id) }}" class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4">@csrf<strong class="text-xs text-emerald-800">Government Approved</strong><textarea name="remarks" rows="2" placeholder="Approval remarks" class="erp-input mt-3"></textarea><button class="mt-2 w-full rounded-lg bg-emerald-600 py-2 text-[10px] font-bold text-white">Record Approval</button></form>@endif
                        @if(auth()->user()->hasPermission('applications.edit'))<form method="POST" action="{{ route('app.applications.return',$application->id) }}" class="rounded-2xl border border-amber-200 bg-amber-50 p-4">@csrf<strong class="text-xs text-amber-800">Returned for Correction</strong><textarea required name="reason" rows="2" placeholder="Authority reason and required correction *" class="erp-input mt-3"></textarea><button class="mt-2 w-full rounded-lg bg-amber-600 py-2 text-[10px] font-bold text-white">Record Return</button></form>@endif
                        @if(auth()->user()->hasPermission('applications.reject'))<form method="POST" action="{{ route('app.applications.rejection',$application->id) }}" class="rounded-2xl border border-rose-200 bg-rose-50 p-4">@csrf<strong class="text-xs text-rose-800">Government Rejected</strong><textarea required name="reason" rows="2" placeholder="Structured rejection reason *" class="erp-input mt-3"></textarea><button class="mt-2 w-full rounded-lg bg-rose-600 py-2 text-[10px] font-bold text-white">Record Rejection</button></form>@endif
                    </section>
                @endif

                <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Government Attempt History</h2><p>Returns and resubmissions never overwrite earlier attempts.</p></div><span class="text-[10px] font-bold text-slate-400">{{ $application->submissions->count() }} attempt(s)</span></div><div class="mt-4 overflow-x-auto"><table class="erp-table"><thead><tr><th>Attempt</th><th>Authority / Portal</th><th>References</th><th>Government Fee</th><th>Status</th><th>Response</th></tr></thead><tbody>
                    @forelse($application->submissions as $submission)
                        <tr><td><strong>#{{ $submission->attempt_number }}</strong><small>{{ $submission->created_at->format('d M Y, h:i A') }}</small></td><td><strong>{{ $submission->authority_code }}</strong><small>{{ $submission->portal_name }}</small></td><td><strong>{{ $submission->government_reference }}</strong><small>{{ $submission->request_number ?: $submission->transaction_number }}</small></td><td><strong>AED {{ number_format((float)$submission->gov_fee_paid,2) }}</strong><small>{{ $submission->receipt_number }}</small></td><td><span class="erp-status" data-status="{{ $submission->status }}">{{ ucfirst($submission->status) }}</span></td><td><strong>{{ $submission->response_at?->format('d M Y, h:i A') ?? 'Awaiting response' }}</strong>@if($submission->return_reason)<small class="text-amber-600">{{ $submission->return_reason }}</small>@endif</td></tr>
                    @empty<tr><td colspan="6"><div class="erp-empty"><span>G</span><strong>No submission attempts</strong><p>Advance to Government Submission to record the first attempt.</p></div></td></tr>@endforelse
                </tbody></table></div></section>
            </section>

            <section x-show="tab==='outputs'" class="space-y-5">
                @if(in_array($stageCode,['GOVERNMENT_APPROVED','OUTPUT_READY']) && auth()->user()->hasPermission('documents.upload'))
                    <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Upload Approved Government Output</h2><p>Store the exact delivered permit, visa, form, license or official receipt.</p></div></div><form method="POST" enctype="multipart/form-data" action="{{ route('app.applications.outputs.store',$application->id) }}" class="mt-4 grid gap-3 sm:grid-cols-2">@csrf<input required name="document_name" placeholder="Output document name *" class="erp-input"><select required name="output_type" class="erp-input"><option value="government_output">Government output</option><option value="visa">Visa</option><option value="permit">Permit</option><option value="work_permit">Work permit</option><option value="emirates_id_form">Emirates ID form</option><option value="license">License</option><option value="government_receipt">Government receipt</option><option value="other">Other</option></select><input name="reference_number" placeholder="Output reference" class="erp-input"><input required type="file" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.webp" class="erp-input"><input type="date" name="issue_date" class="erp-input"><input type="date" name="expiry_date" class="erp-input"><button class="rounded-xl bg-orange-600 py-3 text-xs font-bold text-white sm:col-span-2">Upload Secure Output</button></form></section>
                @endif
                <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Output Register</h2><p>Customer-visible final records attached to this application.</p></div><span class="erp-status" data-status="{{ $application->output_status }}">{{ ucfirst($application->output_status) }}</span></div><div class="mt-4 overflow-x-auto"><table class="erp-table"><thead><tr><th>Document</th><th>Type</th><th>Reference</th><th>Validity</th><th>Status</th></tr></thead><tbody>@forelse($application->outputs as $output)<tr><td><strong>{{ $output->document_name }}</strong><small>By {{ $output->uploader?->name }} · {{ $output->created_at->diffForHumans() }}</small></td><td><strong>{{ str($output->output_type)->replace('_',' ')->title() }}</strong></td><td><strong>{{ $output->reference_number ?: 'Not recorded' }}</strong></td><td><strong>{{ $output->issue_date?->format('d M Y') ?? '—' }}</strong><small>{{ $output->expiry_date ? 'Expires '.$output->expiry_date->format('d M Y') : 'No expiry' }}</small></td><td><span class="erp-status" data-status="{{ $output->status }}">{{ ucfirst($output->status) }}</span></td></tr>@empty<tr><td colspan="5"><div class="erp-empty"><span>O</span><strong>No approved outputs uploaded</strong><p>Outputs become available after government approval.</p></div></td></tr>@endforelse</tbody></table></div></section>

                @if(in_array($stageCode,['OUTPUT_READY','CUSTOMER_NOTIFICATION']) && auth()->user()->hasPermission('communications.manage'))
                    <section class="grid gap-5 lg:grid-cols-2">
                        <div class="erp-panel"><div class="erp-panel-heading"><div><h2>Notify Customer</h2><p>Log the channel and exact collection message.</p></div></div><form method="POST" action="{{ route('app.applications.notify',$application->id) }}" class="mt-4 space-y-3">@csrf<select name="channel" class="erp-input"><option value="whatsapp">WhatsApp</option><option value="sms">SMS</option><option value="email">Email</option><option value="phone">Phone call</option></select><input name="recipient" placeholder="Recipient (uses customer contact if empty)" class="erp-input"><textarea required name="message" rows="3" class="erp-input">Your application {{ $application->application_number }} is ready for collection. Please bring valid identification.</textarea><button class="w-full rounded-xl bg-emerald-600 py-3 text-xs font-bold text-white">Record Customer Notification</button></form></div>
                        @if($stageCode==='CUSTOMER_NOTIFICATION')<div class="erp-panel"><div class="erp-panel-heading"><div><h2>Secure Delivery Acknowledgement</h2><p>Identify the recipient before closing the application.</p></div></div><form method="POST" action="{{ route('app.applications.deliver',$application->id) }}" class="mt-4 grid gap-3 sm:grid-cols-2">@csrf<select name="delivery_method" class="erp-input"><option value="counter_collection">Counter collection</option><option value="courier">Courier</option><option value="email">Email</option><option value="digital_portal">Digital portal</option></select><input required name="recipient_name" placeholder="Recipient name *" class="erp-input"><input name="recipient_mobile" placeholder="Recipient mobile" class="erp-input"><input name="identification_type" placeholder="ID type" class="erp-input"><input name="identification_reference" placeholder="Masked ID reference" class="erp-input"><textarea required name="acknowledgement" rows="2" placeholder="Acknowledgement / handover notes *" class="erp-input sm:col-span-2"></textarea><button class="rounded-xl bg-[#0b1f38] py-3 text-xs font-bold text-white sm:col-span-2">Acknowledge Delivery & Close</button></form></div>@endif
                    </section>
                @endif
            </section>

            <section x-show="tab==='finance'" class="space-y-5">
                <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Immutable Fee Snapshot</h2><p>Government money remains separated from typing-center revenue.</p></div>@if(auth()->user()->hasPermission('payments.view'))<a href="{{ $activeInvoice ? route('app.billing.invoices.show',$activeInvoice->id) : route('app.billing.pos',['q'=>$application->application_number]) }}">{{ $activeInvoice ? 'Open Invoice' : 'Open POS' }}</a>@endif</div><div class="mt-4 overflow-x-auto"><table class="erp-table"><thead><tr><th>Fee</th><th>Classification</th><th>Tax</th><th>Amount</th></tr></thead><tbody>@foreach($application->feeItems as $fee)<tr><td><strong>{{ $fee->name_en }}</strong><small>{{ $fee->fee_code }}</small></td><td><strong>{{ str($fee->revenue_classification)->replace('_',' ')->title() }}</strong></td><td><strong>{{ str($fee->tax_behavior)->replace('_',' ')->title() }}</strong></td><td><strong>AED {{ number_format((float)$fee->amount,2) }}</strong></td></tr>@endforeach<tr class="bg-slate-50"><td colspan="3"><strong>Total</strong></td><td><strong class="text-orange-600">AED {{ number_format((float)$application->total_price,2) }}</strong></td></tr></tbody></table></div></section>
                <section class="erp-panel"><div class="erp-panel-heading"><div><h2>Workflow Tasks</h2><p>Role handoffs create traceable operational assignments.</p></div><a href="{{ route('app.tasks.index') }}">Task Center</a></div><div class="mt-4 overflow-x-auto"><table class="erp-table"><thead><tr><th>Task</th><th>Assigned</th><th>Due</th><th>Status</th></tr></thead><tbody>@forelse($application->workflowTasks as $task)<tr><td><strong>{{ $task->task_number }} · {{ $task->title }}</strong><small>{{ $task->description }}</small></td><td><strong>{{ $task->assignedUser?->name ?? 'Role queue' }}</strong></td><td><strong>{{ $task->due_at?->format('d M Y, h:i A') ?? 'No deadline' }}</strong></td><td><span class="erp-status" data-status="{{ $task->status }}">{{ str($task->status)->replace('_',' ')->title() }}</span></td></tr>@empty<tr><td colspan="4"><div class="erp-empty"><span>T</span><strong>No workflow tasks yet</strong><p>The next role handoff creates an operational task.</p></div></td></tr>@endforelse</tbody></table></div></section>
            </section>

            <section x-show="tab==='timeline'" class="erp-panel"><div class="erp-panel-heading"><div><h2>Complete Application Timeline</h2><p>Stage movements, assignments and government actions are immutable.</p></div></div><div class="mt-5 space-y-4 border-l-2 border-slate-100 pl-5">
                @foreach($application->stageHistory->sortByDesc('created_at') as $history)<article class="relative rounded-2xl border border-slate-200 bg-slate-50 p-4 before:absolute before:-left-[27px] before:top-5 before:h-3 before:w-3 before:rounded-full before:bg-orange-500"><div class="flex flex-wrap items-start justify-between gap-2"><div><strong class="text-xs text-[#0b1f38]">{{ $history->action_name }}</strong><p class="mt-1 text-[10px] text-slate-500">{{ $history->fromStage?->stage_name_en ?? 'Application created' }} → {{ $history->toStage?->stage_name_en }}</p></div><small class="text-[9px] text-slate-400">{{ $history->created_at->format('d M Y, h:i A') }}</small></div><p class="mt-2 text-[10px] text-slate-500">{{ $history->remarks }}</p><small class="mt-2 block text-[9px] font-bold text-slate-400">By {{ $history->performedByUser?->name }}</small></article>@endforeach
            </div></section>
        </main>

        <aside class="space-y-5">
            <section class="erp-panel">
                <div class="erp-panel-heading"><div><h2>Next Actions</h2><p>Only permitted direct transitions are shown.</p></div></div>
                <div class="mt-4 space-y-3">
                    @forelse($availableTransitions as $transition)
                        <div class="rounded-2xl border {{ $transition['ready'] ? 'border-emerald-200 bg-emerald-50' : 'border-amber-200 bg-amber-50' }} p-3">
                            <strong class="block text-xs text-[#0b1f38]">{{ $transition['action_name_en'] }}</strong><small class="mt-1 block text-[9px] text-slate-500">Next: {{ $transition['to_stage']?->stage_name_en }}</small>
                            @if($transition['ready'])
                                <form method="POST" action="{{ route('app.applications.transition',$application->id) }}" class="mt-3 space-y-2">@csrf<input type="hidden" name="target_stage_id" value="{{ $transition['to_stage_id'] }}"><input name="remarks" placeholder="Handover remarks" class="erp-input"><button class="w-full rounded-lg bg-[#0b1f38] py-2 text-[10px] font-bold text-white">Complete & Handoff</button></form>
                            @else
                                <ul class="mt-2 space-y-1">@foreach($transition['blockers'] as $blocker)<li class="text-[9px] text-amber-700">• {{ $blocker }}</li>@endforeach</ul>
                            @endif
                        </div>
                    @empty<div class="erp-empty !p-4"><span>✓</span><strong>No direct action</strong><p>Use the stage-specific form or wait for the assigned role.</p></div>@endforelse
                </div>
            </section>

            @if($stageApproval)
                <section class="rounded-2xl border {{ $stageApproval->status==='approved' ? 'border-emerald-200 bg-emerald-50' : 'border-violet-200 bg-violet-50' }} p-4"><p class="text-[9px] font-bold uppercase text-slate-500">Supervisor Approval</p><strong class="mt-1 block text-xs">{{ $stageApproval->approval_number }}</strong><span class="erp-status mt-2" data-status="{{ $stageApproval->status }}">{{ ucfirst($stageApproval->status) }}</span>@if($stageApproval->status==='pending' && auth()->user()->hasPermission('approvals.manage'))<a href="{{ route('app.tasks.index',['approval_status'=>'pending']) }}" class="mt-3 block text-[10px] font-bold text-violet-700">Review in Approval Center →</a>@endif</section>
            @endif

            <section class="erp-panel"><div class="erp-panel-heading"><div><h2>SLA Control</h2><p>Pauses require an operational reason.</p></div></div>
                @if($application->sla_paused_at)
                    <div class="mt-4 rounded-xl bg-amber-50 p-3 text-[10px] text-amber-800"><strong>Paused: {{ str($application->sla_pause_reason)->replace('_',' ')->title() }}</strong><small class="mt-1 block">Since {{ $application->sla_paused_at->diffForHumans() }}</small></div>
                    @if(auth()->user()->hasPermission('applications.edit'))<form method="POST" action="{{ route('app.applications.sla.resume',$application->id) }}" class="mt-3 space-y-2">@csrf<input name="remarks" placeholder="Resume notes" class="erp-input"><button class="w-full rounded-lg bg-emerald-600 py-2 text-[10px] font-bold text-white">Resume SLA</button></form>@endif
                @elseif(auth()->user()->hasPermission('applications.edit'))
                    <form method="POST" action="{{ route('app.applications.sla.pause',$application->id) }}" class="mt-4 space-y-2">@csrf<select name="reason" class="erp-input"><option value="waiting_customer">Waiting customer</option><option value="documents_pending">Documents pending</option><option value="payment_pending">Payment pending</option><option value="government_delay">Government delay</option><option value="portal_down">Portal down</option></select><input name="remarks" placeholder="Reason details" class="erp-input"><button class="w-full rounded-lg border border-slate-200 bg-white py-2 text-[10px] font-bold text-slate-700">Pause SLA</button></form>
                @endif
            </section>

            @if(auth()->user()->hasPermission('applications.edit'))<section class="erp-panel"><div class="erp-panel-heading"><div><h2>Add Timeline Note</h2><p>Internal or customer-visible context.</p></div></div><form method="POST" action="{{ route('app.applications.note',$application->id) }}" class="mt-4 space-y-2">@csrf<textarea required name="note_text" rows="3" placeholder="Note *" class="erp-input"></textarea><label class="flex items-center gap-2 text-[10px] text-slate-600"><input type="checkbox" name="is_customer_visible" value="1"> Customer visible</label><button class="w-full rounded-lg bg-orange-600 py-2 text-[10px] font-bold text-white">Add Note</button></form></section>@endif
        </aside>
    </div>
</div>
@endsection
