<x-admin-layout title="Detalle de inscripción">
<div x-data="applicationDetail('{{ $application->folio }}')">
    <div class="page-heading">
        <div>
            <a href="{{ route('admin.applications.index') }}" class="back-link mb-2"><i data-lucide="arrow-left"></i> Volver a inscripciones</a>
            <span class="eyebrow">{{ $application->folio }}</span>
            <h1>{{ $application->full_name }}</h1>
            <p>{{ ['particular' => 'Socio Particular', 'radomiro' => 'División Radomiro Tomic', 'gabriela' => 'División Gabriela Mistral', 'club_golf' => 'Socios Club de Golf', 'enaex' => 'Enaex'][$application->type] ?? $application->type }}</p>
        </div>
        <div class="d-flex flex-wrap align-items-center gap-2">
            <a class="btn btn-light" href="{{ route('admin.applications.edit', $application) }}"><i data-lucide="pencil"></i> Editar formulario</a>
            @if(in_array($application->type, ['particular', 'radomiro', 'gabriela', 'club_golf'], true))
                <button type="button" class="btn btn-light" @click="openPreview"><i data-lucide="eye"></i> Vista previa</button>
                <a class="btn btn-copper" href="{{ route('admin.applications.pdf', $application) }}"><i data-lucide="file-down"></i> Descargar PDF</a>
            @endif
            @if(in_array($application->type, ['radomiro', 'gabriela'], true))
                <button type="button" class="btn btn-outline-copper" data-bs-toggle="modal" data-bs-target="#payrollAuthorizationModal"><i data-lucide="badge-dollar-sign"></i> Autorización descuento</button>
            @endif
            <span class="status-badge status-{{ $application->status }}">{{ ['pending'=>'Pendiente','review'=>'En revisión','approved'=>'Aprobada','rejected'=>'Rechazada'][$application->status] }}</span>
        </div>
    </div>

    @if(session('status'))<div class="alert alert-success">{{ session('status') }}</div>@endif

    <div class="row g-4">
        <div class="col-xl-8">
            <div class="admin-panel">
                @php($personalFields = ['full_name'=>'Nombre completo','rut'=>'RUT','birth_date'=>'Fecha de nacimiento','email'=>'Correo','phone'=>'Teléfono','address'=>'Dirección'] + ($application->type === 'particular' ? [] : ['delivery_address'=>'Dirección de entrega']))
                @php($workFields = $application->type === 'particular' ? ['profession'=>'Profesión','company'=>'Empresa','job_title'=>'Cargo','work_phone'=>'Teléfono laboral','work_email'=>'Correo laboral'] : ['profession'=>'Profesión','work_area'=>'Área de trabajo','superintendency'=>'Superintendencia','work_phone'=>'Teléfono laboral','management'=>'Gerencia','work_email'=>'Correo laboral'])
                @foreach(['Datos personales'=>$personalFields,'Datos laborales'=>$workFields] as $title=>$fields)
                    <h2 class="detail-title">{{ $title }}</h2>
                    <div class="detail-grid">
                        @foreach($fields as $key=>$label)<div><small>{{ $label }}</small><strong>{{ data_get($application->data,$key) ?: '—' }}</strong></div>@endforeach
                    </div>
                @endforeach

                <h2 class="detail-title">Cargas familiares</h2>
                <div class="table-responsive"><table class="table table-sm"><thead><tr><th>Nombre</th><th>RUT</th><th>Nacimiento</th><th>Parentesco</th></tr></thead><tbody>@forelse(data_get($application->data,'dependents',[]) as $dependent)<tr><td>{{ $dependent['full_name'] ?? '—' }}</td><td>{{ $dependent['rut'] ?? '—' }}</td><td>{{ $dependent['birth_date'] ?? '—' }}</td><td>{{ $dependent['relationship'] ?? '—' }}</td></tr>@empty<tr><td colspan="4" class="text-muted">Sin cargas familiares.</td></tr>@endforelse</tbody></table></div>

                <h2 class="detail-title">Aprobación del Consejo Directivo</h2>
                <div class="table-responsive"><table class="table table-sm"><thead><tr><th>Integrante</th><th>RUT</th><th>Firma</th></tr></thead><tbody>@forelse(data_get($application->data,'board_members',[]) as $member)<tr><td>{{ $member['name'] ?? '—' }}</td><td>{{ $member['rut'] ?? '—' }}</td><td>{{ ! empty($member['signature']) ? 'Registrada' : '—' }}</td></tr>@empty<tr><td colspan="3" class="text-muted">Sin aprobaciones registradas.</td></tr>@endforelse</tbody></table></div>

                <h2 class="detail-title">Documentos adjuntos</h2>
                @forelse($application->attachments ?? [] as $file)
                    <div class="attachment-row"><i data-lucide="file"></i><span><strong>{{ $file['name'] }}</strong><small>{{ number_format($file['size']/1024,0) }} KB · {{ $file['type'] }}</small></span><button type="button" class="btn btn-sm btn-outline-copper ms-auto" @click="openAttachment('{{ route('admin.applications.attachment', [$application, $loop->index, 'preview' => 1]) }}','{{ route('admin.applications.attachment', [$application, $loop->index]) }}',@js($file['name']))"><i data-lucide="eye"></i> Ver</button><a class="btn btn-sm btn-light" href="{{ route('admin.applications.attachment', [$application, $loop->index]) }}" title="Descargar"><i data-lucide="download"></i></a></div>
                @empty<p class="text-muted">Sin documentos adjuntos.</p>@endforelse
            </div>
        </div>

        <div class="col-xl-4">
            <div class="admin-panel sticky-xl-top" style="top:92px">
                <h2 class="h5 fw-bold mb-3">Gestionar solicitud</h2>
                <form method="POST" action="{{ route('admin.applications.update',$application) }}" enctype="multipart/form-data" x-data="{ selectedStatus: @js(old('status', $application->status)) }">
                    @csrf @method('PATCH')
                    <h3 class="h6 fw-bold">Antecedentes de la inscripción</h3>
                    <label class="form-label" for="application_date">Fecha de postulación <span class="required">*</span></label>
                    <input id="application_date" name="application_date" type="date" class="form-control mb-3" required value="{{ old('application_date', optional($application->application_date)->format('Y-m-d')) }}">
                    <label class="form-label" for="payment_amount">Valor de inscripción</label>
                    <input id="payment_amount" name="payment_amount" class="form-control mb-3" value="{{ old('payment_amount', data_get($application->data, 'payment_amount')) }}">
                    <label class="form-label" for="receipt_number">Número de comprobante</label>
                    <input id="receipt_number" name="receipt_number" class="form-control mb-3" value="{{ old('receipt_number', data_get($application->data, 'receipt_number')) }}">
                    <label class="form-label" for="first_payment_date">Fecha del primer pago</label>
                    <input id="first_payment_date" name="first_payment_date" type="date" class="form-control mb-4" value="{{ old('first_payment_date', data_get($application->data, 'first_payment_date')) }}">
                    <label class="form-label">Estado</label>
                    <select name="status" class="form-select mb-3" x-model="selectedStatus">@foreach(['pending'=>'Pendiente','review'=>'En revisión','approved'=>'Aprobada','rejected'=>'Rechazada'] as $value=>$label)<option value="{{ $value }}">{{ $label }}</option>@endforeach</select>
                    @if(in_array($application->type, ['radomiro', 'gabriela'], true))
                        <div x-show="selectedStatus === 'approved'" x-transition>
                            <div class="alert alert-light border small"><i data-lucide="calendar-check"></i> La fecha de recepción se estampará automáticamente al aprobar.</div>
                            <label class="form-label" for="payroll_received_by">Recepcionado por <span class="required">*</span></label>
                            <input id="payroll_received_by" name="payroll_received_by" class="form-control mb-3 @error('payroll_received_by') is-invalid @enderror" value="{{ old('payroll_received_by', data_get($application->data, 'payroll_received_by')) }}" :required="selectedStatus === 'approved'" placeholder="Nombre de quien recibe">
                            @error('payroll_received_by')<div class="field-error mb-2">{{ $message }}</div>@enderror
                            <label class="form-label" for="payroll_stamp">Firma o timbre <span class="text-muted fw-normal">(opcional)</span></label>
                            <input id="payroll_stamp" name="payroll_stamp" type="file" accept="image/png,image/jpeg" class="form-control mb-2 @error('payroll_stamp') is-invalid @enderror">
                            <small class="text-muted d-block mb-3">Puedes dejarlo vacío para imprimir y timbrar físicamente.</small>
                            @error('payroll_stamp')<div class="field-error mb-2">{{ $message }}</div>@enderror
                        </div>
                    @endif
                    <label class="form-label">Notas internas</label>
                    <textarea name="admin_notes" rows="6" class="form-control mb-3">{{ $application->admin_notes }}</textarea>
                    <button class="btn btn-copper w-100">Guardar cambios</button>
                </form>
            </div>
        </div>
    </div>

    @if(in_array($application->type, ['particular', 'radomiro', 'gabriela', 'club_golf'], true))
        <div class="modal fade" id="applicationPreviewModal" tabindex="-1" aria-labelledby="applicationPreviewTitle" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content">
                <div class="modal-header"><div><span class="eyebrow mb-1">DOCUMENTO ORIGINAL</span><h2 class="modal-title h5" id="applicationPreviewTitle">Vista previa de la inscripción</h2></div><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button></div>
                <div class="modal-body bg-dark p-2 p-md-3"><iframe class="pdf-template-preview" title="Vista previa del PDF" loading="lazy" src="{{ route('admin.applications.pdf', [$application, 'preview' => 1]) }}"></iframe></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cerrar</button>
                    <a class="btn btn-copper" href="{{ route('admin.applications.pdf', $application) }}"><i data-lucide="file-down"></i> Descargar PDF</a>
                </div>
            </div></div>
        </div>
    @endif

    @if(in_array($application->type, ['radomiro', 'gabriela'], true))
        @php($authorizationRoute = $application->type === 'gabriela' ? 'admin.applications.gabriela-authorization' : 'admin.applications.radomiro-authorization')
        <div class="modal fade" id="payrollAuthorizationModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content"><div class="modal-header"><div><span class="eyebrow mb-1">{{ $application->type === 'gabriela' ? 'DIVISIÓN GABRIELA MISTRAL' : 'DIVISIÓN RADOMIRO TOMIC' }}</span><h2 class="modal-title h5">Autorización de descuento por planilla</h2></div><button class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button></div><div class="modal-body bg-dark p-2 p-md-3"><iframe class="pdf-template-preview" title="Autorización de descuento por planilla" src="{{ route($authorizationRoute, [$application, 'preview' => 1]) }}"></iframe></div><div class="modal-footer"><button class="btn btn-light" data-bs-dismiss="modal">Cerrar</button><a class="btn btn-copper" href="{{ route($authorizationRoute, $application) }}"><i data-lucide="download"></i> Descargar autorización</a></div></div></div></div>
    @endif

    <div class="modal fade" id="attachmentPreviewModal" tabindex="-1" aria-labelledby="attachmentPreviewTitle" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content">
            <div class="modal-header"><div><span class="eyebrow mb-1">DOCUMENTO ADJUNTO</span><h2 class="modal-title h5" id="attachmentPreviewTitle" x-text="attachmentName"></h2></div><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button></div>
            <div class="modal-body bg-dark p-2 p-md-3"><iframe class="attachment-preview-frame" title="Vista previa del documento adjunto" :src="attachmentUrl"></iframe></div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Cerrar</button><a class="btn btn-copper" :href="attachmentDownloadUrl"><i data-lucide="download"></i> Descargar archivo</a></div>
        </div></div>
    </div>
</div>
</x-admin-layout>
