<?= $this->extend('estructura/header_dashboard'); ?>
<?= $this->section('content'); ?>
<!-- ============================================================== -->
<!-- Start right Content here -->
<!-- ============================================================== -->
<div class="main-content">
	<div class="page-content">
		<div class="container-fluid">
			<!-- start page title -->
			<div class="row">
				<div class="col-12">
					<div class="page-title-box d-sm-flex align-items-center justify-content-between">
						<h4 class="mb-sm-0"><?= $breadcrumb_alias ?></h4>
						<div class="page-title-right">
							<ol class="breadcrumb m-0">
								<li class="breadcrumb-item"><a href="javascript: void(0);">Inicio</a></li>
								<li class="breadcrumb-item active"><?= $breadcrumb_alias ?></li>
							</ol>
						</div>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-lg-12">
					<div class="card">
						<div class="card-header d-flex align-items-center">
                            <h5 class="card-title mb-0 flex-grow-1"><?= $breadcrumb_alias ?></h5>
                            <div>
								<a href="<?= $baseUrl.'/'.$previo ?>" class="btn px-2 py-0" style="border-radius: 45%; background-color: red;"><i class="mdi mdi-arrow-left-circle" style="font-size: 24px; color: #FFF"></i></a>
                            </div>
                        </div>
                        
                    </div>
				</div>
			</div>
			<!-- end page title -->
			<div class="row">   
				<div class="col-12">

                    <div class="card card-h-100">
                            <div class="card-body">
                                    <div class="container">
                                    <h2>Calendario de Horarios</h2>
                                    <table id="calendarGeneral" class="table table-striped table-hover" style="width:100%">
                                        <thead>
                                            <tr id="headerRow">
                                                <th>Matrícula</th>
                                                <!-- Las columnas de fecha se agregarán dinámicamente -->
                                            </tr>
                                        </thead>
                                    </table>
                            </div>
                         </div>
                     </div>

                   <!--end row-->
                   <div style="clear:both"></div>

			</div>
		</div>
		<span class="respuesta_global"></span>
		<!-- container-fluid -->
	</div>

</div>

                   <!-- Add New Event MODAL -->
                   <div id="infoModal" class="modal fade" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered">
                         <div class="modal-content border-0">
                            <div class="modal-header p-3 bg-info-subtle">
                               <h5 class="modal-title" id="modal-title">Evento</h5>
                               <button type="button" class="btn-close" data-bs-dismiss="modal" aria-hidden="true"></button>
                            </div>
                            <div class="modal-body p-4">
                               <form class="formulario view-event" name="event-form" action="<?=$baseUrl ?>/actualizar-planificacion-general" id="form-event" novalidate="" autocomplete="off" method="POST">
                                   <span class="respuesta"></span>
                                  <!--<div class="text-end">-->
                                  <!--   <a href="#" class="btn btn-sm btn-soft-primary" id="edit-event-btn" data-id="edit-event" onclick="editEvent(this)" role="button">Editar</a>-->
                                  <!--</div>-->
                                  <!--<div class="event-details">-->
                                  <!--   <div class="d-flex mb-2">-->
                                  <!--      <div class="flex-grow-1 d-flex align-items-center">-->
                                  <!--         <div class="flex-shrink-0 me-3">-->
                                  <!--            <i class="ri-calendar-event-line text-muted fs-16"></i>-->
                                  <!--         </div>-->
                                  <!--         <div class="flex-grow-1">-->
                                  <!--            <h6 class="d-block fw-semibold mb-0" id="event-start-date-tag"></h6>-->
                                  <!--         </div>-->
                                  <!--      </div>-->
                                  <!--   </div>-->
                                  <!--   <div class="d-flex align-items-center mb-2">-->
                                  <!--      <div class="flex-shrink-0 me-3">-->
                                  <!--         <i class="ri-time-line text-muted fs-16"></i>-->
                                  <!--      </div>-->
                                  <!--      <div class="flex-grow-1">-->
                                  <!--         <h6 class="d-block fw-semibold mb-0"><span id="event-timepicker1-tag"></span> - <span id="event-timepicker2-tag"></span></h6>-->
                                  <!--      </div>-->
                                  <!--   </div>-->
                                  <!--   <div class="d-flex align-items-center mb-2">-->
                                  <!--      <div class="flex-shrink-0 me-3">-->
                                  <!--         <i class="ri-bookmark-line text-muted fs-16"></i>-->
                                  <!--      </div>-->
                                  <!--      <div class="flex-grow-1">-->
                                  <!--         <h6 class="d-block fw-semibold mb-0"> <span id="event-grupo-trabajo-tag"></span></h6>-->
                                  <!--      </div>-->
                                  <!--   </div>-->
                                  <!--   <div class="d-flex mb-3">-->
                                  <!--      <div class="flex-shrink-0 me-3">-->
                                  <!--         <i class="ri-shield-user-line text-muted fs-16"></i>-->
                                  <!--      </div>-->
                                  <!--      <div class="flex-grow-1">-->
                                  <!--         <p class="d-block text-muted mb-0" id="event-jefe-grupo-trabajo-tag"></p>-->
                                  <!--      </div>-->
                                  <!--   </div>-->
                                  <!--</div>-->
                                  <div class="row event-form">
                                     <div class="col-12">
                                        <div class="mb-3">
                                           <label for="lista_horarios" class="form-label">Horarios</label>

                                                 <select class="form-select" name="lista_horarios" id="lista_horarios" required="" tabindex="-1" data-choice="active">
                                                    <option value="bg-danger-subtle" data-custom-properties=""></option>
                                                 </select>

                                           <div class="invalid-feedback">Por favor seleccione una categoría de evento válida</div>
                                        </div>
                                     </div>
                                     <!--end col-->
                                     <div class="col-12">
                                        <div class="mb-3">
                                           <label for="modalMatricula" class="form-label">Matricula | Usuario</label>
                                           <input class="form-control" placeholder="Código Horario" type="text" name="modalMatricula" id="modalMatricula" required="" value="" disabled>
                                           <input type="hidden" id="idUsuarioPlanificacion" name="idUsuarioPlanificacion">
                                           <input type="hidden" id="idPlanificacion" name="idPlanificacion">
                                           <div class="invalid-feedback">Por favor proporcione un nombre de evento válido</div>
                                        </div>
                                     </div>
                                     <!--end col-->
                                     <div class="col-12">
                                        <div class="mb-3">
                                           <label for="fecha_planificacion">Fecha del evento</label>
                                           <div class="input-group">
                                              <input type="text" id="fecha_planificacion" name="fecha_planificacion" class="form-control flatpickr flatpickr-input" placeholder="Select date" required="" disabled>
                                              <span class="input-group-text"><i class="ri-calendar-event-line"></i></span>
                                           </div>
                                        </div>
                                     </div>

                                     <div class="col-12">
                                        <div class="mb-3">
                                           <label for="modalTurno">Turno</label>
                                           <div>
                                              <input type="text" class="form-control" name="modalTurno" id="modalTurno" placeholder="Turno" disabled>
                                           </div>
                                        </div>
                                     </div>
                                     <!--end col-->

                                     <div class="col-12">
                                        <div class="mb-3">
                                           <label for="lider_grupo_trabajo" class="form-label">Lider Grupo Trabajo</label>
                                           <div>
                                              <input type="text" class="form-control" name="lider_grupo_trabajo" id="lider_grupo_trabajo" placeholder="Jefe Grupo Trabajo" disabled>
                                           </div>
                                           <!--<textarea class="form-control d-none" id="event-description" placeholder="Enter a description" rows="3" spellcheck="false"></textarea>-->
                                        </div>
                                     </div>
                                     <div class="col-12">
                                        <div class="mb-3">
                                            <label for="motivo_cambio_planificacion_horaria" class="form-label">Motivo</label>
                                            <textarea class="form-control" id="motivo_cambio_planificacion_horaria" name="motivo_cambio_planificacion_horaria" placeholder="Motivo del cambio" rows="3" spellcheck="false"></textarea>
                                        </div>
                                     </div>
                                     <!--end col-->
                                  </div>
                                  <!--end row-->
                                  <div class="hstack gap-2 justify-content-end">
                                     <button type="button" class="btn btn-soft-danger d-none" id="btn-delete-planificacion-horaria"><i class="ri-close-line align-bottom"></i> Borrar</button>
                                     <button type="submit" class="btn btn-success" id="btn-update-planificacion" >Actualizar</button>
                                  </div>
                               </form>
                            </div>
                         </div>
                         <!-- end modal-content-->
                      </div>
                      <!-- end modal dialog-->
                   </div>
                   <!-- end modal-->
                   
                  
<?= $this->section('js'); ?>
    <script>
$(document).ready(function() {

    var idGrupoTrabajo = <?= $idGrupoTrabajo ?>;
    
    // Hacer una solicitud AJAX para cargar los datos
    $.ajax({
        url: baseUrl + "/calendario-general-planificacion",
        type: 'POST',
        dataType: 'json',
        data: {
            idGrupoTrabajo: idGrupoTrabajo
        },
        success: function(response) {
            // console.log("Datos recibidos:", response);

            // Crear una lista única de fechas para las columnas
            let fechas = [];
            let datosPorMatricula = {};

            // Organizar datos por matrícula y recolectar fechas
            response.forEach(function(evento) {
                const matricula = evento.matricula.split(" - ")[0];
                const fecha = evento.start.split(" ")[0];  // Extraer la fecha
                // console.log(evento.matricula + ' ' + evento.id_horario+ ' ' +fecha);

                // Agregar la fecha a la lista si no está ya
                if (!fechas.includes(fecha)) {
                    fechas.push(fecha);
                }

                // Si no existe la matrícula en `datosPorMatricula`, inicializarla
                if (!datosPorMatricula[matricula]) {
                    datosPorMatricula[matricula] = {};
                }
                
                datosPorMatricula[matricula][fecha] = { 
                    matricula: matricula,
                    motivo: evento.motivo,
                    jefeGrupoTrabajo: evento.jefeGrupoTrabajo,
                    id_horario: evento.id_horario,
                    idUsuarioPlanificacion: evento.idUsuarioPlanificacion,
                    id_planificacion: evento.id_planificacion,
                    nombreUsuarioPlanificacion: evento.nombreUsuarioPlanificacion,
                    horario: evento.title  // Asignar el turno para el título del evento
                };

            });
            
            // Ordenar las fechas para que aparezcan en orden cronológico
            fechas.sort();

            // Agregar encabezados dinámicamente al HTML de la tabla
            let headerRow = $("#headerRow");
            fechas.forEach(fecha => {
                headerRow.append(`<th>${fecha}</th>`);
            });

            // Convertir `datosPorMatricula` a un array de objetos para DataTables
            let data = Object.keys(datosPorMatricula).map(matricula => {
                let row = { matricula: matricula };
                
                // Llenar cada fecha con el objeto completo o un valor vacío si no existe
                fechas.forEach(fecha => {
                    row[fecha] = datosPorMatricula[matricula][fecha] || { horario: "", jefeGrupoTrabajo: "", id_horario: "", idUsuarioPlanificacion: "", nombreUsuarioPlanificacion: "", id_planificacion: "", motivo: "" };
                });
            
                return row;
            });

            // Inicializar DataTable con las columnas dinámicas
            var table = $('#calendarGeneral').DataTable({
                data: data,
                columns: [
                    { data: "matricula", title: "Matrícula" },
                    ...fechas.map(fecha => ({ 
                            data: fecha + ".horario",  // Mostrar el turno en cada columna de fecha
                            title: fecha 
                        })) // Crear columnas para cada fecha
                    // { data: "jefeGrupoTrabajo", visible: false }
                ],
                lengthMenu: [[50], [50]],
                responsive: false,
                autoWidth: false,
                scrollX: true,    // Permitir desplazamiento horizontal
                paging: true,     // Agregar paginación
                searching: true,  // Agregar búsqueda
                ordering: true,    // Permitir ordenamiento de columnas
                createdRow: function(row, rowData, dataIndex) {
                    // Agrega una clase a todas las celdas para cambiar el cursor
                    fechas.forEach((fecha, index) => {
                        // Accede al `id_horario` de cada fecha en la fila de datos
                        var idHorario = rowData[fecha] ? rowData[fecha].id_horario : "";
            
                        // Añade el `data-horario` a la celda correspondiente
                        $('td:eq(' + (index + 1) + ')', row).attr("data-horario", idHorario);
                    });
            
                    // Agrega clase de cursor a todas las celdas
                    $(row).find('td').addClass('pointer-cursor');
                }
            });
                    // Manejar clics en celdas específicas para abrir el modal
            $('#calendarGeneral tbody').on('click', 'td', function() {
                // Obtener la información de la celda seleccionada
                var cellData = table.cell(this).data(); 
                var columnIndex = table.cell(this).index().column; 
                var rowData = table.row(this).data(); 

                // Obtener matrícula, fecha y turno
                var matricula = rowData.matricula;
                var fecha = table.column(columnIndex).header().textContent;
                var turno = cellData || "Sin turno";
                var jefeGrupoTrabajo = rowData[table.column(columnIndex).header().textContent].jefeGrupoTrabajo;
                var idHorario = rowData[table.column(columnIndex).header().textContent].id_horario;
                var idUsuarioPlanificacion = rowData[table.column(columnIndex).header().textContent].idUsuarioPlanificacion; 
                var nombreUsuarioPlanificacion = rowData[table.column(columnIndex).header().textContent].nombreUsuarioPlanificacion; 
                var idPlanificacion = rowData[table.column(columnIndex).header().textContent].id_planificacion; 
                var motivo = rowData[table.column(columnIndex).header().textContent].motivo;
                
                // Verificar si los valores esenciales están presentes
                if (!idHorario || !idPlanificacion) {
                    return; // Si no hay `id_horario` o `id_planificacion`, no abrir el modal
                }
                // Mostrar los datos en el modal
                $('#modalMatricula').val(matricula +' | ' +nombreUsuarioPlanificacion);
                $('#fecha_planificacion').val(fecha);
                $('#modalTurno').val(turno);
                $('#lider_grupo_trabajo').val(jefeGrupoTrabajo);
                $('#idUsuarioPlanificacion').val(idUsuarioPlanificacion);
                $('#idPlanificacion').val(idPlanificacion);
                $('#motivo_cambio_planificacion_horaria').val(motivo);
                // Abrir el modal
                $('#infoModal').modal('show');
                
                selectHorariosEstructura('lista_horarios', idUsuarioPlanificacion, idHorario, 'infoModal');
            });
        },
        error: function(xhr) {
            console.error('Error al cargar los datos:', xhr);
            alert('Hubo un error al cargar los datos del servidor.');
        }
    });
});



    </script>
<?php $this->endSection(); ?>

<!-- end main content-->

<div class="flatpickr-calendar rangeMode animate" tabindex="-1">
   <div class="flatpickr-months">
      <span class="flatpickr-prev-month flatpickr-disabled">
         <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 17 17">
            <g></g>
            <path d="M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z"></path>
         </svg>
      </span>
      <div class="flatpickr-month">
         <div class="flatpickr-current-month">
            <select class="flatpickr-monthDropdown-months" aria-label="Month" tabindex="-1">
               <option class="flatpickr-monthDropdown-month" value="6" tabindex="-1">July</option>
               <option class="flatpickr-monthDropdown-month" value="7" tabindex="-1">August</option>
               <option class="flatpickr-monthDropdown-month" value="8" tabindex="-1">September</option>
               <option class="flatpickr-monthDropdown-month" value="9" tabindex="-1">October</option>
               <option class="flatpickr-monthDropdown-month" value="10" tabindex="-1">November</option>
               <option class="flatpickr-monthDropdown-month" value="11" tabindex="-1">December</option>
            </select>
            <div class="numInputWrapper"><input class="numInput cur-year" type="number" tabindex="-1" aria-label="Year" min="2024"><span class="arrowUp"></span><span class="arrowDown"></span></div>
         </div>
      </div>
      <span class="flatpickr-next-month">
         <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 17 17">
            <g></g>
            <path d="M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z"></path>
         </svg>
      </span>
   </div>
   <div class="flatpickr-innerContainer">
      <div class="flatpickr-rContainer">
         <div class="flatpickr-weekdays">
            <div class="flatpickr-weekdaycontainer">
               <span class="flatpickr-weekday">
               Sun</span><span class="flatpickr-weekday">Mon</span><span class="flatpickr-weekday">Tue</span><span class="flatpickr-weekday">Wed</span><span class="flatpickr-weekday">Thu</span><span class="flatpickr-weekday">Fri</span><span class="flatpickr-weekday">Sat
               </span>
            </div>
         </div>
         <div class="flatpickr-days" tabindex="-1">
            <div class="dayContainer"><span class="flatpickr-day prevMonthDay flatpickr-disabled" aria-label="June 30, 2024">30</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 1, 2024">1</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 2, 2024">2</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 3, 2024">3</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 4, 2024">4</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 5, 2024">5</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 6, 2024">6</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 7, 2024">7</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 8, 2024">8</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 9, 2024">9</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 10, 2024">10</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 11, 2024">11</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 12, 2024">12</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 13, 2024">13</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 14, 2024">14</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 15, 2024">15</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 16, 2024">16</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 17, 2024">17</span><span class="flatpickr-day flatpickr-disabled" aria-label="July 18, 2024">18</span><span class="flatpickr-day today" aria-label="July 19, 2024" aria-current="date" tabindex="-1">19</span><span class="flatpickr-day" aria-label="July 20, 2024" tabindex="-1">20</span><span class="flatpickr-day" aria-label="July 21, 2024" tabindex="-1">21</span><span class="flatpickr-day" aria-label="July 22, 2024" tabindex="-1">22</span><span class="flatpickr-day" aria-label="July 23, 2024" tabindex="-1">23</span><span class="flatpickr-day" aria-label="July 24, 2024" tabindex="-1">24</span><span class="flatpickr-day" aria-label="July 25, 2024" tabindex="-1">25</span><span class="flatpickr-day" aria-label="July 26, 2024" tabindex="-1">26</span><span class="flatpickr-day" aria-label="July 27, 2024" tabindex="-1">27</span><span class="flatpickr-day" aria-label="July 28, 2024" tabindex="-1">28</span><span class="flatpickr-day" aria-label="July 29, 2024" tabindex="-1">29</span><span class="flatpickr-day" aria-label="July 30, 2024" tabindex="-1">30</span><span class="flatpickr-day" aria-label="July 31, 2024" tabindex="-1">31</span><span class="flatpickr-day nextMonthDay" aria-label="August 1, 2024" tabindex="-1">1</span><span class="flatpickr-day nextMonthDay" aria-label="August 2, 2024" tabindex="-1">2</span><span class="flatpickr-day nextMonthDay" aria-label="August 3, 2024" tabindex="-1">3</span><span class="flatpickr-day nextMonthDay" aria-label="August 4, 2024" tabindex="-1">4</span><span class="flatpickr-day nextMonthDay" aria-label="August 5, 2024" tabindex="-1">5</span><span class="flatpickr-day nextMonthDay" aria-label="August 6, 2024" tabindex="-1">6</span><span class="flatpickr-day nextMonthDay" aria-label="August 7, 2024" tabindex="-1">7</span><span class="flatpickr-day nextMonthDay" aria-label="August 8, 2024" tabindex="-1">8</span><span class="flatpickr-day nextMonthDay" aria-label="August 9, 2024" tabindex="-1">9</span><span class="flatpickr-day nextMonthDay" aria-label="August 10, 2024" tabindex="-1">10</span></div>
         </div>
      </div>
   </div>
</div>
<div class="flatpickr-calendar hasTime noCalendar animate" tabindex="-1">
   <div class="flatpickr-time" tabindex="-1">
      <div class="numInputWrapper"><input class="numInput flatpickr-hour" type="number" aria-label="Hour" tabindex="-1" step="1" min="1" max="12" maxlength="2"><span class="arrowUp"></span><span class="arrowDown"></span></div>
      <span class="flatpickr-time-separator">:</span>
      <div class="numInputWrapper"><input class="numInput flatpickr-minute" type="number" aria-label="Minute" tabindex="-1" step="5" min="0" max="59" maxlength="2"><span class="arrowUp"></span><span class="arrowDown"></span></div>
      <span class="flatpickr-am-pm" title="Click to toggle" tabindex="-1">PM</span>
   </div>
</div>
<div class="flatpickr-calendar hasTime noCalendar animate" tabindex="-1">
   <div class="flatpickr-time" tabindex="-1">
      <div class="numInputWrapper"><input class="numInput flatpickr-hour" type="number" aria-label="Hour" tabindex="-1" step="1" min="1" max="12" maxlength="2"><span class="arrowUp"></span><span class="arrowDown"></span></div>
      <span class="flatpickr-time-separator">:</span>
      <div class="numInputWrapper"><input class="numInput flatpickr-minute" type="number" aria-label="Minute" tabindex="-1" step="5" min="0" max="59" maxlength="2"><span class="arrowUp"></span><span class="arrowDown"></span></div>
      <span class="flatpickr-am-pm" title="Click to toggle" tabindex="-1">PM</span>
   </div>
</div>

<?php $this->endSection(); ?>