<style>
    .btn-spacing + .btn-spacing {
        margin-left: 10px;
    }
</style>

<h2 class="page-title">Buscar Trámite</h2>
<p class="text-muted">Seleccione un criterio de búsqueda y complete el formulario.</p>

<div class="row">
    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-header">
                <strong class="card-title">Criterio de Búsqueda</strong>
            </div>
            <div class="card-body">
                <form id="search-form" action="<?= BASE_ACTION ?>search/handle" method="POST">
                    <div class="form-group">
                        <label for="search_type">Buscar por</label>
                        <select name="search_type" id="search_type" class="form-control" required>
                            <option value="">Seleccione...</option>
                            <option value="name" <?= isset($search_type) && $search_type === 'name' ? 'selected' : '' ?>>Nombres y Apellidos</option>
                            <option value="dni" <?= isset($search_type) && $search_type === 'dni' ? 'selected' : '' ?>>DNI</option>
                            <option value="dates" <?= isset($search_type) && $search_type === 'dates' ? 'selected' : '' ?>>Solo Fechas</option>
                            <option value="procedure" <?= isset($search_type) && $search_type === 'procedure' ? 'selected' : '' ?>>Por procedimiento</option>
                            <option value="derivados" <?= isset($search_type) && $search_type === 'derivados' ? 'selected' : '' ?>>Derivados</option>
                            <option value="state" <?= isset($search_type) && $search_type === 'state' ? 'selected' : '' ?>>Por estado</option>
                            <option value="process_number" <?= isset($search_type) && $search_type === 'process_number' ? 'selected' : '' ?>>Por número de trámite</option>
                        </select>
                    </div>

                    <!-- Campos comunes/dinámicos -->
                    <div id="fields-container">
                        <!-- Se llenan dinámicamente -->
                    </div>

                    <input type="hidden" name="export_type" id="export_type" value="">

                    <div class="d-flex justify-content-start mt-3">
                        <button type="submit" class="btn btn-primary btn-spacing" onclick="setSearchAction()">Buscar</button>
                        <button type="submit" class="btn btn-danger btn-spacing" onclick="setExportAction('pdf')">Exportar a PDF</button>
                        <button type="submit" class="btn btn-success btn-spacing" onclick="setExportAction('excel')">Exportar a Excel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<?php if (!empty($processes)): ?>
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card shadow">
                <div class="card-header">
                    <strong class="card-title">Resultados de la búsqueda</strong>
                </div>
                <div class="card-body">
                    <table class="table datatables" id="dataTable-1">
                        <thead class="thead-dark">
                            <tr>
                                <th>N°</th>
                                <th>Expediente</th>
                                <th>Administrado</th>
                                <th>DNI</th>
                                <th>Procedimiento</th>
                                <th>Asunto</th>
                                <th>Folios</th>
                                <th>Estado</th>
                                <th>Fecha</th>
                                <th>Acción</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($processes as $index => $process): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($process->num_exped) ?></td>
                                <td><?= htmlspecialchars($process->user()->name) . ' ' . htmlspecialchars($process->user()->paternal_surname) . ' ' . htmlspecialchars($process->user()->maternal_surname) ?></td>
                                <td><?= htmlspecialchars($process->user()->dni) ?></td>
                                <td><?= htmlspecialchars($process->procedure()->description ?? 'Sin procedimiento') ?></td>
                                <td><?= htmlspecialchars($process->subject) ?></td>
                                <td><?= htmlspecialchars($process->folios) ?></td>
                                <td><?= htmlspecialchars($process->general_state) ?></td>
                                <td><?= date('d/m/Y', strtotime($process->entry_date)) ?></td>
                                <td><a href="<?= BASE_HREF ?>processes/<?= htmlspecialchars($process->id); ?>/show-process" class="btn btn-sm btn-primary">Ver</a></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
<?php elseif (!empty($derivation_results)): ?>
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card shadow">
                <div class="card-header">
                    <strong class="card-title">Resultados de la búsqueda por derivación</strong>
                </div>
                <div class="card-body">
                    <table class="table datatables" id="dataTable-2">
                        <thead class="thead-dark">
                            <tr>
                                <th>N°</th>
                                <th>Expediente</th>
                                <th>Administrado</th>
                                <th>DNI</th>
                                <th>Procedimiento</th>
                                <th>Asunto</th>
                                <th>Fecha de derivación</th>
                                <th>Derivado a</th>
                                <th>Acción</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($derivation_results as $index => $derivation): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($derivation['num_exped']) ?></td>
                                <td><?= htmlspecialchars($derivation['user_name']) ?></td>
                                <td><?= htmlspecialchars($derivation['user_dni']) ?></td>
                                <td><?= htmlspecialchars($derivation['procedure_description'] ?? 'Sin procedimiento') ?></td>
                                <td><?= htmlspecialchars($derivation['subject']) ?></td>
                                <td><?= date('d/m/Y', strtotime($derivation['derived_date'])) ?></td>
                                <td><?= htmlspecialchars($derivation['subgroup_name'] ?? $derivation['group_name'] ?? 'N/A') ?></td>
                                <td><a href="<?= BASE_HREF ?>processes/<?= htmlspecialchars($derivation['process_id']); ?>/show-process" class="btn btn-sm btn-primary">Ver</a></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

<?php elseif (!empty($state_results)): ?>
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card shadow">
                <div class="card-header">
                    <strong class="card-title">Resultados de la búsqueda por estado</strong>
                </div>
                <div class="card-body">
                    <table class="table datatables" id="dataTable-3">
                        <thead class="thead-dark">
                            <tr>
                                <th>N°</th>
                                <th>Expediente</th>
                                <th>Asunto</th>
                                <th>Fecha de entrada</th>
                                <th>Área</th>
                                <th>Grupo</th>
                                <th>Subgrupo</th>
                                <th>Días transcurridos</th>
                                <th>Estado</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($state_results as $index => $item): ?>
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <td><?= htmlspecialchars($item['expediente']) ?></td>
                                    <td><?= htmlspecialchars($item['asunto']) ?></td>
                                    <td><?= date('d/m/Y', strtotime($item['fecha_ingreso'])) ?></td>
                                    <td><?= htmlspecialchars($item['area']) ?></td>
                                    <td><?= htmlspecialchars($item['grupo']) ?></td>
                                    <td><?= htmlspecialchars($item['subgrupo'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($item['dias_transcurridos']) ?></td>
                                    <td>
                                        <span class="badge" style="background-color: <?= htmlspecialchars($item['color']) ?>; color: #000;">
                                            <?= htmlspecialchars($item['estado']) ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                </div>
            </div>
        </div>
    </div>

<?php elseif (isset($search_type)): ?>
    <div class="alert alert-info mt-4">No se encontraron resultados.</div>
<?php endif; ?>


<script>
  $(document).ready(function() {    
    $('#dataTable-1').DataTable({
      autoWidth: true,
      "lengthMenu": [
        [10, 15, 20, -1],
        [10, 15, 20, "Todos"]
      ]
    });

    $('#dataTable-2').DataTable({
      autoWidth: true,
      "lengthMenu": [
        [10, 15, 20, -1],
        [10, 15, 20, "Todos"]
      ]
    });

    $('#dataTable-3').DataTable({
      autoWidth: true,
      "lengthMenu": [
        [10, 15, 20, -1],
        [10, 15, 20, "Todos"]
      ]
    });
  });
</script>

<script>
    function setSearchAction() {
        const form = document.getElementById('search-form');
        form.action = '<?= BASE_ACTION ?>search/handle';
        form.removeAttribute('target');
        document.getElementById('export_type').value = '';
    }

    function setExportAction(type) {
        const form = document.getElementById('search-form');
        form.action = '<?= BASE_ACTION ?>report/generate';
        document.getElementById('export_type').value = type;

        if (type === 'pdf') {
            form.setAttribute('target', '_blank');
        } else {
            form.removeAttribute('target'); 
        }
    }
</script>

<script>
    const searchType = document.getElementById('search_type');
    const fieldsContainer = document.getElementById('fields-container');

    const templates = {
        name: `
             <div class="form-group">
                <label for="paternal_surname">Apellido Paterno</label>
                <input type="text" name="paternal_surname" class="form-control" id="paternal_surname" value="<?= isset($filters['paternal_surname']) ? htmlspecialchars($filters['paternal_surname']) : '' ?>" required>
            </div>
            <div class="form-group">
                <label for="maternal_surname">Apellido Materno</label>
                <input type="text" name="maternal_surname" class="form-control" id="maternal_surname" value="<?= isset($filters['maternal_surname']) ? htmlspecialchars($filters['maternal_surname']) : '' ?>" required>
            </div>
            <div class="form-group">
                <label for="name">Nombres</label>
                <input type="text" name="name" class="form-control" id="name" value="<?= isset($filters['name']) ? htmlspecialchars($filters['name']) : '' ?>" required>
            </div>
            ${dateRangeTemplate()}
        `,
        dni: `
            <div class="form-group">
                <label for="dni">DNI</label>
                <input type="text" name="dni" maxlength="8" class="form-control" id="dni" value="<?= isset($filters['dni']) ? htmlspecialchars($filters['dni']) : '' ?>" required>
            </div>
            ${dateRangeTemplate()}
        `,
        dates: `
            ${dateRangeTemplate(true)}
        `,
        priority: `
            <div class="form-group">
                <label for="priority">Estado</label>
                <select name="priority" id="priority" class="form-control" required>
                    <option value="">Seleccione estado</option>
                    <?php foreach ($priorities as $priority): ?>
                        <option value="<?= $priority->id ?>" <?= isset($filters['priority']) && $filters['priority'] == $priority->id ? 'selected' : '' ?>>
                            <?= htmlspecialchars($priority->description) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            ${dateRangeTemplate()}
        `,
        procedure: `
            <div class="form-group">
                <label for="procedure_id">Procedimiento</label>
                <select name="procedure_id" id="procedure_id" class="form-control" required>
                    <option value="">Seleccione un procedimiento</option>
                    <?php foreach ($procedures as $procedure): ?>
                        <option value="<?= $procedure->id ?>" <?= isset($filters['procedure_id']) && $filters['procedure_id'] == $procedure->id ? 'selected' : '' ?>>
                            <?= htmlspecialchars($procedure->description) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            ${dateRangeTemplate()}
        `,
        derivados: `
            <div class="form-group">
                <label for="grouping_type">Agrupar por</label>
                <select name="grouping_type" id="grouping_type" class="form-control" required onchange="toggleDerivadoFields()">
                    <option value="">Seleccione...</option>
                    <option value="day" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'day' ? 'selected' : '' ?>>Día</option>
                    <option value="month" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'month' ? 'selected' : '' ?>>Mes</option>
                    <option value="year" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'year' ? 'selected' : '' ?>>Año</option>
                    <option value="period" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'period' ? 'selected' : '' ?>>Período</option>
                </select>
            </div>
            <div class="form-group derivado-field" id="field-day" style="display:none">
                <label for="day_date">Seleccione el día</label>
                <input type="date" name="day_date" id="day_date" class="form-control" value="<?= isset($filters['day_date']) ? htmlspecialchars($filters['day_date']) : '' ?>">
            </div>
            <div class="form-group derivado-field" id="field-month" style="display:none">
                <label for="month">Mes</label>
                <select name="month" id="month" class="form-control">
                    <option value="">Seleccione un mes</option>
                    <?php 
                        $months = [
                            '01' => 'Enero', '02' => 'Febrero', '03' => 'Marzo', '04' => 'Abril',
                            '05' => 'Mayo', '06' => 'Junio', '07' => 'Julio', '08' => 'Agosto',
                            '09' => 'Septiembre', '10' => 'Octubre', '11' => 'Noviembre', '12' => 'Diciembre'
                        ];
                        foreach ($months as $key => $value): ?>
                            <option value="<?= $key ?>" <?= (isset($filters['month']) && $filters['month'] === $key) ? 'selected' : '' ?>>
                                <?= $value ?>
                            </option>
                    <?php endforeach; ?>
                </select>

                <label for="month_year" class="mt-2">Año</label>
                <select name="month_year" id="month_year" class="form-control">
                    <option value="">Seleccione un año</option>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= $period ?>" <?= isset($filters['month_year']) && $filters['month_year'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>

            </div>
            <div class="form-group derivado-field" id="field-year" style="display:none">
                <label for="year">Año</label>
                <select name="year" id="year" class="form-control">
                    <option value="">Seleccione un año</option>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= $period ?>" <?= isset($filters['year']) && $filters['year'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group derivado-field" id="field-period" style="display:none">
                <label for="period">Periodo</label>
                <select name="period" id="period" class="form-control">
                    <option value="">Seleccione un período</option>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= $period ?>" <?= isset($filters['period']) && $filters['period'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        `,
        state: `
            <div class="form-group">
                <label for="state">Estado</label>
                <select name="state" id="state" class="form-control">
                    <option value="">Todos</option>
                        <?php foreach ($priorities as $state): ?>
                            <option value="<?= htmlspecialchars($state->description) ?>"
                                <?= (isset($filters['state']) && $filters['state'] === $state->description) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($state->description) ?>
                            </option>
                        <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label for="grouping_type">Agrupar por</label>
                <select name="grouping_type" id="grouping_type" class="form-control" onchange="toggleDerivadoFields()">
                    <option value="">Seleccione...</option>
                    <option value="day" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'day' ? 'selected' : '' ?>>Día</option>
                    <option value="month" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'month' ? 'selected' : '' ?>>Mes</option>
                    <option value="year" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'year' ? 'selected' : '' ?>>Año</option>
                    <option value="period" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'period' ? 'selected' : '' ?>>Período</option>
                    <option value="range" <?= isset($filters['grouping_type']) && $filters['grouping_type'] === 'range' ? 'selected' : '' ?>>Rango de fechas</option>
                </select>
            </div>
            <div class="form-group derivado-field" id="field-day" style="display:none">
                <label for="day_date">Seleccione el día</label>
                <input type="date" name="day_date" id="day_date" class="form-control" value="<?= isset($filters['day_date']) ? htmlspecialchars($filters['day_date']) : '' ?>">
            </div>
            <div class="form-group derivado-field" id="field-month" style="display:none">
                <label for="month">Mes</label>
                <select name="month" id="month" class="form-control">
                    <option value="">Seleccione un mes</option>
                    <?php 
                        $months = [
                            '01' => 'Enero', '02' => 'Febrero', '03' => 'Marzo', '04' => 'Abril',
                            '05' => 'Mayo', '06' => 'Junio', '07' => 'Julio', '08' => 'Agosto',
                            '09' => 'Septiembre', '10' => 'Octubre', '11' => 'Noviembre', '12' => 'Diciembre'
                        ];
                        foreach ($months as $key => $value): ?>
                            <option value="<?= $key ?>" <?= (isset($filters['month']) && $filters['month'] === $key) ? 'selected' : '' ?>>
                                <?= $value ?>
                            </option>
                    <?php endforeach; ?>
                </select>

                <label for="month_year" class="mt-2">Año</label>
                <select name="month_year" id="month_year" class="form-control">
                    <option value="">Seleccione un año</option>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= $period ?>" <?= isset($filters['month_year']) && $filters['month_year'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>

            </div>
            <div class="form-group derivado-field" id="field-year" style="display:none">
                <label for="year">Año</label>
                <select name="year" id="year" class="form-control">
                    <option value="">Seleccione un año</option>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= $period ?>" <?= isset($filters['year']) && $filters['year'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group derivado-field" id="field-period" style="display:none">
                <label for="period">Periodo</label>
                <select name="period" id="period" class="form-control">
                    <option value="">Seleccione un período</option>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= $period ?>" <?= isset($filters['period']) && $filters['period'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group derivado-field" id="field-range" style="display:none">
                <label for="start_date">Desde</label>
                <input type="date" name="start_date" id="start_date" class="form-control"
                    value="<?= isset($filters['start_date']) ? htmlspecialchars($filters['start_date']) : '' ?>">

                <label for="end_date" class="mt-2">Hasta</label>
                <input type="date" name="end_date" id="end_date" class="form-control"
                    value="<?= isset($filters['end_date']) ? htmlspecialchars($filters['end_date']) : '' ?>">
            </div>


            <?php if ($_SESSION['role'] === 'ADMIN'): ?>
                <div class="form-group">
                        <label for="area">Área</label>
                        <select id="area" name="area_id" class="form-control">
                            <option value="">Seleccione un Área</option>
                            <?php foreach ($areas as $area) : ?>
                                <option value="<?= $area->id ?>"><?= $area->description ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="group_type">Tipo de Grupo</label>
                        <select id="group_type" name="group_type_id" class="form-control">
                            <option value="">Seleccione un Tipo de Grupo</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="group">Grupo</label>
                        <select id="group" name="group_id" class="form-control">
                            <option value="">Seleccione un Grupo</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="subgroup">Subgrupo</label>
                        <select id="subgroup" name="subgroup_id" class="form-control">
                            <option value="">Seleccione un Subgrupo</option>
                        </select>
                    </div>
            <?php endif; ?>
        `,

        process_number: `
            <div class="form-group">
                <label for="period">Periodo</label>
                <select name="period" id="period" class="form-control" required>
                    <?php foreach ($periods as $period): ?>
                        <option value="<?= htmlspecialchars($period) ?>" 
                            <?= isset($filters['period']) && $filters['period'] == $period ? 'selected' : '' ?>>
                            <?= htmlspecialchars($period) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="num_exped">Número de Trámite</label>
                <input type="text" name="num_exped" class="form-control" id="num_exped" 
                    value="<?= isset($filters['num_exped']) ? htmlspecialchars($filters['num_exped']) : '' ?>" required>
            </div>
        `

    };

    function dateRangeTemplate(required = false) {
        const attr = required ? 'required' : '';
        return `
            <div class="form-group">
                <label for="start_date">Desde</label>
                <input type="date" name="start_date" id="start_date" class="form-control" value="<?= isset($filters['start_date']) ? htmlspecialchars($filters['start_date']) : '' ?>" ${attr}>
            </div>
            <div class="form-group">
                <label for="end_date">Hasta</label>
                <input type="date" name="end_date" id="end_date" class="form-control" value="<?= isset($filters['end_date']) ? htmlspecialchars($filters['end_date']) : '' ?>" ${attr}>
            </div>
        `;
    }

    function toggleDerivadoFields() {
        const value = document.getElementById('grouping_type').value;
        document.querySelectorAll('.derivado-field').forEach(field => field.style.display = 'none');
        if (value) {
            document.getElementById(`field-${value}`).style.display = 'block';
        }
    }

    function applyEnhancements() {
        document.querySelectorAll("#fields-container input[required], #fields-container select[required]").forEach(function (input) {
            const label = document.querySelector(`label[for="${input.id}"]`);
            if (label && !label.innerHTML.includes("*")) {
                label.innerHTML += ' <span class="text-danger">*</span>';
            }
        });

        ['paternal_surname', 'maternal_surname', 'name', 'num_exped'].forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.addEventListener('input', e => e.target.value = e.target.value.toUpperCase());
            }
        });
    }

    function initSelect2() {
        $('#procedure_id, #area, #group_type, #group, #subgroup').select2({
            theme: 'bootstrap4',
            placeholder: 'Seleccione',
            allowClear: true,
            width: '100%'
        });
    }


    searchType.addEventListener('change', () => {
        const selected = searchType.value;

        fieldsContainer.querySelectorAll('input, select, textarea').forEach(el => {
            if (el.type === 'checkbox' || el.type === 'radio') {
                el.checked = false; 
            } else {
                el.value = ''; 
            }
        });
        
        fieldsContainer.innerHTML = templates[selected] || '';
        if (selected === 'derivados' || selected === 'state') toggleDerivadoFields();
        if (selected === 'procedure' || selected === 'state') initSelect2();

        applyEnhancements();
    });

    window.addEventListener('DOMContentLoaded', () => {
        const selected = searchType.value;
        if (selected && templates[selected]) {
            fieldsContainer.innerHTML = templates[selected];
            if (selected === 'derivados' || selected === 'state') toggleDerivadoFields();
            if (selected === 'procedure' || selected === 'state') initSelect2();
            applyEnhancements();
        }
    });

</script>

<script>
    const areas = <?= json_encode($areas, JSON_PRETTY_PRINT) ?>;

    $(document).on('change', '#area', function () {
        console.log('Área seleccionada: ', this.value);
        const areaId = this.value;
        const groupTypeSelect = $('#group_type');
        const groupSelect = $('#group');
        const subgroupSelect = $('#subgroup');

        groupTypeSelect.html('<option value="">Seleccione un Tipo de Grupo</option>').prop('disabled', true);
        groupSelect.html('<option value="">Seleccione un Grupo</option>').prop('disabled', true);
        subgroupSelect.html('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true);

        if (areaId) {
            const area = areas.find(a => a.id == areaId);
            if (area) {
                groupTypeSelect.prop('disabled', false);
                Object.values(area.groupTypes).forEach(groupType => {
                    groupTypeSelect.append(new Option(groupType.description, groupType.id));
                });
            }
        }
    });

    $(document).on('change', '#group_type', function () {
        const groupTypeId = this.value;
        const groupSelect = $('#group');
        const subgroupSelect = $('#subgroup');

        groupSelect.html('<option value="">Seleccione un Grupo</option>').prop('disabled', true);
        subgroupSelect.html('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true);

        if (groupTypeId) {
            const areaId = $('#area').val();
            const area = areas.find(a => a.id == areaId);
            if (area) {
                const groupType = Object.values(area.groupTypes).find(gt => gt.id == groupTypeId);
                if (groupType) {
                    groupSelect.prop('disabled', false);
                    Object.values(groupType.groups).forEach(group => {
                        groupSelect.append(new Option(group.description, group.id));
                    });
                }
            }
        }
    });

    $(document).on('change', '#group', function () {
        const groupId = this.value;
        const subgroupSelect = $('#subgroup');

        subgroupSelect.html('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true);

        if (groupId) {
            const areaId = $('#area').val();
            const groupTypeId = $('#group_type').val();
            const area = areas.find(a => a.id == areaId);
            if (area) {
                const groupType = Object.values(area.groupTypes).find(gt => gt.id == groupTypeId);
                if (groupType) {
                    const group = Object.values(groupType.groups).find(g => g.id == groupId);
                    if (group) {
                        subgroupSelect.prop('disabled', false);
                        Object.values(group.subGroups).forEach(subgroup => {
                            subgroupSelect.append(new Option(subgroup.description, subgroup.id));
                        });
                    }
                }
            }
        }
    });
</script>
