@extends('main')
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
@section('form')

    <div class="alert alert-warning alert-dismissible" role="alert">
        <p><i class="fa fa-exclamation-circle" aria-hidden="true"></i> <strong>Nota: </strong>Por favor, tenga en cuenta que
        toda la información que digite en el formulario, debe registrarse únicamente en español.
        <br>

        @if ($tesis_requieren_soporte)
            <br>
            <p><i class="fa fa-exclamation-circle" aria-hidden="true"></i> <strong>Aviso: </strong> Los siguientes perfiles
            seleccionados requieren soporte de tesis:
            @foreach ($tesis_requieren_soporte as $s)
                <li><strong>{{ $s->identificador }}<strong> - {{ $s->area_desempeno }} </li>
            @endforeach
            </p>
        @endif
    </div>

    <div class="panel panel-default">
        @if ($msg)
            <div id="msg" class="alert alert-success" role="alert" style="cursor: pointer;">
                {{ $msg }}
            </div>
            <div class="modal fade" id="ss" tabindex="-1" role="dialog" aria-labelledby="ss" style="display: none;">
                <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;">
                            {{ $msg }}
                        </div>
                    </div>
                </div>
            </div>
        @endif

        <div class="panel-heading">
            <strong>Tesis</strong>
        </div>
        <form method="post" action="{{ env('APP_URL') }}tesis" class="form-horizontal" style="margin:20px 0"
            enctype="multipart/form-data">
            {!! csrf_field() !!}
            <div class="form-group">
                <label for="titulo" class="col-sm-12 col-md-2 control-label">Titulo</label>
                <div class="col-sm-12 col-md-9">
                    <input type="text" class="form-control" id="titulo" maxlength="500" name="titulo"
                        placeholder="Titulo de la tesis" required>
                </div>
            </div>
            <div class="form-group">
                <label for="fecha_inicio" class="col-sm-12 col-md-2 control-label">Fecha</label>
                <div class="col-sm-12 col-md-5" id="fecha">
                    <div>
                        <label class="form-label required">Fecha</label>
                        <div class="input-group">
                            <input type="date" placeholder="dd/mm/aaaa" class="form-control maxToday" id="fecha" name="fecha" max="{{ \Carbon\Carbon::now()->format('Y-m-d') }}" aria-describedby="fecha-help" required/>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="detalles" class="col-sm-12 col-md-2 control-label">Detalle</label>
                <div class="col-sm-12 col-md-9">
                    <textarea name="detalles" id="detalles" maxlength="600" class="form-control " placehoder="Detalles"></textarea>
                </div>
            </div>

            <div class="form-group">
                <div id="adjunto">
                    <label for="adjunto" class="col-sm-12 col-md-2 control-label">Documento de soporte:</label>
                    <div class="col-sm-12 col-md-5">
                        <input type="file" id="adjunto_input" class="form-control" name="adjunto" accept=".pdf,application/pdf" required>
                        <br><em>Por favor, tenga en cuenta que el archivo adjunto debe estar en formato PDF y no tener un
                            tamaño superior a 9MB</em>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-4 col-md-offset-4">
                    <button type="submit" class="btn btn-success form-control">
                        <i class="fa fa-plus" aria-hidden="true"></i>
                        Guardar tesis
                    </button>
                </div>
            </div>

        </form>

        <div class="panel-heading">
            <strong>Resumen de tesis cargadas</strong>
        </div>
        <div class="panel-body">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Titulo</th>
                        <th>Fecha</th>
                        <th>Detalle</th>
                        <th>Documento de soporte</th>
                        <th>Opciones</th>
                    </tr>
                </thead>
                @forelse($tesis as $t)
                    <tr>
                        <td>
                            {{ $t->titulo }}
                        </td>
                        <td>
                            {{ $t->fecha }}
                        </td>
                        <td>
                            {{ $t->detalles }}
                        </td>
                        <td>
                            <a href="{{ env('APP_URL') . $t->ruta_adjunto }}" download>Documento adjunto</a>
                        </td>
                        <td>
                            <form method="post" action="{{ env('APP_URL') }}tesis/delete"
                                onsubmit="return confirm('¿Está seguro que desea eliminar el idioma seleccionado?');"
                                style="margin:20px 0">
                                {!! csrf_field() !!}
                                <input type="hidden" name="id" value="{{ $t->id }}" />
                                <button type="submit" data-id="{{ $t->id }}" class="btn btn-danger btn-sm">
                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="4">No se han ingresado información asociada.</td>
                    </tr>
                @endforelse
            </table>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Manejar el mensaje de éxito y mostrar modal
            var msgElement = document.getElementById("msg");
            var modalElement = document.getElementById("ss");
            
            if (msgElement && modalElement) {
                msgElement.addEventListener('click', function() {
                    modalElement.style.display = 'block';
                    modalElement.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
                    
                    // Cerrar modal al hacer click fuera de él
                    modalElement.addEventListener('click', function(e) {
                        if (e.target === modalElement) {
                            modalElement.style.display = 'none';
                        }
                    });
                    
                    // Cerrar modal con Escape
                    document.addEventListener('keydown', function(e) {
                        if (e.key === 'Escape' && modalElement.style.display === 'block') {
                            modalElement.style.display = 'none';
                        }
                    });
                });
                
                // Auto-disparar el click del mensaje
                setTimeout(function() {
                    msgElement.click();
                }, 100);
            }

            // Validación de archivos PDF
            var fileInputs = document.querySelectorAll("input[type='file']");
            var MAX_FILE_SIZE = 9 * 1024 * 1024; // 9MB en bytes
            
            fileInputs.forEach(function(input) {
                input.addEventListener('change', function() {
                    var file = this.files[0];
                    if (!file) {
                        return;
                    }
                    
                    // Validar extensión
                    var fileName = file.name.toLowerCase();
                    var isValidExtension = fileName.endsWith('.pdf');
                    
                    // Validar tamaño
                    var isValidSize = file.size <= MAX_FILE_SIZE;
                    
                    // Crear o actualizar mensaje de error
                    var errorDiv = this.parentElement.querySelector('.file-error-message');
                    if (!errorDiv) {
                        errorDiv = document.createElement('div');
                        errorDiv.className = 'file-error-message alert alert-danger';
                        errorDiv.style.marginTop = '5px';
                        this.parentElement.appendChild(errorDiv);
                    }
                    
                    if (!isValidExtension) {
                        errorDiv.textContent = 'El archivo debe ser PDF';
                        errorDiv.style.display = 'block';
                        this.setCustomValidity('El archivo debe ser PDF');
                        return;
                    }
                    
                    if (!isValidSize) {
                        var fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
                        errorDiv.textContent = 'El archivo es demasiado grande (' + fileSizeMB + 'MB). El tamaño máximo permitido es 9MB';
                        errorDiv.style.display = 'block';
                        this.setCustomValidity('El archivo es demasiado grande');
                        return;
                    }
                    
                    // Archivo válido
                    errorDiv.style.display = 'none';
                    this.setCustomValidity('');
                });
            });
        });
    </script>
@stop
