<?php
session_start();
ob_start();
  if(!(isset($_SESSION["k_name"]))){
        header("location:index.php");
        }
        else{  
 include("includes/conect.php");
 include("includes/timezone.php");
 // header("Content-Type:text/html; charset=utf-8");
 

 

// $tipo_ocu_user = $_SESSION['k_ocupacion'];
switch ($_SESSION['k_ocupacion']) {

    // huesped
    case '1':   
        $antelacion =  date("Y".'-'."m".'-'."d" ,strtotime($fecha_actual."+ 0 days")); 
     break;

    // huesped Invitado
    case '2':        
        $antelacion =  date("Y".'-'."m".'-'."d" ,strtotime($fecha_actual."+ 3 days")); 
     break;

    // Propietario
    case '3':      
        $antelacion =  date("Y".'-'."m".'-'."d" ,strtotime($fecha_actual."+ 3 days"));  
     break;
   
   default:
     $antelacion =  date("Y".'-'."m".'-'."d" ,strtotime($fecha_actual."+ 0 days")); 
     break;
 }

$cod_nucleo =  $_SESSION['k_code'];

?>
<!DOCTYPE html>
<html lang="es">


<head>
<?php include('head.php'); 

echo $_SESSION['k_ocupacion'];
?>

<style type="text/css">
  .feather-16{
    width: 16px;
    height: 16px;
}

.feather-24{
    width: 24px;
    height: 24px;
}

.feather-32{
    width: 32px;
    height: 32px;
}
</style>
</head>

<body>
  <div class="loader"></div>
  <div id="app">
    <div class="main-wrapper main-wrapper-1">
      <div class="navbar-bg"></div>
      
      <?php include('navbar.php')?>

      <?php include('sidebar.php')?>
      <!-- Main Content -->

          <div class="main-content">
            <section class="section">


               <div class="col-xl-12 col-lg-12 col-md-12">
                <?php
                if (isset($_GET['full'])) {
                ?>

                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>No disponible!</strong> Capacidad llena para esta Área.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                <?php
                }

                if (isset($_GET['inside'])) {
                ?>

                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <strong>No puedes reservar!</strong> Ya has Reservado en esta u otra área, pirmero debes realizar la salida o cancelar la reserva.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                <?php
                } 

                if (isset($_GET['success'])) {
                ?>

                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Área reservada!</strong> Ha reservado de forma exitosa. Hemos enviado a su Correo un Código de Reservación.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                <?php
                } 

                if (isset($_GET['up'])) {
                ?>

                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Usuario verificado de forma exitosa!</strong>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                <?php
                } 

                if (isset($_GET['fail'])) {
                ?>

                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Error! Usuario no pudo ser verificado.</strong>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                <?php
                } 

                ?>
            </div>

          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h6 mb-0 text-gray-800">
              <?php
              
            //   echo $_SESSION['k_ocupacion'];
                echo strftime(" %d de %B del %Y");
              ?>
            </h1>            
          </div>

        <?php 

        // echo $hora_actual;

        $hora_actual_min = substr($hora_actual, 0,2);

        
        
        
         
            // echo $_SESSION['k_ocupacion'];

        ?>

          <?php 
          
          $tipo_ocu_user = $_SESSION['k_ocupacion'];
           switch ($_SESSION['k_ocupacion']) {

              // huesped
              case '1':
                  
                 
              ?>

          <div class="row ">


            <?php
 
             
                $result_areas = mysqli_query($conexion, "SELECT descripcion, modalidad_reserva, consecucion_reserva, id_area_matriz as id_del_area, nombre_area, url, width_img FROM area_matriz where area_activa = 1 and tipo_ocupacion='0' order by nombre_area asc");
                while($row_areas = mysqli_fetch_array($result_areas)){

                   $image = " <img src='assets/img/banner/".$row_areas['url']."' alt='' width='".$row_areas['width_img']."px' height='100px'>";
                   $label = 'Reservar';
 

                 echo "
                    <div class='col-xl-3 col-lg-6 col-md-6 col-sm-6 col-xs-12'>
                      <div class='card'>
                        <div class='card-statistic-4'>
                          <div class='align-items-center justify-content-between'>
                            <div class='row '>
                              <div class='col-lg-6 col-md-6 col-sm-6 col-xs-6 pr-0 pt-3'>
                                <div class='card-content'>
                                  <h5 class='font-15'>".$row_areas['nombre_area']."</h5>
                                  <input type='hidden' value='".$row_areas['nombre_area']."' id='name_area_".$row_areas['id_del_area']."'>
                                  <h2 class='mb-3 font-14'>";
                                  // if ($row['id_del_area'] == 6){
                                  //   echo "Capacidad: ".$row['capacidad'];
                                  // }
                                  
                                  echo "</h2>
                                  <p class='mb-0'><span class='col-blue'>
                                     
                                  </span></p>                                                                      
                                   
                                    <button type='button' value='".$row_areas['id_del_area']."' class='btn btn-success btn-sm  btnrsv'>
                                      <i class='feather-16' data-feather='calendar'></i> $label
                                    </button> 

                                    <input type='hidden' id='area_".$row_areas['id_del_area']."' value='".$row_areas['nombre_area']."'> 
                                    <input type='hidden' id='modalidad_reserva_".$row_areas['id_del_area']."' value='".$row_areas['modalidad_reserva']."'>
                                    <input type='hidden' id='consecucion_reserva_".$row_areas['id_del_area']."' value='".$row_areas['consecucion_reserva']."'>

                                    
                                    <span href='#' data-toggle='tooltip' title='".$row_areas['descripcion']."' data-placement='right' ><i class='feather-16'  data-feather='info'></i></span>
                                   
                                </div>
                              </div>
                              <div class='col-lg-6 col-md-6 col-sm-6 col-xs-6 pl-0'>
                                <div class='banner-img'>
                                 $image
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>";

                }

            ?>
          </div> 


              <?php
              break; 

              // huésped invitado
              case '2':
                  
                 
              ?>

          <div class="row ">


            <?php
 

                $result_areas = mysqli_query($conexion, "SELECT descripcion, modalidad_reserva, consecucion_reserva, id_area_matriz as id_del_area, nombre_area, url, width_img FROM area_matriz where area_activa = 1 order by nombre_area asc");
                while($row_areas = mysqli_fetch_array($result_areas)){

                   $image = " <img src='assets/img/banner/".$row_areas['url']."' alt='' width='".$row_areas['width_img']."px' height='100px'>";
                   $label = 'Reservar';
 

                 echo "
                    <div class='col-xl-3 col-lg-6 col-md-6 col-sm-6 col-xs-12'>
                      <div class='card'>
                        <div class='card-statistic-4'>
                          <div class='align-items-center justify-content-between'>
                            <div class='row '>
                              <div class='col-lg-6 col-md-6 col-sm-6 col-xs-6 pr-0 pt-3'>
                                <div class='card-content'>
                                  <h5 class='font-15'>".$row_areas['nombre_area']."</h5>
                                  <input type='hidden' value='".$row_areas['nombre_area']."' id='name_area_".$row_areas['id_del_area']."'>
                                  <h2 class='mb-3 font-14'>";
                                  // if ($row['id_del_area'] == 6){
                                  //   echo "Capacidad: ".$row['capacidad'];
                                  // }
                                  
                                  echo "</h2>
                                  <p class='mb-0'><span class='col-blue'>
                                     
                                  </span></p>                                                                      
                                   
                                    <button type='button' value='".$row_areas['id_del_area']."' class='btn btn-success btn-sm  btnrsv'>
                                      <i class='feather-16' data-feather='calendar'></i> $label
                                    </button> 

                                    <input type='hidden' id='area_".$row_areas['id_del_area']."' value='".$row_areas['nombre_area']."'> 
                                    <input type='hidden' id='modalidad_reserva_".$row_areas['id_del_area']."' value='".$row_areas['modalidad_reserva']."'>
                                    <input type='hidden' id='consecucion_reserva_".$row_areas['id_del_area']."' value='".$row_areas['consecucion_reserva']."'>

                                    
                                    <span href='#' data-toggle='tooltip' title='".$row_areas['descripcion']."' data-placement='right' ><i class='feather-16'  data-feather='info'></i></span>
                                   
                                </div>
                              </div>
                              <div class='col-lg-6 col-md-6 col-sm-6 col-xs-6 pl-0'>
                                <div class='banner-img'>
                                 $image
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>";

                }

            ?>
          </div> 


              <?php
              break;  

              // Propietario
              case '3':
                 
              ?>

          <div class="row ">


            <?php
 

                $result_areas = mysqli_query($conexion, "SELECT descripcion, modalidad_reserva, consecucion_reserva, id_area_matriz as id_del_area, nombre_area, url, width_img FROM area_matriz where area_activa = 1 order by nombre_area asc");
                while($row_areas = mysqli_fetch_array($result_areas)){

                   $image = " <img src='assets/img/banner/".$row_areas['url']."' alt='' width='".$row_areas['width_img']."px' height='100px'>";
                   $label = 'Reservar';
 

                 echo "
                    <div class='col-xl-3 col-lg-6 col-md-6 col-sm-6 col-xs-12'>
                      <div class='card'>
                        <div class='card-statistic-4'>
                          <div class='align-items-center justify-content-between'>
                            <div class='row '>
                              <div class='col-lg-6 col-md-6 col-sm-6 col-xs-6 pr-0 pt-3'>
                                <div class='card-content'>
                                  <h5 class='font-15'>".$row_areas['nombre_area']."</h5>
                                  <input type='hidden' value='".$row_areas['nombre_area']."' id='name_area_".$row_areas['id_del_area']."'>
                                  <h2 class='mb-3 font-14'>";
                                  // if ($row['id_del_area'] == 6){
                                  //   echo "Capacidad: ".$row['capacidad'];
                                  // }
                                  
                                  echo "</h2>
                                  <p class='mb-0'><span class='col-blue'>
                                     
                                  </span></p>                                                                      
                                   
                                    <button type='button' value='".$row_areas['id_del_area']."' class='btn btn-success btn-sm  btnrsv'>
                                      <i class='feather-16' data-feather='calendar'></i> $label
                                    </button> 

                                    <input type='hidden' id='area_".$row_areas['id_del_area']."' value='".$row_areas['nombre_area']."'>
                                    <input type='hidden' id='modalidad_reserva_".$row_areas['id_del_area']."' value='".$row_areas['modalidad_reserva']."'>
                                    <input type='hidden' id='consecucion_reserva_".$row_areas['id_del_area']."' value='".$row_areas['consecucion_reserva']."'>

                                    <span tabindex='0' role='button' data-toggle='popover' data-trigger='focus'title='Modo de reservación' data-content='".$row_areas['descripcion']."'><i class='feather-16'  data-feather='info'></i></span>
                                   
                                   
                                </div>
                              </div>
                              <div class='col-lg-6 col-md-6 col-sm-6 col-xs-6 pl-0'>
                                <div class='banner-img'>
                                 $image
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>";

                }

            ?>
          </div> 


              <?php
              break; 
              default:
                  
                   header("location:checkout.php");
                    
              ?>


              <script type="text/javascript">
                $(document).ready(function(){
                  $('[data-toggle="tooltip"]').tooltip();   
                });
              </script>


                <div class="row">

                  <?php

                  $result_area = mysqli_query($conexion, 'SELECT id as id_del_area, nombre, capacidad, (select count(*) from area inner join ocupante_reserva on area.id = ocupante_reserva.idarea where fecha_in = \''.$fecha_hoy.'\'  and area.id = id_del_area and ocupante_reserva.estado = 0) as cant FROM area order by nombre asc');
                  while($row_area = mysqli_fetch_array($result_area)){

                      $capacidad = $row_area['capacidad'];
                      $cant = $row_area['cant'];

                      $disponible = $capacidad - $cant;

                      if($disponible < 0){
                        $disponible_show = 0;
                      }else{
                        $disponible_show = $capacidad - $cant;
                      }


                    ?>


                  <div class="col-md-6 col-lg-12 col-xl-6">
                    <div class="card">
                      <div class="card-header">
                        <h4><?php echo "Ingreso a ".$row_area['nombre'] . " | Capacidad: ". $row_area['capacidad']. " | Disponible: <button type='button' class='btn btn-primary'>".$disponible_show ."</button>"; ?> </h4>
                      </div>
                      <div class="card-body">
                        <div class="table-responsive">
                          <table class="table table-hover mb-0">
                            <thead>
                              <tr>
                                <th>#</th>
                                <th>Apartamento</th>
                                <th>Nombres</th>
                                <th>Código</th>
                                <th>Ingreso</th> 
                              </tr>
                            </thead>
                            <tbody>

                              <?php
                              $contador = 1;
                              $result_ocupante = mysqli_query($conexion, 'SELECT * FROM ocupante_reserva inner join usuario_area on ocupante_reserva.id_ocupante = usuario_area.id_table_ocup where idarea = \''.$row_area['id_del_area'].'\' and fecha_in = \''.$fecha_hoy.'\' and ocupante_reserva.estado = 0 and verificado = 0 ');
                              while($row_ocupante = mysqli_fetch_array($result_ocupante)){
                             
                                echo"<tr>
                                  <td>".$contador++."</td>
                                  <td>".$row_ocupante['apto_from']."</td>
                                  <td>".$row_ocupante['nombres']." ".$row_ocupante['apellidos']."</td>
                                  <td>".$row_ocupante['code_reserva']."</td>
                                  <td>
                                    <form action='validation/confirmar.php' method='post'>
                                      <button value='".$row_ocupante['id_tabla']."' type='submit' name='confirmar' class='btn btn-success'>Confirmar</button>
                                    </form>
                                    </td>
                                </tr>";

                                }
                              ?>



                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>
                  </div>

                    <?php

                  }



                  ?>


                </div>

              <?php
              break;
            }

          ?>



        

        </section>
 

        <!-- moadal para ingreso -->
        <div class="modal fade" id='modal_reservation' tabindex="-1" role="dialog" aria-labelledby="formModal"
          aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="formModal">Zona a reservar: <span id="span_text_rsv"></span></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>

              <div class="modal-body">                

                <!-- <div class="col-12 col-md-12 col-lg-12">
                <div class="card card-success">
                  <div class="card-header">
                    <h4>Card Header</h4>
                  </div>
                  <div class="card-body">
                    <p>Card <code>.card-success</code></p>
                  </div>
                </div>
              </div> -->

               <form id="form_hpds">
                <input type="hidden" id='input_area' name="input_area">

                <?php

                /*Apto */
                $apto_reserva  = $_SESSION['k_code_reserva'];

                /*Folio*/
                $k_id_tabla    = $_SESSION['k_code'];

                 echo "<input type='hidden' name='id_factura' value='".$apto_reserva."'>";
                 echo "<input type='hidden' name='apto_from' value='".$apto_reserva."'>";
                ?>






                  <div class="form-group">
                    <label>Apartamento:</label>
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <div class="input-group-text">
                          <i class="fas fa-home"></i>
                        </div>
                      </div>
                      <div class="col-xs-12">
                        <!-- <div class="col-md-1 col-sm-1 col-xs-1"> -->
                        <input type="text" id="apto_from" name='apto_from' value="<?php echo $_SESSION['k_code_reserva'];?>" readonly="readonly" class="form-control" style="width: 180px">
                      </div>
                    </div>
                  </div> 



                  <div class="form-group div_nucleo" style="display: nonex; width: 85%;">
                     <div class="table-responsive">
                      <caption>Núcleo de Reserva</caption>
                    <table class="table table-striped">
                      <tr> 
                        <th style="text-align:left; width: 5%;">Elegir</th>
                        <th style="text-align:left">Nombres y Apellidos</th>
                        <!-- <th style="text-align:left">ID</th> -->
                      </tr> 

                       <?php 

                      $contador = 1;


                        $result = mysqli_query($conexion, 'SELECT id as idocupante, apellido_uno, nombre_uno, nombre_dos FROM checkin where consecutivo =\''.$cod_nucleo.'\' order by nombre_uno asc');
                        while($row_nucleo = mysqli_fetch_array($result)){        
 

                          echo "
                            <tr>
                              <td style='text-align:left' class='p-0 text-center'>".$contador++." 
                                <input type='checkbox' name='check_huesped' id='".$cod_nucleo.$contador."' class='check_huesped' value='".$row_nucleo['idocupante']."' checked>
                                <input type='hidden' name='name_huesped[]' id='".$cod_nucleo.$contador."name_huesped' class='name_huesped'  value='".$row_nucleo['nombre_uno']." ".$row_nucleo['nombre_dos']."'></td> 
                              <td style='text-align:left'> 
                                <input type='hidden' name='ide_nucleo[]' value='".$row_nucleo['idocupante']."' id='".$cod_nucleo.$contador."ide_nucleo'>
                                <input type='hidden' name='ide_consecutivo[]' value='".$cod_nucleo."' id='".$cod_nucleo.$contador."ide_consecutivo'>
                               
                              ".$row_nucleo['nombre_uno']." ".$row_nucleo['apellido_uno']."
                            </td>                         
                            <!--<td style='text-align:left' class='p-0 text-center'>".$row_nucleo['idocupante']."</td>-->
                            </tr>
                          "; 
                        } 

                      ?>

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

                  
                    <div class="form-group">
                    <label for="post_day">Fecha de Reservación: *</label>
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <div class="input-group-text">
                          <i class="fas fa-calendar"></i>
                        </div>
                      </div>
                      <div class="col-xs-12" > 
                      <?php
                        $bloqueo_id_sesion = "readonly";
                        
                        if($_SESSION['k_id'] == '1128062171'){
                            // $bloqueo_id_sesion = '';
                            // $fecha_hoy = '2024-07-05';
                            // $antelacion = '2024-07-05';
                        }
                      
                      ?>
                        <input type='date' name='date_reserva' id='date_reserva' min='<?php echo $fecha_hoy; ?>' max='<?php echo $antelacion; ?>' value='<?php echo $fecha_hoy; ?>' class="form-control " style="width: 180px" <?php echo $bloqueo_id_sesion;?> >
                      </div>
                    </div>
                  </div>
                  
                    <!-- <div class="form-group show_number_reserva" style="display:none;">
                    <label for="post_day">Número de personas:</label>
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <div class="input-group-text">
                          <i class="fas fa-user"></i>
                        </div>
                      </div>
                      <div class="col-xs-9">  -->
                        <input type='hidden' name='number_reserva' id='number_reserva' min="1" max="6" value='0' class="form-control  " style="width: 180px">
                  <!--     </div>
                    </div>
                  </div> -->
                  
                    <div class="form-group">
                    <label for="post_day">Zona Común: *</label>
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <div class="input-group-text">
                          <i class="fas fa-tag"></i>
                        </div>
                      </div>
                      <div class="col-xs-12"> 
                        <select name='select_area' id='select_area' class='form-control' style="width: 180px"></select>
                      </div>
                    </div>
                  </div>
                  
                    <div class="form-group">
                    <label for="post_day">Horario: *</label>
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <div class="input-group-text">
                          <i class="fas fa-clock"></i>
                        </div>
                      </div>
                      <div class="col-xs-12"> 
                        <select name='select_turno' id='select_turno' class='form-control' style="width: 180px"></select>
                      </div>
                    </div>
                  </div>
                  
                    


                    <div class="form-group" style="text-align: center;"> 
                    <div class="input-group" style="text-align: center;">
                      <div class="input-group-prepend" style="text-align: center;"> 
                        <input type='hidden' name='modalidad_reserva_send' id='modalidad_reserva_send' class="form-control" style="width: 180px">
                        <input type='hidden' name='consecucion_reserva_send' id='consecucion_reserva_send' class="form-control" style="width: 180px">
                        <button type="submit" id="btn_send_hpds" class="btn btn-success m-t-15 waves-effect" disabled='disabled'>Confirmar Reserva</button>
                      </div>  
                    </div>
                  </div>                   

                </form>

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

        
      </div>

      <?php include('footer.php'); ?>

    </div>
  </div>
 
  <!-- General JS Scripts -->
  <script src="assets/js/app.min.js"></script>
  <!-- JS Libraies -->
  <script src="assets/bundles/apexcharts/apexcharts.min.js"></script>
  <!-- Page Specific JS File -->
  <script src="assets/js/page/index.js"></script>
  <!-- Template JS File -->
  <script src="assets/js/scripts.js"></script>
  <!-- Custom JS File -->
  <script src="assets/js/custom.js"></script>

  <script type="text/javascript">

    $("#number_reserva").val(1)


    /*detección de cambio de fecha select turnos*/
  $('#date_reserva').on('change',function(){    

    $("#btn_send_hpds").removeClass("btn btn-success");
    $("#btn_send_hpds").addClass("btn btn-default");
    $('#btn_send_hpds').attr("disabled", true);
    $("#select_turno option").remove();
     var select_turno = $('#select_turno');select_turno.val($('option:first', select_turno).val());

      $("#select_turno option").remove();

      var data_area = $("#select_area").val();
      var data_fecha = $("#date_reserva").val();
      var modalidad_reserva_send = $("#modalidad_reserva_send").val();
      var consecucion_reserva_send = $("#consecucion_reserva_send").val();
      var apto_from = $("#apto_from").val();
      

      $.ajax({
        type: "POST",
        url: "select_turnos.php",
        data: {
          data_area:data_area,
          data_fecha:data_fecha,
          data_modalidad_reserva_send: modalidad_reserva_send,
          data_apto_from: apto_from,
          data_consecucion_reserva_send: consecucion_reserva_send
        }
      })
      .done(function(data, status){
                  
            var result_data      = JSON.parse(data);
            // console.log(result_data['array_turnos']);

             $('#select_turno').append('<option value=""> -Seleccione horario disponible- </option>');

              var index = 1;
              for (i = 0; i < result_data['array_turnos'].length; i++) {
              var loop = index++;

                
                console.log(result_data['array_turnos'][i][3]['out_time'])

                  if(result_data['array_turnos'][i][3]['out_time'] == "fh"){

                  }else{

                  if(result_data['array_turnos'][i][2]['action'] == "dis"){
                    }else{
                       if(result_data['array_turnos'][i][4]['reservado'] == "tr"){
                    }else{
                        $('#select_turno').append('<option '+result_data['array_turnos'][i][2]['action']+' value="'+result_data['array_turnos'][i][1]['id']+'" >'+result_data['array_turnos'][i][0]['descripcion']+''+result_data['array_turnos'][i][5]['disponible']+'</option>');  
                      }
                    }
                  }
              
              }
          })      
      .fail(function() {
       console.log("fail load zonas");
       });

  });


    $('.btnrsv').click(function(){  

      $("#select_area option").remove();


         // console.log($(this).val());

          var  id_rel_area = $(this).val();
          var name_del_area = $(this).val(); 

    
            $('#select_area').append("<option value='0'> -Seleccione área - <option>")

            $("#btn_send_hpds").removeClass("btn btn-default");
            $("#btn_send_hpds").removeClass("btn btn-success");
            $("#btn_send_hpds").addClass("btn btn-default");
            $('#btn_send_hpds').attr("disabled", true);


            $("#select_turno option").remove();

       

            // $('#select_area_div').fadeIn(1000);

                $.ajax({
                  type: "POST",
                  url: "select_area.php",
                  data: { 
                  id_rel_area: id_rel_area
                  }
                })
              .done(function(data){
                //$('#info').fadeOut().html(data);
                // $('#select_area').hide();
                $('#select_area').append(1000).html(data);
                // console.log(data);
                })
 
    var modalidad_reserva = $("#modalidad_reserva_"+id_rel_area).val()
    $("#modalidad_reserva_send").val(modalidad_reserva);
 

    var consecucion_reserva = $("#consecucion_reserva_"+id_rel_area).val()
    $("#consecucion_reserva_send").val(consecucion_reserva);


      // modalidad reserva por apartamento
    if (modalidad_reserva == 1) {




      var count_name_huesped = $(".name_huesped").length;

      // alert(count_name_huesped);

      for (i=2;i<count_name_huesped+2;i++) { 


        // <input type='hidden' name='name_huesped[]' id='".$cod_nucleo.$contador."name_huesped' class='name_huesped'  value='".$row_nucleo['nombre_uno']." ".$row_nucleo['nombre_dos']."'></td>                                
        // <input type='hidden' name='ide_nucleo[]' value='".$row_nucleo['idocupante']."' id='".$cod_nucleo.$contador."ide_nucleo'>
        // <input type='hidden' name='ide_consecutivo[]' value='".$cod_nucleo."' id='".$cod_nucleo.$contador."ide_consecutivo'>

        var compare_id = $("#<?php echo $_SESSION['k_code'];?>"+i+"ide_nucleo").val();
        var sesion_ide = "<?php echo $_SESSION['k_id'];?>";


        // alert("compare_id: "+compare_id)
        // alert("sesion_ide: "+sesion_ide)

        if (compare_id == sesion_ide) {

          $("#"+<?php echo $_SESSION['k_code'];?>+i+"name_huesped").attr("disabled", false)
          $("#"+<?php echo $_SESSION['k_code'];?>+i+"ide_nucleo").attr("disabled", false)
          $("#"+<?php echo $_SESSION['k_code'];?>+i+"ide_consecutivo").attr("disabled", false)
        }else{

          $("#"+<?php echo $_SESSION['k_code'];?>+i+"name_huesped").attr("disabled", true)
          $("#"+<?php echo $_SESSION['k_code'];?>+i+"ide_nucleo").attr("disabled", true)
          $("#"+<?php echo $_SESSION['k_code'];?>+i+"ide_consecutivo").attr("disabled", true)

        }
        
      }


      $(".div_nucleo").fadeOut();

      // modalidad de reserva por aforo
    }else{
      $(".div_nucleo").fadeIn();
    }



    $("#modal_reservation").modal('show'); 

  


      // if (name_del_area == 6){
      //     $(".show_number_reserva").fadeIn()
      //   }else{
      //     $("#number_reserva").val(1)
      //     $(".show_number_reserva").fadeOut()
      //   }

      // $("#span_text_rsv").text($("#date_reserva").val());
      $("#span_text_rsv").text($("#name_area_"+name_del_area).val())

      //    

      // var id_del_area_ajax = $(this).val();

      // var area_name = $("#area_"+$(this).val()).val();     

      // $('#select_area').append('<option value="'+id_del_area_ajax+'" >'+area_name+'</option>');       

  
  

    });




    $(".check_huesped").click(function(){ 

      var identificador_input = this.id;

        if ($(this).is(":checked")) {

            // alert(identificador_input)

          $("#"+identificador_input+"name_huesped").attr("disabled", false);
          $("#"+identificador_input+"ide_nucleo").attr("disabled", false);
          $("#"+identificador_input+"ide_consecutivo").attr("disabled", false);

           
 
            console.log('1');
              var num1 = parseInt(1);
              var num2 = parseInt($("#number_reserva").val());
              var resultado=num1+num2;

              // console.log('total hpds'+resultado);
              // console.log("valor de number_reserva: " + $("#number_reserva").val(resultado));



                $("#select_turno option").remove();

                var data_area = $("#select_area").val();
                var data_fecha = $("#date_reserva").val();
                var modalidad_reserva_send = $("#modalidad_reserva_send").val();
                var consecucion_reserva_send = $("#consecucion_reserva_send").val();
                var apto_from = $("#apto_from").val();


                $.ajax({
                  type: "POST",
                  url: "select_turnos.php",
                  data: {
                    data_area:data_area,
                    data_fecha:data_fecha,
                    data_modalidad_reserva_send: modalidad_reserva_send,
                    data_apto_from: apto_from,
                    data_consecucion_reserva_send: consecucion_reserva_send
                  }
                })
                .done(function(data, status){
                  
                  var result_data      = JSON.parse(data);
                  // console.log(result_data['array_turnos']);

                   $('#select_turno').append('<option value=""> -Seleccione horario disponible- </option>');

                    var index = 1;
                    for (i = 0; i < result_data['array_turnos'].length; i++) {
                    var loop = index++;

                      
                      console.log(result_data['array_turnos'][i][3]['out_time'])

                        if(result_data['array_turnos'][i][3]['out_time'] == "fh"){

                        }else{

                        if(result_data['array_turnos'][i][2]['action'] == "dis"){
                          }else{
                             if(result_data['array_turnos'][i][4]['reservado'] == "tr"){
                          }else{
                              $('#select_turno').append('<option '+result_data['array_turnos'][i][2]['action']+' value="'+result_data['array_turnos'][i][1]['id']+'" >'+result_data['array_turnos'][i][0]['descripcion']+''+result_data['array_turnos'][i][5]['disponible']+'</option>');  
                            }
                          }
                        }
                    
                    }
                })      
              .fail(function() {
               console.log("fail load zonas");
               });
     

            $("#btn_send_hpds").removeClass("btn btn-default");
            $("#btn_send_hpds").removeClass("btn btn-success");
            $("#btn_send_hpds").addClass("btn btn-default");
            $('#btn_send_hpds').attr("disabled", true);
          
        }
        else if ($(this).is(":not(:checked)")) {



          $("#"+identificador_input+"name_huesped").attr("disabled", true);
          $("#"+identificador_input+"ide_nucleo").attr("disabled", true);
          $("#"+identificador_input+"ide_consecutivo").attr("disabled", true);


            console.log('0');

              var num2 = parseInt($("#number_reserva").val());
              var num1 = parseInt(1);
              var resultado=num2-num1;


                $("#select_turno option").remove();

                var data_area = $("#select_area").val();
                var data_fecha = $("#date_reserva").val();
                var modalidad_reserva_send = $("#modalidad_reserva_send").val();
                var consecucion_reserva_send = $("#consecucion_reserva_send").val();
                var apto_from = $("#apto_from").val();

                $.ajax({
                  type: "POST",
                  url: "select_turnos.php",
                  data: {
                    data_area:data_area,
                    data_fecha:data_fecha,
                    data_modalidad_reserva_send: modalidad_reserva_send,
                    data_apto_from: apto_from,
                    data_consecucion_reserva_send: consecucion_reserva_send
                  }
                })
                .done(function(data, status){
                  
                  var result_data      = JSON.parse(data);
                  // console.log(result_data['array_turnos']);

                   $('#select_turno').append('<option value=""> -Seleccione horario disponible- </option>');

                    var index = 1;
                    for (i = 0; i < result_data['array_turnos'].length; i++) {
                    var loop = index++;

                      
                      console.log(result_data['array_turnos'][i][3]['out_time'])

                        if(result_data['array_turnos'][i][3]['out_time'] == "fh"){

                        }else{

                        if(result_data['array_turnos'][i][2]['action'] == "dis"){
                          }else{
                             if(result_data['array_turnos'][i][4]['reservado'] == "tr"){
                          }else{
                              $('#select_turno').append('<option '+result_data['array_turnos'][i][2]['action']+' value="'+result_data['array_turnos'][i][1]['id']+'" >'+result_data['array_turnos'][i][0]['descripcion']+''+result_data['array_turnos'][i][5]['disponible']+'</option>');  
                            }
                          }
                        }
                    
                    }
                })      
              .fail(function() {
               console.log("fail load zonas");
               });
     

            $("#btn_send_hpds").removeClass("btn btn-default");
            $("#btn_send_hpds").removeClass("btn btn-success");
            $("#btn_send_hpds").addClass("btn btn-default");
            $('#btn_send_hpds').attr("disabled", true);

              
              // console.log('total hpds'+resultado);
        }

            $("#number_reserva").val(resultado);

        });



    /*selección de turnos*/
    $('select#select_area').on('change',function(){

      console.log("cambio: "+ $(this).val())


        $("#select_turno option").remove();

        if ($(this).val() == "") { 
          $('#select_turno').append('<option value=""> -Sin horario disponible- </option>');
        }else{
            var data_area = $("#select_area").val();
            var data_fecha = $("#date_reserva").val();
            var modalidad_reserva_send = $("#modalidad_reserva_send").val();
            var consecucion_reserva_send = $("#consecucion_reserva_send").val();
            var apto_from = $("#apto_from").val();

            $.ajax({
              type: "POST",
              url: "select_turnos.php",
              data: {
                data_area:data_area,
                data_fecha:data_fecha,
                data_modalidad_reserva_send: modalidad_reserva_send,
                data_apto_from: apto_from,
                data_consecucion_reserva_send: consecucion_reserva_send
              }
            })
            .done(function(data, status){
              
              var result_data      = JSON.parse(data);
              // console.log(result_data['array_turnos']);

              if (result_data['array_turnos'].length == 0) {
                $('#select_turno').append('<option value=""> -Sin horario disponible- </option>');
              }else{
                $('#select_turno').append('<option value=""> -Seleccione horario disponible- </option>');
              }

               

                var index = 1;
                for (i = 0; i < result_data['array_turnos'].length; i++) {
                var loop = index++;

                  
                  console.log(result_data['array_turnos'][i][3]['out_time'])

                    if(result_data['array_turnos'][i][3]['out_time'] == "fh"){

                    }else{

                    if(result_data['array_turnos'][i][2]['action'] == "dis"){
                      }else{
                         if(result_data['array_turnos'][i][4]['reservado'] == "tr"){
                      }else{
                          $('#select_turno').append('<option '+result_data['array_turnos'][i][2]['action']+' value="'+result_data['array_turnos'][i][1]['id']+'" >'+result_data['array_turnos'][i][0]['descripcion']+''+result_data['array_turnos'][i][5]['disponible']+'</option>');  
                        }
                      }
                    }
                
                }
            })      
          .fail(function() {
           console.log("fail load zonas");
           });

        }

      $("#btn_send_hpds").removeClass("btn btn-default");
      $("#btn_send_hpds").removeClass("btn btn-success");
      $("#btn_send_hpds").addClass("btn btn-default");
      $('#btn_send_hpds').attr("disabled", true);
      });


  /*selección de turnos*/
    $('select#select_turno').on('change',function(){

      // alert($(this).val())

      if($(this).val() == 0){
        $('#btn_send_hpds').attr("disabled", true);
            $("#btn_send_hpds").removeClass("btn btn-success");
            $("#btn_send_hpds").addClass("btn btn-default");
          }else{

      var checks = $(".check_huesped:checked").length;

        console.log(checks); 

          if (checks == 0) {
            $('#btn_send_hpds').attr("disabled", true);
            $("#btn_send_hpds").removeClass("btn btn-success");
            $("#btn_send_hpds").addClass("btn btn-default");
          } else {        
            $('#btn_send_hpds').attr("disabled", false);
            $("#btn_send_hpds").removeClass("btn btn-default");
            $("#btn_send_hpds").addClass("btn btn-success");
          }

        }
      });


      /*envio de data formulario*/
      $("#form_hpds").submit(function(event) {
        $("#btn_send_hpds").attr("disabled", true);
        
        var frm     = $(this);
        var formulario  = $(this).serialize();
      
      
        $.post( "reservation_turno.php", formulario)
        .done(function alerta(data){
           var result_data      = JSON.parse(data);

           switch (result_data.result) {
          case "100":   
              alertify.notify(result_data.msg,'error',3, null);  
              break;
          case "101":    
              alertify.alert('Ya tiene una reserva!', result_data.msg+"<br> "+result_data.inside, function(){}); 
              break;
          case "102":        
              alertify.notify(result_data.msg,'error',3, null); 
              break;
          case "103":      
            alertify.notify(result_data.msg,'success',3, null); 
              /*success*/  
                $("#btn_send_hpds").removeClass("btn btn-success");
                $("#btn_send_hpds").addClass("btn btn-default");
                $('#btn_send_hpds').attr("disabled", true);
                 $("#select_turno option").remove();


                 /*reiniciando datos de ventana modal*/
                  $("#btn_send_hpds").removeClass("btn btn-success");
                  $("#btn_send_hpds").addClass("btn btn-default");
                  $('#btn_send_hpds').attr("disabled", true);
                  $("#select_turno option").remove();
                   var select_turno = $('#select_turno');select_turno.val($('option:first', select_turno).val());


                    $("#select_turno option").remove();

                    var data_area = $("#select_area").val();
                    var data_fecha = $("#date_reserva").val();
                    var modalidad_reserva_send = $("#modalidad_reserva_send").val();
                    var consecucion_reserva_send = $("#consecucion_reserva_send").val();
                    var apto_from = $("#apto_from").val();

                    $.ajax({
                      type: "POST",
                      url: "select_turnos.php",
                      data: {
                        data_area:data_area,
                        data_fecha:data_fecha,
                        data_modalidad_reserva_send: modalidad_reserva_send,
                        data_apto_from: apto_from,
                        data_consecucion_reserva_send: consecucion_reserva_send
                      }
                    })
                    .done(function(data, status){
                  
                  var result_data      = JSON.parse(data);
                  // console.log(result_data['array_turnos']);

                   $('#select_turno').append('<option value=""> -Seleccione horario disponible- </option>');

                    var index = 1;
                    for (i = 0; i < result_data['array_turnos'].length; i++) {
                    var loop = index++;

                      
                      console.log(result_data['array_turnos'][i][3]['out_time'])

                        if(result_data['array_turnos'][i][3]['out_time'] == "fh"){

                        }else{

                        if(result_data['array_turnos'][i][2]['action'] == "dis"){
                          }else{
                             if(result_data['array_turnos'][i][4]['reservado'] == "tr"){
                          }else{
                              $('#select_turno').append('<option '+result_data['array_turnos'][i][2]['action']+' value="'+result_data['array_turnos'][i][1]['id']+'" >'+result_data['array_turnos'][i][0]['descripcion']+''+result_data['array_turnos'][i][5]['disponible']+'</option>');  
                            }
                          }
                        }
                    
                    }
                })      
                    .fail(function() {
                     console.log("fail load zonas");
                     });

  
                 $("#modal_reservation").modal('hide');


              break;
          case "104":      
                alertify.alert('Información de Reserva!', result_data.msg, function(){}); 
              break;
          case "105": 
            alertify.alert('Información de Reserva!', result_data.msg, function(){});      
              break;
          default:  
              alertify.alert('Información de Reserva!', 'Error al realizar reserva por favor contactar a soporte técnico, Error de conexión', function(){}); 
          }
            
            console.log(data);

          })//done
      .fail(function() {
        $('#btn_send_hpds').attr("disabled", false);
        alert( "Error al cargar Información");
      }); 
      event.preventDefault();
      });
 


    
  </script>

</body>


</html>

<?php
ob_end_flush();
  }
?>