<?php
require_once('../../config/Conexion.php');
ob_start();
ini_set('session.gc_maxlifetime', 14400);
session_set_cookie_params(14400);
session_start();

if (!isset($_SESSION["nombre"]))
{
    header("Location: ../../login/login.php");
}
else
{
    require '../header.php';

if($_SESSION['averia']==1){

    $sql="SELECT idagenda as id, title, start, end, color,idaveria FROM agenda";
    $events = ejecutarConsulta($sql);

?>



            <div class="content-wrapper">
                <!-- Breadcrumb Section -->
                <section class="content-header">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-sm-12">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb">
                                        <li class="breadcrumb-item">
                                            <a href="#"><i class="fas fa-home"></i> Panel</a>
                                        </li>
                                        <li class="breadcrumb-item active" aria-current="page">
                                            <a href="list.php">
                                                <i class="module-icon"></i> Averia
                                            </a>
                                        </li>
                                    </ol>
                                </nav>
                            </div>
                          
                            <div class="col-sm-12" style="margin-top: 20px;">
                                <form class="form" method="post"  id="frmForm" autocomplete="off">
                                    <div class="card">
                                        <div class="card-header">
                                            <h3 class="card-title" id="idtitle" >
                                                <i class="fas fa-plus"></i> <!-- Icono para agregar -->
                                                Registro de Trabajos<!-- Título del formulario -->
                                            </h3>
                                        </div>
                                        <div class="card-body" style="display: block;">
                                            <div class="container-fluid">
                                                <input type="hidden" name="idaveria" id="idaveria">
                                                <div class="row">
                                                    <!-- Primera columna -->
                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label for="idpersona">Nombre Cliente:</label>
                                                            <select  name="idpersona" id="idpersona" class="form-control"  data-live-search="true" data-style="btn-default" required>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <!-- Segunda columna -->
                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Servicios Contratados:</label>
                                                            <select  name="idcontrato" id="idcontrato" class="form-control"  data-live-search="true" data-style="btn-default">
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <input type="hidden" class="form-control" name="title1" id="title1" >   
                                                    <input type="hidden" class="form-control" name="color1" id="color1" >   
                                                    <input type="hidden" name="start1"  id="start1">  
                                                    <input type="hidden"  name="end1" id="end1" > 
                                                    <input type="hidden" class="form-control" name="tecnologia" id="tecnologia" >  
                                                    <input type="hidden" class="form-control" name="iddireccion" id="iddireccion" >
                                                    <input type="hidden" class="form-control" name="latitud" id="latitud" > 
                                                    <input type="hidden" class="form-control" name="longitud" id="longitud" > 
                                                    <input type="hidden" class="form-control" name="idincidencia" id="idincidencia" > 
                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label >Estado Servicio:</label>
                                                            <input type="text" class="form-control" name="sit_contrato" id="sit_contrato"  placeholder="Estado Servicio" readonly="">
                                                        </div>
                                                    </div>
                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Fecha Trabajo:</label>
                                                            <input type="date" class="form-control" name="fecha_hora" id="fecha_hora" value="<?php echo date("Y-m-d")?>" readonly="">
                                                        </div>
                                                    </div>
                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label for="direccion" >Direccion:</label>
                                                            <input type="text" class="form-control" name="direccion" id="direccion"  placeholder="Direccion" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-6">
                                                        <div class="form-group">
                                                            <label>Referencia:</label>
                                                            <input type="text" class="form-control" name="referencia" id="referencia"  placeholder="Referencia" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Distrito:</label>
                                                            <input type="text" class="form-control" name="distrito" id="distrito"  placeholder="Distrito" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Celular 01:</label>
                                                            <input type="text" class="form-control" name="celular1" id="celular1"  placeholder="Celular 01" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Celular 02:</label>
                                                            <input type="text" class="form-control" name="celular2" id="celular2"  placeholder="Celular 02" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-6">
                                                        <div class="form-group">
                                                            <label>Detalle Problema:</label>
                                                            <input type="text" class="form-control" name="detalle_problema" id="detalle_problema"  placeholder="Detalle Problema" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-6">
                                                        <div class="form-group">
                                                            <label>Observaciones Call Center:</label>
                                                            <input type="text" class="form-control" name="observacion" id="observacion"  placeholder="Observacion" >
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Categoria:</label>
                                                            <select  name="idcategoria_ingreso" id="idcategoria_ingreso" class="form-control"  data-live-search="true" data-style="btn-default" required>
                                                            </select>
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Tipo Trabajo:</label>
                                                            <select  name="idconcepto_ingreso" id="idconcepto_ingreso" class="form-control"  data-live-search="true" data-style="btn-default" required>
                                                            </select>
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label for="prioridad">Prioridad:</label>
                                                            <select  name="prioridad" id="prioridad" class="form-control"  data-live-search="true" data-style="btn-default" required>
                                                                <option value="">Seleccione Estado</option>
                                                                <option value="Pendiente - Alto">Pendiente - Alto</option>
                                                                <option value="Pendiente - Medio">Pendiente - Medio</option>
                                                                <option value="Reprogramado - Alto">Reprogramado - Alto</option>      
                                                            </select>
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label>Asignar Tecnico:</label>
                                                            <select  name="idtecnico" id="idtecnico" class="form-control"  data-live-search="true" data-style="btn-default" required>
                                                            </select>
                                                        </div>
                                                    </div>

                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <label for="estado">Estado Trabajo:</label>
                                                            <select  name="estado" id="estado" class="form-control"  data-live-search="true" data-style="btn-default" required>
                                                                <option value="">Seleccione Estado</option>
                                                                <option value="1">Pendiente</option>
                                                                <option value="2">Proceso</option>
                                                                <option value="3">Atendido</option>
                                                                <option value="4">Calificar</option>
                                                                <option value="7">Cerrado</option>      
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-12 col-sm-12 col-md-3">
                                                        <div class="form-group">
                                                            <button id="btnAgregarArt" type="button" class="btn btn-danger btn-xs btn-flat" data-toggle="modal" data-target="#myModalCalendario">
                                                                <span class="fas fa-calendar-days"></span>&nbsp;&nbsp;Agendar Trabajo
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div class="card-footer">
                                                        <!-- Botones de acción -->
                                                        <button  id="btnGuardar" class="btn btn-primary btn-flat">
                                                            <i class="fas fa-save"></i> Guardar registro
                                                        </button>
                                                        <a href="list.php" class="btn btn-danger btn-flat">
                                                            <i class="fas fa-times"></i> Cancelar
                                                        </a>
                                                    </div>
                                                    <br>
                                                    
                                                </div>  
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </section>                
            </div>


            <div class="modal fade" id="myModalCalendario" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl" role="document">
                    <div class="modal-content">
                        <div class="modal-header" style="background:#2c3e50; color:white">
                            <h5 class="modal-title" id="modalLabel"><i class="fa-solid fa-magnifying-glass"></i> Selecione la Fecha</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body table-responsive">
                            <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                <div id="calendar" class="col-centered"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="ModalAdd" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header" style="background:#2c3e50; color:white">
                            <h5 class="modal-title" id="modalLabel"><i class="fa-solid fa-magnifying-glass"></i> Agregar Visita</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body table-responsive">
                        <div class="form-group">
                            <label for="title" class="col-sm-12 control-label">Descripcion</label>
                            <div class="col-sm-12">
                                <input type="text"  class="form-control" id="title" name="title"  placeholder="Agregar una Descripcion">
                            </div>
                        </div>
                        <div class="form-group">
                        <label for="color" class="col-sm-12 control-label">Color</label>
                            <div class="col-sm-12">
                                <select name="color" class="form-control" id="color" >
                                        <option value="">Seleccionar</option>
                                <option style="color:#0071c5;" value="#0071c5">&#9724; Azul oscuro</option>
                                <option style="color:#40E0D0;" value="#40E0D0">&#9724; Turquesa</option>
                                <option style="color:#008000;" value="#008000">&#9724; Verde</option>             
                                <option style="color:#FFD700;" value="#FFD700">&#9724; Amarillo</option>
                                <option style="color:#FF8C00;" value="#FF8C00">&#9724; Naranja</option>
                                <option style="color:#FF0000;" value="#FF0000">&#9724; Rojo</option>
                                <option style="color:#000;" value="#000">&#9724; Negro</option>
                                
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="start" class="col-sm-12 control-label">Fecha Inicial</label>
                            <div class="col-sm-12">
                                <input type="datetime-local" name="start" class="form-control" id="start"  >
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="end" class="col-sm-12 control-label">Fecha Final</label>
                            <div class="col-sm-12">
                                <input type="datetime-local" name="end" class="form-control" id="end" >
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary btn-flat" data-dismiss="modal" ><i class="fas fa-save"></i> Registrar Visita</button>
                        </div>
                        </div>
                    </div>
                </div>
            </div>
            
             <div class="modal fade" id="ModalEdit" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header" style="background:#2c3e50; color:white">
                            <h5 class="modal-title" id="modalLabel"><i class="fa-solid fa-magnifying-glass"></i> Agregar Visita</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body table-responsive">
                        <div class="form-group">
                            <label for="title" class="col-sm-12 control-label">Descripcion</label>
                            <div class="col-sm-12">
                                <input type="text"  class="form-control" id="title" name="title"  placeholder="Agregar una Descripcion">
                            </div>
                        </div>
                        <div class="form-group">
                        <label for="color" class="col-sm-12 control-label">Color</label>
                            <div class="col-sm-12">
                                <select name="color" class="form-control" id="color" >
                                <option value="">Seleccionar</option>
                                <option style="color:#0071c5;" value="#0071c5">&#9724; Azul oscuro</option>
                                <option style="color:#40E0D0;" value="#40E0D0">&#9724; Turquesa</option>
                                <option style="color:#008000;" value="#008000">&#9724; Verde</option>             
                                <option style="color:#FFD700;" value="#FFD700">&#9724; Amarillo</option>
                                <option style="color:#FF8C00;" value="#FF8C00">&#9724; Naranja</option>
                                <option style="color:#FF0000;" value="#FF0000">&#9724; Rojo</option>
                                <option style="color:#000;" value="#000">&#9724; Negro</option>
                                
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="start" class="col-sm-12 control-label">Fecha Inicial</label>
                            <div class="col-sm-12">
                                <input type="datetime-local" name="start" class="form-control" id="start"  >
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="end" class="col-sm-12 control-label">Fecha Final</label>
                            <div class="col-sm-12">
                                <input type="datetime-local" name="end" class="form-control" id="end" >
                            </div>
                        </div>
                        <input type="hidden" name="id" class="form-control" id="id">
                        <input type="hidden" name="idaveria" class="form-control" id="idaveria">
                       
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary btn-flat" data-dismiss="modal" ><i class="fas fa-save"></i> Registrar Visita</button>
                        </div>
                        </div>
                    </div>
                </div>
            </div>



            
               
<?php
}
require '../footer.php';
?>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.js'></script>
<script src='../../static/js/fullcalendar/locale/es.js'></script>
<link href='../../static/css/fullcalendar.css' rel='stylesheet' />
<script type="text/javascript" src="../../scripts/averia.js"></script>
<script>
          

        $(document).ready(function() {
                var date = new Date();
                var yyyy = date.getFullYear().toString();
                var mm = (date.getMonth()+1).toString().length == 1 ? "0"+(date.getMonth()+1).toString() : (date.getMonth()+1).toString();
                var dd  = (date.getDate()).toString().length == 1 ? "0"+(date.getDate()).toString() : (date.getDate()).toString();
                
                $('#calendar').fullCalendar({
                header: {
                    language: 'es',
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay',

                },
                defaultDate: yyyy+"-"+mm+"-"+dd,
                editable: true,
                eventLimit: true, // allow "more" link when too many events
                selectable: true,
                selectHelper: true,
                select: function(start, end) {
                    $("#title").val("");
                    $("#color").val("");
                    $("#start").val("");
                    $("#end").val("");
                    $("#title1").val("");
                    $("#color1").val("");
                    $("#start1").val("");
                    $("#end1").val("");
                    //$('#ModalAdd #start').val(moment(start).format('YYYY-MM-DD HH:mm:ss'));
                    //$('#ModalAdd #end').val(moment(end).format('YYYY-MM-DD HH:mm:ss'));
                    $('#ModalAdd').modal('show');
                },
                eventRender: function(event, element) {
                    element.bind('dblclick', function() {
                    $('#ModalEdit #id').val(event.id);
                    $('#ModalEdit #title').val(event.title);          
                    $('#ModalEdit #color').val(event.color).trigger('change');     
                    $('#ModalEdit #start').val(moment(event.start).format('YYYY-MM-DD HH:mm'));
                    $('#ModalEdit #end').val(moment(event.end).format('YYYY-MM-DD HH:mm:ss'));
                    $('#ModalEdit #idaveria').val(event.idaveria);
                    $('#ModalEdit').modal('show');
                    });
                },
                eventDrop: function(event, delta, revertFunc) { // si changement de position

                    edit(event);

                },
                eventResize: function(event,dayDelta,minuteDelta,revertFunc) { // si changement de longueur

                    edit(event);

                },
                events: [
                <?php foreach($events as $event): 
                
                    $start = explode(" ", $event['start']);
                    $end = explode(" ", $event['end']);
                    if($start[1] == '00:00:00'){
                    $start = $start[0];
                    }else{
                    $start = $event['start'];

                    }
                    if($end[1] == '00:00:00'){
                    $end = $end[0];
                    }else{
                    $end = $event['end'];
                    }
                ?>
                    {
                    id: '<?php echo $event['id']; ?>',
                    title: '<?php echo $event['title']; ?>',
                    start: '<?php echo $start; ?>',
                    end: '<?php echo $end; ?>',
                    color: '<?php echo $event['color'];?>',
                    idaveria: '<?php echo $event['idaveria'];?>',
                    },
                <?php endforeach; ?>
                ]
                });
    


            // Evento para cerrar los modales
            $('.close').click(function() {
                $('#ModalAdd, #ModalEdit').modal('hide');
            });
        });

        $("#title").keyup(function () {
            var value = $(this).val();
            $("#title1").val(value);
        });

        $("#color").change(function(){
        var x = $('#color').val();
        $('#color1').val(x);
        });

        // Copiar el valor del campo "start" del modal al "start1" del formulario principal
        $("#start").change(function() {
            var startValue = $(this).val(); // Obtener el valor del modal
            $('#start1').val(startValue); // Asignar el valor al campo en el formulario principal
        });

        function add24Hours(dateTime) {
        let date = new Date(dateTime);
        date.setHours(date.getHours() + 24); // Agregar 24 horas
        return date.toISOString().slice(0, 16); // Formatear a "YYYY-MM-DDTHH:mm"
        }

        // Actualizar automáticamente la segunda fecha
        $("#start").change(function () {
            let startValue = $(this).val(); // Obtener el valor de la fecha inicial
            if (startValue) {
                let newEndValue = add24Hours(startValue); // Calcular la nueva fecha final
                $("#end").val(newEndValue); // Actualizar el campo "end" en el modal
                $("#start1").val(startValue); // Sincronizar con el formulario principal
                $("#end1").val(newEndValue); // Sincronizar la fecha final en el formulario principal
            }
        });

        // Sincronizar manualmente si se modifica la fecha final
        $("#end").change(function () {
            let endValue = $(this).val();
            $("#end1").val(endValue); // Sincronizar la fecha final en el formulario principal
        });
        
        $("#ModalEdit #title").keyup(function () {
                var value = $(this).val();
                $("#title1").val(value);
            });

            // Sincronizar color desde ModalEdit
            $("#ModalEdit #color").change(function(){
                var x = $(this).val();
                $("#color1").val(x);
            });

            // Sincronizar fecha inicio desde ModalEdit
            $("#ModalEdit #start").change(function () {
                let startValue = $(this).val();
                $("#start1").val(startValue);
            });

            // Sincronizar fecha fin desde ModalEdit
            $("#ModalEdit #end").change(function () {
                let endValue = $(this).val();
                $("#end1").val(endValue);
            });
</script>
<?php 
}
ob_end_flush();
?>