<h2 class="page-title">Ruta del Procedimiento: <?= htmlspecialchars(ucfirst(strtolower($procedure->description))) ?></h2>
<p class="text-muted">Puede visualizar la ruta de este procedimiento.</p>

<div class="d-flex justify-content-end mb-3">
    <a href="<?= BASE_HREF ?>procedures" class="btn btn-secondary">Volver</a>
</div>


<!-- <div class="container-fluid"> -->
    <div class="row">
        <div class="col-md-12">
            <?php if (!empty($routes)): ?>
                <div class="card">
                    <div class="card-body">
                        <h5>Pasos Actuales</h5>
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Grupo</th>
                                    <th>Subgrupo</th>
                                    <th>Paso Anterior</th>
                                    <th>Paso Siguiente</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($routes as $index => $route): ?>
                                    <tr>
                                        <td><?= $route->id ?></td>
                                        <td><?= htmlspecialchars($route->group()->description ?? 'N/A') ?></td>
                                        <td><?= htmlspecialchars($route->subgroup()->description ?? 'N/A') ?></td>
                                        <td><?= $route->previous_step_id ? 'Paso ' . $route->previous_step_id : 'Inicio' ?></td>
                                        <td><?= $route->next_step_id ? 'Paso ' . $route->next_step_id : 'Final' ?></td>
                                        <td>
                                            <a href="<?= BASE_HREF ?>procedures-route/<?= $route->id ?>/edit" class="btn btn-sm btn-primary">Editar</a>
                                            <form action="<?= BASE_ACTION ?>procedures-route/<?= $route->id ?>/delete" method="POST" style="display:inline;" onsubmit="return confirm('¿Eliminar este paso?');">
                                                <input type="hidden" name="_method" value="DELETE">
                                                <button type="submit" class="btn btn-sm btn-danger">Eliminar</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php else: ?>
                <div class="alert alert-warning">Este procedimiento no tiene una ruta definida. Por favor, cree una ruta antes de salir de esta pantalla.</div>
            <?php endif; ?>

            <!-- Sección para agregar nuevo nodo -->
            <div class="card mt-4">
                <div class="card-body">
                    <h5>Agregar Nuevo Nodo</h5>
                    <form action="<?= BASE_ACTION ?>procedures-route/<?= $procedure->id ?>/add" method="POST">
                        <div class="form-row">
                            <div class="col-md-3">
                                <label>Área</label>
                                <select name="area_id" id="area" class="form-control select2" required>
                                    <option value="">Seleccione...</option>
                                    <?php foreach ($areas as $area): ?>
                                        <option value="<?= $area->id ?>"><?= htmlspecialchars($area->description) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label>Tipo de Grupo</label>
                                <select name="group_type_id" id="group_type" class="form-control select2" disabled required>
                                    <option value="">Seleccione...</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label>Grupo</label>
                                <select name="group_id" id="group" class="form-control select2" disabled required>
                                    <option value="">Seleccione...</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label>Subgrupo (Opcional)</label>
                                <select name="subgroup_id" id="subgroup" class="form-control select2" disabled>
                                    <option value="">Seleccione...</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row mt-4">
                            <div class="col-md-6">
                                <label>Paso Anterior</label>
                                <select name="previous_step_id" class="form-control">
                                    <option value="">Inicio</option>
                                    <?php foreach ($routes as $route): ?>
                                        <option value="<?= $route->id ?>">Paso <?= $route->id ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary mt-4">Crear Nodo</button>
                    </form>
                </div>
            </div>

        </div>
    </div>

<script>
    $(document).ready(function () {
        // Inicializar Select2
        $('#area, #group_type, #group, #subgroup').select2({
            theme: 'bootstrap4',
            placeholder: 'Seleccione...',
            allowClear: true,
            width: '100%'
        });

        const areas = <?= json_encode($areas, JSON_PRETTY_PRINT) ?>;
        console.log(areas);

        $('#area').on('change', function () {
            const areaId = $(this).val();

            const $groupType = $('#group_type');
            const $group = $('#group');
            const $subgroup = $('#subgroup');

            // Reset y desactivar selects
            $groupType.empty().append('<option value="">Seleccione un Tipo de Grupo</option>').prop('disabled', true).trigger('change');
            $group.empty().append('<option value="">Seleccione un Grupo</option>').prop('disabled', true).trigger('change');
            $subgroup.empty().append('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true).trigger('change');

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

        $('#group_type').on('change', function () {
            const groupTypeId = $(this).val();

            const $group = $('#group');
            const $subgroup = $('#subgroup');

            $group.empty().append('<option value="">Seleccione un Grupo</option>').prop('disabled', true).trigger('change');
            $subgroup.empty().append('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true).trigger('change');

            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) {
                        $group.prop('disabled', false);
                        Object.values(groupType.groups).forEach(group => {
                            $group.append(new Option(group.description, group.id));
                        });
                        $group.trigger('change');
                    }
                }
            }
        });

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

            $subgroup.empty().append('<option value="">Seleccione un Subgrupo</option>').prop('disabled', true).trigger('change');

            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) {
                            $subgroup.prop('disabled', false);
                            Object.values(group.subGroups).forEach(subgroup => {
                                $subgroup.append(new Option(subgroup.description, subgroup.id));
                            });
                            $subgroup.trigger('change');
                        }
                    }
                }
            }
        });
    });
</script>