<?php $__env->startSection('content'); ?>
<div style="display: flex; flex-direction: column;">

<div class="panel-heading" style="margin-top:16px;">
    <p>Bienvenido <?php echo e(Auth::user()->name); ?></p>
    <p>Seleccione uno o varios perfiles para ver los candidatos inscritos.   </p>
</div>

<div class="panel-body">
    <div class="form-group">
        <div class="col-md-3">
            <div>
                <label class="form-label required">Perfiles</label>
                <div class="input-group">
                    <select class="form-tom-select select-type-checkbox" id="profile_list" multiple>
                        <option value="">Seleccione</option>
                        <option value="0" data-label="Seleccionar todos">Todos los perfiles</option>
                        <?php foreach($perfiles as $perfil): ?>
                        <option value="<?php echo e($perfil->id); ?>" data-label="<?php echo e($perfil->identificador); ?>"><?php echo e($perfil->identificador); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <div id="start-group" class="form-text">Seleccione uno o varios perfiles para ver los candidatos inscritos</div>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <form method="get" action="<?php echo e(secure_url('admin/candidatos/excel')); ?>">
                <?php echo csrf_field(); ?>

				<input id="excel_input" type="hidden" name="selected_profiles" value="0"/>
                <button type="submit" class="btn btn-info">
                    Exportar a Excel
                </button>

            </form>
        </div>
        <div class="col-md-2">
          <a href="<?php echo e(secure_url('datos')); ?>"> <button class="btn btn-warning">
              Vista candidato
          </button></a>
        </div>
        <div class="col-md-2">
          <a href="<?php echo e(secure_url('admin/candidatos/emails')); ?>"> <button class="btn btn-warning">
              Listado de correos
          </button></a>
        </div>
		<div class="col-md-3">
            <form method="get" action="<?php echo e(secure_url('auth/logout')); ?>">
                <?php echo csrf_field(); ?>

                <button type="submit" class="btn btn-danger">
                    Cerrar sesión
                </button>

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

<div class="panel-heading">
    <strong>Resumen de aspirantes registrados</strong>
</div>
<div class="panel-body" >
    <table id="candidates" class="datatable table table-striped">
        <thead>
            <tr>
                <th style="text-align: center">Documento de identidad</th>
                <th style="text-align: center">Código</th>
                <th style="text-align: center">Nombres y apellidos</th>
                <th style="text-align: center">Perfiles inscritos</th>
                <th style="text-align: center">Correo</th>
                <th style="text-align: center">Finalizado</th>
                <th style="text-align: center">Adjuntos</th>
            </tr>
        </thead>
        <tbody>
            <tr id="not_selected_profile">
                <td colspan="8"> No se ha seleccionado ningun perfil todavia. Por favor, seleccione al menos un perfil para mostrar la lista de candidatos inscritos.</td>
            </tr>
            <?php foreach($aspirantes as $aspirante): ?>
            <tr data-id="<?php echo e($aspirante->id); ?>" class="candidate_row">

                <td style="text-align: center">
                    <?php echo e($aspirante->documento); ?>

                </td>
                <td style="text-align: center">
                    <?php echo e($aspirante->codigo); ?>

                </td>
                <td style="text-align: center">
                    <?php echo e($aspirante->nombre); ?> <?php echo e($aspirante->apellido); ?>

                </td>
                <td style="text-align: center">
                    <?php foreach($aspirantes_perfiles as $alfa): ?>
                    <?php if($alfa->aspirantes_id == $aspirante->id): ?>
                      <?php foreach($perfiles as $perfil): ?>
                        <?php if($alfa->perfiles_id == $perfil->id): ?>
                        <?php echo e($perfil->identificador); ?>,
                        <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    <?php endforeach; ?>
                </td>
                <td style="text-align: center">
                    <?php echo e($aspirante->correo); ?>

                </td>
                <td style="text-align: center">
                    <?php echo e($aspirante->formulario_enviado); ?> 
                </td>
                <td style="text-align: center">
                    <form method="get" action="<?php echo e(secure_url('admin/candidatos/adjuntos')); ?>" style="margin:20px 0">
                        <?php echo csrf_field(); ?>

                        <input type="hidden" name="id" value="<?php echo e($aspirante->id); ?>"/>
                        <button type="submit" data-id="<?php echo e($aspirante->id); ?>" class="btn btn-primary btn-sm">
                            <i class="fa fa-folder-open" aria-hidden="true"> <p>Descargar documentos</p></i>
                        </button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
</div>

<script type="text/javascript">
    (function() {
        console.log("=== Inicializando script de candidatos ===");
        
        // Convertir la colección de Laravel a JSON correctamente
        var aspirantes_perfiles = <?php echo json_encode($aspirantes_perfiles); ?>;
        var selected_profile_ids = [];
        var excel_input = document.getElementById("excel_input");
        var profileListSelectElement = document.getElementById("profile_list");
        var notSelectedProfileRow = document.getElementById("not_selected_profile");
        var candidateRows = document.querySelectorAll("#candidates .candidate_row");
        var tomSelectInstance = null;

        console.log("aspirantes_perfiles:", aspirantes_perfiles);
        console.log("candidateRows encontrados:", candidateRows.length);

        // Ocultar todos los candidatos al inicio
        candidateRows.forEach(function(row) {
            row.style.display = 'none';
        });
        if (notSelectedProfileRow) {
            notSelectedProfileRow.style.display = '';
        }

        // Función para inicializar Tom-select después de que las bibliotecas estén cargadas
        function initializeTomSelect() {
            if (typeof TomSelect !== 'undefined' && profileListSelectElement) {
                try {
                    var selectElement = profileListSelectElement;
                    var needsReinit = false;
                    
                    // Verificar si ya está inicializado (por el Kit UNAL u otro código)
                    if (selectElement.tomselect) {
                        tomSelectInstance = selectElement.tomselect;
                        console.log('Tom-select ya estaba inicializado para profile_list');
                        
                        // Verificar si tiene el plugin remove_button habilitado
                        var settings = tomSelectInstance.settings || {};
                        var plugins = settings.plugins || [];
                        var hasRemoveButton = Array.isArray(plugins) && plugins.includes('remove_button');
                        
                        if (!hasRemoveButton) {
                            console.log('Plugin remove_button no encontrado, reinicializando...');
                            needsReinit = true;
                        }
                    } else {
                        needsReinit = true;
                    }
                    
                    // Reinicializar si es necesario
                    if (needsReinit) {
                        var currentValues = [];
                        if (tomSelectInstance) {
                            currentValues = tomSelectInstance.getValue() || [];
                            tomSelectInstance.destroy();
                            tomSelectInstance = null;
                        }
                        
                        // Pequeño delay para asegurar que el DOM esté listo
                        setTimeout(function() {
                            tomSelectInstance = new TomSelect('#profile_list', {
                                maxItems: null,
                                placeholder: 'Seleccione',
                                closeAfterSelect: false,
                                plugins: ['remove_button']
                            });
                            
                            // Restaurar valores si había selecciones previas
                            if (currentValues && currentValues.length > 0) {
                                tomSelectInstance.setValue(currentValues);
                            }
                            
                            console.log('Tom-select reinicializado con plugin remove_button');
                            // Reinicializar eventos después de recrear la instancia
                            initializeEvents();
                        }, 100);
                        
                        return true;
                    }
                    
                    return true;
                } catch (e) {
                    console.error('Error al inicializar Tom-select:', e);
                    return false;
                }
            }
            return false;
        }
        
        // Esperar a que se carguen las bibliotecas
        function waitForLibraries() {
            if (typeof TomSelect !== 'undefined') {
                // Esperar un poco más para que el Kit UNAL termine de inicializar
                setTimeout(function() {
                    initializeTomSelect();
                    initializeEvents();
                }, 300);
            } else {
                // Reintentar después de un tiempo
                setTimeout(waitForLibraries, 100);
            }
        }
        
        // Iniciar la espera
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', waitForLibraries);
        } else {
            waitForLibraries();
        }

        function refreshCandidatesDisplay() {
            console.log("=== refreshCandidatesDisplay INICIO ===");
            
            // Obtener los valores seleccionados del select (compatible con tom-select y select nativo)
            var selectedValues = [];
            
            if (tomSelectInstance) {
                // Si es tom-select, usar la API de Tom-select
                selectedValues = tomSelectInstance.getValue() || [];
                console.log('Valores desde Tom-select:', selectedValues);
            } else if (profileListSelectElement) {
                // Fallback para select nativo
                var selectedOptions = profileListSelectElement.selectedOptions || profileListSelectElement.options;
                
                for (var i = 0; i < selectedOptions.length; i++) {
                    if (selectedOptions[i].selected) {
                        var value = selectedOptions[i].value;
                        if (value !== null && value !== undefined && value !== '') {
                            selectedValues.push(String(value));
                        }
                    }
                }
            }
            
            selected_profile_ids = selectedValues;
            console.log('Perfiles seleccionados:', selected_profile_ids);
            
            // Ocultar todo primero
            if (notSelectedProfileRow) {
                notSelectedProfileRow.style.display = 'none';
            }
            candidateRows.forEach(function(row) {
                row.style.display = 'none';
            });
            
            if(selected_profile_ids.length <= 0){
                console.log('No hay perfiles seleccionados - mostrando mensaje');
                if (notSelectedProfileRow) {
                    notSelectedProfileRow.style.display = '';
                }
            }
            else {
                // Si se seleccionó "Todos los perfiles" (valor "0")
                if (selected_profile_ids.indexOf('0') !== -1) {
                    console.log('Perfil "0" (Todos) está seleccionado - mostrando todos los candidatos');
                    candidateRows.forEach(function(row) {
                        row.style.display = '';
                    });
                }
                else {
                    // Mostrar solo los candidatos que tienen los perfiles seleccionados
                    var candidateIdsToShow = [];
                    
                    // Verificar que aspirantes_perfiles sea un array
                    if (!Array.isArray(aspirantes_perfiles)) {
                        console.error('aspirantes_perfiles no es un array:', aspirantes_perfiles);
                        return;
                    }
                    
                    selected_profile_ids.forEach(function(selectedProfileId) {
                        aspirantes_perfiles.forEach(function(spids_item) {
                            // Obtener los IDs del objeto
                            var profileId = spids_item.perfiles_id;
                            var aspiranteId = spids_item.aspirantes_id;
                            
                            // Comparar como strings para evitar problemas de tipo
                            if (profileId !== null && profileId !== undefined && 
                                String(profileId) === String(selectedProfileId)) {
                                if (aspiranteId !== null && aspiranteId !== undefined &&
                                    candidateIdsToShow.indexOf(aspiranteId) === -1) {
                                    candidateIdsToShow.push(aspiranteId);
                                }
                            }
                        });
                    });
                    
                    console.log('Candidatos a mostrar:', candidateIdsToShow);
                    
                    // Mostrar solo los candidatos encontrados
                    candidateIdsToShow.forEach(function(candidateId) {
                        var candidateRow = document.querySelector("#candidates .candidate_row[data-id='" + candidateId + "']");
                        if (candidateRow) {
                            candidateRow.style.display = '';
                        }
                    });
                }
            }
            
            // Cambiar el value del campo input con id "excel_input"
            if (excel_input) {
                excel_input.value = selected_profile_ids.toString();
                console.log('excel_input.value actualizado a:', excel_input.value);
            }
            
            console.log("=== refreshCandidatesDisplay FIN ===\n");
        }

        // Esperar a que el DOM esté listo (ya manejado en initializeTomSelect)
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                console.log('DOM cargado');
            });
        } else {
            console.log('DOM ya está listo');
        }

        function initializeEvents() {
            // Escuchar cambios en el select
            if (tomSelectInstance) {
                // Usar eventos de Tom-select para cambios
                tomSelectInstance.on('change', function(values) {
                    console.log('Evento change de Tom-select disparado:', values);
                    refreshCandidatesDisplay();
                });
                
                // Evento cuando se remueve un item
                tomSelectInstance.on('item_remove', function(value) {
                    console.log('Item removido:', value);
                    refreshCandidatesDisplay();
                });
                
                console.log('Event listener agregado a Tom-select');
            } else if (profileListSelectElement) {
                // Fallback para select nativo
                profileListSelectElement.addEventListener('change', function() {
                    console.log('Evento change del select disparado');
                    refreshCandidatesDisplay();
                });
                console.log('Event listener agregado al select');
            } else {
                console.error('No se encontró el elemento profile_list');
            }
        }

    })();

</script>

<style>
    /* Ensure footer stays at bottom */
    main.detalle {
        display: flex;
        flex-direction: column;
        flex-grow: 1;
    }
    
    /* Estilos para los botones de remover en Tom-select */
    .ts-wrapper.multi .ts-control .item .remove,
    .ts-control .item .remove,
    [data-ts-item] .remove {
        border-left: 1px solid rgba(0, 0, 0, 0.2);
        padding: 0 8px !important;
        margin-left: 8px !important;
        cursor: pointer !important;
        font-weight: bold !important;
        color: #999 !important;
        display: inline-block !important;
        opacity: 1 !important;
        visibility: visible !important;
        pointer-events: auto !important;
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
    }

    .ts-wrapper.multi .ts-control .item .remove:hover,
    .ts-control .item .remove:hover,
    [data-ts-item] .remove:hover {
        background-color: rgba(0, 0, 0, 0.1) !important;
        color: #d00 !important;
    }

    /* Asegurar que los items removibles sean visibles */
    .ts-wrapper.multi .ts-control .item,
    .ts-control .item,
    [data-ts-item] {
        display: inline-flex !important;
        align-items: center !important;
        padding: 4px 8px !important;
        margin: 2px !important;
        background-color: #e8e8e8 !important;
        border: 1px solid #ddd !important;
        border-radius: 4px !important;
    }

    /* Forzar visibilidad de elementos de remover */
    .ts-wrapper .ts-control .item .remove-button,
    .ts-wrapper .ts-control .item [class*="remove"],
    .ts-wrapper .ts-control .item [class*="Remove"] {
        display: inline-block !important;
        visibility: visible !important;
        opacity: 1 !important;
    }
</style>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('unal', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>