<?php $__env->startSection('form'); ?>

    <div id="msg-alert" class="alert alert-success d-none"></div>
    <?php if($msg): ?>
        <div class="alert alert-success" role="alert">
            <?php echo e($msg); ?>

        </div>
    <?php endif; ?>
    
    <div class="panel panel-default">

        <div class="panel-heading">
            <strong>Enviar</strong>
        </div>
        <div class="panel-body">
            
            <div class="form-group">
                <br>
                
                <div class="col-md-4 col-md-offset-4 text-center" >
                    <?php echo csrf_field(); ?>

                    <input class="text-center" id="check" class="checkbox" name="check" type="checkbox"
                        <?php if($aspirante->formulario_enviado == 'SI'): ?> checked <?php endif; ?> required>
                    <strong >&ensp; He completado satisfactoriamente el formulario.</strong>
                    <br>
                    <br>
                    <button id="sendDocuments" type="button"  <?php if($aspirante->formulario_enviado == 'SI'): ?> class="btn btn-success" <?php else: ?>  class="btn btn-success" <?php endif; ?>>
                        <i class="fa fa-share-square" aria-hidden="true">
                            <span id="btn-text">
                                <?php if($aspirante->formulario_enviado == 'SI'): ?>
                                Reenviar documentacion
                                <?php else: ?>
                                    Enviar documentacion
                                <?php endif; ?>
                            </span>
                        </i>
                    </button>
                </div>
            </div>

            <div class="col-sm-12 col-md-12 mt-3">
                <hr>
                <p>Recuerde descargar el reporte completo de su hoja de vida al igual que los archivos cargados en el
                    sistema y verificar que toda la información suministrada en esta plataforma es correcta y fue cargada
                    exitosamente. </p>
            </div>
            <?php if($perfiles_seleccionados->isEmpty()): ?>
                <div class="alert alert-warning" role="alert">
                    No se encontraron perfiles seleccionados. Por favor, seleccione primero a que perfiles desea aplicar en
                    la opción <a href="<?php echo e(env('APP_URL')); ?>perfiles" data-path="perfiles" class="alert-link"><i
                            class="fa fa-user" aria-hidden="true"></i>&nbsp;Perfiles</a> e intentelo nuevamente.
                </div>
            <?php else: ?>
            <div class="col-md-4 col-md-offset-4 text-center">
            <form method="get" action="<?php echo e(env('APP_URL')); ?>perfiles/resumen/adjuntos" style="margin:20px 0">
                        <?php echo csrf_field(); ?>

                        <button class="text-center" style="display: inline-block;" type="submit" class="btn btn-primary">
                            <i class="fa fa-folder-open" aria-hidden="true"> <p> Descargar mis archivos adjuntos</p></i>
                        </button>
                    </form>
                </div>
            <?php endif; ?>
    </div>


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


<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('sendDocuments').addEventListener('click', function (e) {
            e.preventDefault();
            
            const check = document.getElementById('check');
            const msgAlert = document.getElementById('msg-alert');
            
            // Verificar que el checkbox esté marcado
            if (!check.checked) {
                msgAlert.classList.remove('d-none');
                msgAlert.classList.remove('alert-success');
                msgAlert.classList.add('alert-danger');
                msgAlert.innerText = "Debe marcar la casilla de confirmación para enviar el formulario";
                return;
            }
            
            // Preparar los datos a enviar
            const formData = new FormData();
            formData.append('check', check.checked ? 'on' : '');
            const csrfToken = document.querySelector('input[name="_token"]').value;
            formData.append('_token', csrfToken);
            
            // Construir URL relativa desde la página actual
            // Si estamos en /concurso2026-dica/perfiles/resumen, extraer /concurso2026-dica
            const currentPath = window.location.pathname;
            let basePath = '';
            const perfilesIndex = currentPath.indexOf('/perfiles/');
            if (perfilesIndex > 0) {
                basePath = currentPath.substring(0, perfilesIndex);
            }
            const checkSubmitionUrl = basePath + '/perfiles/checkSubmition/';
            
            console.log('Current path:', currentPath);
            console.log('Base path:', basePath);
            console.log('URL construida:', checkSubmitionUrl);
            console.log('Token CSRF:', csrfToken ? 'Presente' : 'Faltante');
            
            // Realizar la petición
            fetch(checkSubmitionUrl, {
                method: 'POST',
                headers: { 
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json'
                },
                body: formData
            })
            .then(r => {
                console.log('Respuesta recibida:', r.status, r.statusText);
                if (!r.ok) {
                    return r.text().then(text => {
                        console.error('Error del servidor:', text);
                        throw new Error('HTTP ' + r.status);
                    });
                }
                return r.json();
            })
            .then(data => {
                console.log('Datos recibidos:', data);
                msgAlert.classList.remove('d-none');

                if (data.success) {
                    msgAlert.classList.remove('alert-danger');
                    msgAlert.classList.add('alert-success');
                    msgAlert.innerText = "Formulario enviado correctamente";
                    updateFormState();
                } else {
                    msgAlert.classList.remove('alert-success');
                    msgAlert.classList.add('alert-danger');
                    
                    // Mostrar solo los documentos faltantes
                    if (data.documentos_faltantes && data.documentos_faltantes.length > 0) {
                        const documentosFaltantes = Array.isArray(data.documentos_faltantes) 
                            ? data.documentos_faltantes.join(', ') 
                            : data.documentos_faltantes;
                        msgAlert.innerText = "Faltan los siguientes documentos: " + documentosFaltantes;
                    }
                }
            })
            .catch(error => {
                console.error('Error completo en fetch:', error);
                console.error('URL intentada:', checkSubmitionUrl);
                msgAlert.classList.remove('d-none');
                msgAlert.classList.remove('alert-success');
                msgAlert.classList.add('alert-danger');
                msgAlert.innerText = "Error al verificar documentos. Por favor, recargue la página e intente nuevamente.";
            });
        });
    });

    function updateFormState() {
        const btn = document.getElementById('sendDocuments');
        const btnText = document.getElementById('btn-text');
        const check = document.getElementById('check');

        btn.classList.remove('btn-success');
        btn.classList.add('btn-primary');

        if (btnText) {
            btnText.textContent = "Reenviar documentación";
        }
        check.checked = true;
    }
</script>
<?php echo $__env->make('main', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>