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


<div class="panel panel-default">
  <?php if($msg): ?>
  <div id="msg" data-toggle="modal"  data-toggle="modal" data-target="#ss"class="alert alert-success" role="alert">
      <?php echo e($msg); ?>

  </div>
  <div class="modal fade" id="ss" tabindex="-1" role="dialog" aria-labelledby="ss">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-body" style="background: #dff0d8; border-radius: 8px; text-align: center; font-size: 16pt;color: #3c763d;">
          <?php echo e($msg); ?>

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

  <?php endif; ?>
    <div class="panel-heading">
        <strong>Componente escrito por perfil</strong>
    </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: ?>
    <form name="registro" id="registro" method="post" action="<?php echo e(env('APP_URL')); ?>perfiles/ensayos" class="form-horizontal" style="margin:20px 0"  enctype="multipart/form-data">
        <?php echo csrf_field(); ?>

        <div class="panel-body">
            <?php foreach($perfiles_seleccionados as $perfil_seleccionado): ?>
            <div class="well">
                <div class="form-group">
                    <label for="adjunto_<?php echo e($perfil_seleccionado->id); ?>" class="col-sm-12 col-md-6 control-label">Componente escrito para el perfil <?php echo e($perfil_seleccionado->identificador); ?> - <?php echo e($perfil_seleccionado->departamento); ?>: </label>
                    <div class="col-sm-12 col-md-4">
                        <input id="adjunto_<?php echo e($perfil_seleccionado->id); ?>" type="file" class="form-control" name="adjunto_<?php echo e($perfil_seleccionado->id); ?>" accept=".doc,.docx,.odt,.rtf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.oasis.opendocument.text,application/rtf" required/>
                        <div id="error_<?php echo e($perfil_seleccionado->id); ?>" class="alert alert-danger" style="display: none; margin-top: 10px;"></div>
                        <br><em>Por favor, tenga en cuenta que el archivo adjunto debe estar en formato Word o compatible (.doc, .docx, .odt, .rtf) y no tener un tamaño superior a 9MB</em>
                    </div>
                    <div class="col-sm-12 col-md-4">
                        <?php if($perfil_seleccionado->ruta_ensayo): ?>
                        Archivo cargado previamente: <a style="color:#428bca;" href="<?php echo e(env('APP_URL').$perfil_seleccionado->ruta_ensayo); ?>" download>Ensayo</a>
                        <br><em>Por favor, tenga en cuenta que al cargar un nuevo archivo, se actualizará el archivo previamente cargado</em>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <div class="form-group">
                <div class="col-md-4 col-md-offset-4">
                    <button type="submit" id="submit" class="btn btn-success form-control">
                        <i class="fa fa-book" aria-hidden="true"></i>
                        <i class="fa fa-plus" aria-hidden="true"></i>
                        Guardarensayos
                    </button>
                </div>
            </div>
        </div>
    </form>
    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Trigger del mensaje modal si existe
        var msgElement = document.getElementById("msg");
        if (msgElement) {
            msgElement.click();
        }

        // Constantes de validación
        const MAX_FILE_SIZE = 9 * 1024 * 1024; // 9MB en bytes
        const ALLOWED_EXTENSIONS = ['.doc', '.docx', '.odt', '.rtf'];
        const ALLOWED_MIME_TYPES = [
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.oasis.opendocument.text',
            'application/rtf',
            'text/rtf'
        ];

        // Función para obtener la extensión del archivo
        function getFileExtension(filename) {
            var lastDot = filename.lastIndexOf('.');
            if (lastDot === -1) return '';
            return filename.substring(lastDot).toLowerCase();
        }

        // Función para validar archivo
        function validateFile(file, inputId, errorDivId) {
            var errorDiv = document.getElementById(errorDivId);
            var submitButton = document.getElementById('submit');
            var isValid = true;
            var errorMessages = [];

            // Validar extensión
            var extension = getFileExtension(file.name);
            var isValidExtension = ALLOWED_EXTENSIONS.includes(extension);
            var isValidMimeType = file.type && ALLOWED_MIME_TYPES.includes(file.type);

            // Si no tiene tipo MIME, validar solo por extensión
            // Si tiene tipo MIME, validar por ambos
            if (!isValidExtension && (!file.type || !isValidMimeType)) {
                isValid = false;
                errorMessages.push('El archivo debe ser un documento Word o compatible (.doc, .docx, .odt, .rtf)');
            }

            // Validar tamaño
            if (file.size > MAX_FILE_SIZE) {
                isValid = false;
                var fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
                errorMessages.push('El archivo es demasiado grande (' + fileSizeMB + 'MB). El tamaño máximo permitido es 9MB');
            }

            // Mostrar errores o limpiarlos
            if (!isValid) {
                errorDiv.innerHTML = errorMessages.join('<br>');
                errorDiv.style.display = 'block';
                if (submitButton) {
                    submitButton.disabled = true;
                }
            } else {
                errorDiv.style.display = 'none';
                errorDiv.innerHTML = '';
                if (submitButton) {
                    submitButton.disabled = false;
                }
            }

            return isValid;
        }

        // Validar todos los inputs de archivo al cambiar
        var fileInputs = document.querySelectorAll('input[type="file"][name^="adjunto"]');
        fileInputs.forEach(function(input) {
            input.addEventListener('change', function() {
                if (this.files && this.files.length > 0) {
                    var file = this.files[0];
                    var inputId = this.id;
                    var errorDivId = 'error_' + inputId.replace('adjunto_', '');
                    validateFile(file, inputId, errorDivId);
                }
            });
        });

        // Validar al enviar el formulario
        var form = document.getElementById('registro');
        if (form) {
            form.addEventListener('submit', function(e) {
                var allValid = true;
                var hasFiles = false;

                fileInputs.forEach(function(input) {
                    if (input.files && input.files.length > 0) {
                        hasFiles = true;
                        var file = input.files[0];
                        var inputId = input.id;
                        var errorDivId = 'error_' + inputId.replace('adjunto_', '');
                        if (!validateFile(file, inputId, errorDivId)) {
                            allValid = false;
                        }
                    }
                });

                if (!allValid) {
                    e.preventDefault();
                    alert('Por favor, corrija los errores antes de enviar el formulario.');
                    return false;
                }
            });
        }
    });
</script>

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

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