@extends('layouts.app')

@section('title', 'Estados de Lotes por Sector')

@section('content')
<div class="bg-body-light">
    <div class="content content-full">
        <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2">
            <div class="flex-grow-1">
                <h1 class="h3 fw-bold mb-2">
                    <i class="fa fa-th text-danger me-2"></i>Estados de Lotes por Sector
                </h1>
                <h2 class="fs-base lh-base fw-medium text-muted mb-0">
                    Reporte técnico detallado de situación financiera y legal por manzana.
                </h2>
            </div>
            <div class="mt-3 mt-sm-0 ms-sm-3">
                <a href="{{ route('dashboard') }}" class="btn btn-sm btn-alt-secondary">
                    <i class="fa fa-home me-1"></i> Inicio
                </a>
            </div>
        </div>
    </div>
</div>

<div class="content">
    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">

            <form method="POST" action="{{ route('reportes.estados-sector.pdf') }}" id="formEstados" target="_blank">
                @csrf

                <div class="block block-rounded block-bordered shadow-sm">
                    <div class="block-header block-header-default">
                        <h3 class="block-title">Selección de Ubicación</h3>
                    </div>
                    <div class="block-content">

                        @if($errors->any())
                            <div class="alert alert-danger d-flex align-items-center mb-4" role="alert">
                                <div class="flex-shrink-0"><i class="fa fa-fw fa-times-circle"></i></div>
                                <div class="flex-grow-1 ms-3">
                                    <ul class="mb-0 fs-sm">
                                        @foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach
                                    </ul>
                                </div>
                            </div>
                        @endif

                        <div class="mb-4">
                            <label class="form-label text-muted fs-xs fw-bold text-uppercase">Urbanización <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-city text-muted"></i></span>
                                <select name="select1" id="select1" class="form-select border-primary" required>
                                    <option value="0">— Seleccione —</option>
                                    @foreach($urbanizaciones as $u)
                                        <option value="{{ $u->id }}">{{ $u->id }}. {{ $u->nombre }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label text-muted fs-xs fw-bold text-uppercase">Distrito / Sector <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-map-marked-alt text-muted"></i></span>
                                <select name="select2" id="select2" class="form-select" disabled required>
                                    <option value="0">— Seleccione Urbanización primero —</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label text-muted fs-xs fw-bold text-uppercase">Manzano <small class="text-muted fw-normal">(Opcional)</small></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fa fa-layer-group text-muted"></i></span>
                                <select name="select3" id="select3" class="form-select" disabled>
                                    <option value="0">— Todos los manzanos —</option>
                                </select>
                            </div>
                        </div>

                    </div>
                    <div class="block-content block-content-full block-content-sm bg-body-light border-top text-end">
                        <button type="reset" class="btn btn-alt-secondary me-1" onclick="resetSelects()">
                            <i class="fa fa-sync-alt me-1"></i> Limpiar
                        </button>
                        <button type="submit" class="btn btn-danger" onclick="return validar()">
                            <i class="fa fa-file-pdf me-1"></i> Generar Reporte PDF
                        </button>
                    </div>
                </div>
            </form>

            <div class="block block-rounded block-bordered bg-body-extra-light mt-4">
                <div class="block-header block-header-default bg-white border-bottom">
                    <h3 class="block-title fs-sm fw-bold text-uppercase text-muted">
                        <i class="fa fa-list-ul me-2"></i>Contenido del PDF
                    </h3>
                </div>
                <div class="block-content py-3">
                    <div class="row g-2">
                        @php
                            $columnas = [
                                'M' => 'Manzano', 'L' => 'N° Lote', 'Sup' => 'Superficie m²', 'Est' => 'Estado (1-6)',
                                'Cont' => 'Contrato', 'FC' => 'F. Contrato', 'Total' => 'Monto Total', 'PCM' => 'P. Cuota Mes',
                                'NC' => 'N° Cuotas', 'FUP' => 'F. Últ. Pago', 'TotalEx' => 'T. Extractos', 'Pagado' => 'Cancelado',
                                'Saldo' => 'Pendiente', 'Días' => 'Mora', 'Estado' => 'Literal', 'Auto' => 'N° Autoriz.'
                            ];
                        @endphp
                        @foreach($columnas as $abbr => $desc)
                            <div class="col-6 col-md-4">
                                <div class="fs-xs text-muted border-start border-3 border-light ps-2">
                                    <strong class="text-dark">{{ $abbr }}:</strong> {{ $desc }}
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.getElementById('select1').addEventListener('change', async function () {
    const selDis = document.getElementById('select2');
    const selMan = document.getElementById('select3');
    selDis.innerHTML = '<option value="0">— Seleccione Distrito —</option>';
    selMan.innerHTML = '<option value="0">— Todos los manzanos —</option>';
    selDis.disabled = true;
    selMan.disabled = true;

    if (this.value == 0) return;

    try {
        const response = await fetch(`{{ url('reportes/ajax/distritos') }}/${this.value}`);
        const data = await response.json();
        data.forEach(d => selDis.innerHTML += `<option value="${d.id}">${d.nombre}</option>`);
        selDis.disabled = false;
    } catch (e) { console.error('Error al cargar distritos'); }
});

document.getElementById('select2').addEventListener('change', async function () {
    const selMan = document.getElementById('select3');
    selMan.innerHTML = '<option value="0">— Todos los manzanos —</option>';
    selMan.disabled = true;

    if (this.value == 0) return;

    try {
        const response = await fetch(`{{ url('reportes/ajax/manzanos-lotes') }}/${this.value}`);
        const data = await response.json();
        data.forEach(m => selMan.innerHTML += `<option value="${m}">${m}</option>`);
        selMan.disabled = false;
    } catch (e) { console.error('Error al cargar manzanos'); }
});

function validar() {
    const u = document.getElementById('select1').value;
    const d = document.getElementById('select2').value;
    if (u == 0 || d == 0) {
        Swal.fire('Atención', 'Debe seleccionar Urbanización y Sector.', 'warning');
        return false;
    }
    return true;
}

function resetSelects() {
    ['select2', 'select3'].forEach(id => {
        const s = document.getElementById(id);
        s.innerHTML = id === 'select2'
            ? '<option value="0">— Seleccione Urbanización primero —</option>'
            : '<option value="0">— Todos los manzanos —</option>';
        s.disabled = true;
    });
}
</script>
@endpush