<?php

  $Seccion      = 'Servicios';
  $SubSeccion   = 'Servicios';
  $NameSec      = 'Servicio';
  $Position     = '../../';
  $UrlImgs      = 'images/servicios';
  $Pagina       = '1';
  $SecLine      = array('Servicios', 'Servicio');

  require_once($Position.'config/config.php');
  require_once($Position.'config/conexion.php');
  require_once($Position.'config/user.php');
  require_once($Position.'funciones/acces.php');
  require_once($Position.'funciones/logout.php');
  require_once($Position.'funciones/funciones.php');
  require_once($Position.'funciones/resize-class.php');

  $Hoy      = date('Y-m-d');
  $HoyFecha = CambioFechaInversa($Hoy);

  if( $_POST['Save'] == 'Ok' ){

    //Datos de formulario
    $Titulo               = addslashes($_POST['Titulo']);
    $Contenido            = addslashes($_POST['Contenido']);

    //Inserta Nuevo Registro
    if( $_POST['New'] == 'Ok' ){

      //Inserta Banner
      $Query = "
        INSERT INTO Servicios
        (
          Titulo, Contenido
        )
        VALUES (
          '$Titulo', '$Contenido'
        )
      ";
      $Result = mysqli_query($mysqli, $Query);
      $Id = mysqli_insert_id($mysqli);

    }
    //End Inserta Nuevo Registro

    //Edita datos
    if( $_POST['Edit'] == 'Ok' ){

      $Id		= $_POST['Id'];

      //Update
      $Query = "
        UPDATE Servicios
        SET
          Titulo = '$Titulo', Contenido = '$Contenido'
        WHERE Id = '$Id'
      ";
      $Result = mysqli_query($mysqli, $Query);

      $Saved = 'Ok';

    }
    //End Edita datos

    //Sube Imagen
    $Imagen = "image";
    if(empty($_FILES[$Imagen]['name'])){}else{
      $_FILES[$Imagen]["name"];
      $allowedExts = array("JPEG", "jpeg", "jpg", "JPG");
      $temp = explode(".", $_FILES[$Imagen]["name"]);
      $extension = end($temp);
      if((
      ($_FILES[$Imagen]["type"] == "image/jpeg")
      || ($_FILES[$Imagen]["type"] == "image/jpg")
      || ($_FILES[$Imagen]["type"] == "image/JPEG")
      || ($_FILES[$Imagen]["type"] == "image/JPG")
      )
      && ($_FILES[$Imagen]["size"] < 10000000)
      && in_array($extension, $allowedExts)) {
      if ($_FILES[$Imagen]["error"] > 0) {
      }else{

        //RootSite del Sitio Seleccionado
        $ImageUp = $RootSite.'/'.$UrlImgs."/".$Id.".jpg";

        if ( move_uploaded_file($_FILES[$Imagen]["tmp_name"], $ImageUp) ){
        //if ( copy($_FILES["image"]["tmp_name"], $ImageUp) ){
          //echo "Img Up";
          chmod($ImageUp, 0777);
          //Ajuste de tamaño
          $width = getWidth($ImageUp);
          $height = getHeight($ImageUp);
          $max_width = "1800";
          if ($width > $max_width){
            $scale = $max_width/$width;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(1800, 920, 'crop');
            $resizeObj -> saveImage($ImageUp, 100);
          }else{
            $scale = 1;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(1800, 920, 'crop');
            $resizeObj -> saveImage($ImageUp, 100);
          }
        }else{
          //echo "Img Not<br>";
          print_r(error_get_last());
        }

      }}else{
      }
    }
    //End Sube Imagen

    //Redirecciona
    if( $_POST['New'] == 'Ok' ){
      echo '<script type="text/javascript">document.location.href="?ban='.$Pagina.'&Id='.$Id.'&New=Ok"</script>';
    }
    //End Redirecciona

  }

  //Servicio
  $Query = "
    SELECT
      ser.Id,
      ser.Titulo, ser.Contenido
    FROM Servicios ser
    WHERE ser.Id = '$_GET[Id]'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Serv = mysqli_fetch_assoc($Result);

?>

<!DOCTYPE html>
<html lang="en">

<?php require_once($Position.'head.php'); ?>

<body class="fix-sidebar fix-header card-no-border">
  <?php
    mysqli_data_seek($Fonts, 0);
    while($Font = mysqli_fetch_array($Fonts)) {
      if( $Font['Link'] ){
        echo '<link href="'.$Font['Link'].'" rel="stylesheet">';
      }
    }
  ?>

    <div class="preloader">
      <svg class="circular" viewBox="25 25 50 50">
      <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" /> </svg>
    </div>

    <div id="main-wrapper">
      <?php require_once($Position.'header.php'); ?>
      <?php require_once($Position.'menu.php'); ?>

      <div class="page-wrapper">

        <form method="post" enctype="multipart/form-data" data-validate="parsley" role="form" id="FormPer">
          <div class="container-fluid">

            <div class="row page-titles page-titles-fixed">

                <?php require_once($Position.'title.php'); ?>

                <!-- Botones -->
                <div class="col-md-7 align-self-center text-right">
                  <div class="btn-group" role="group" aria-label="Basic example">
                    <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='../?Id=<?php echo $_GET['ban']; ?>'">Regresar <i class="fa fa-arrow-left m-l-5"></i></button>
                    <!-- <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='?ban=<?php echo $_GET['ban']; ?>'">Nuevo<i class="fa fa-plus m-l-5"></i></button> -->
                    <button type="submit" class="btn btn-sm btn-secondary">Guardar<i class="fa fa-check m-l-5"></i></button>
                    <input type="hidden" name="Save" value="Ok">
                    <?php if( !empty($Serv['Id']) ){ ?>
                      <input type="hidden" name="Id" value="<?php echo $Serv['Id']; ?>">
                      <input type="hidden" name="Edit" value="Ok">
                    <?php }else{ ?>
                      <input type="hidden" name="New" value="Ok">
                    <?php } ?>
                    <input type="hidden" name="Fk_Pagina" value="<?php echo $Ban[Id]; ?>" />
                  </div>
                </div>
                <!-- End Botones -->

            </div>

            <!-- Información del Banner -->
            <div class="row inner-fixed-content">
              <div class="col-lg-12">

                <!-- Text -->
                <div class="card card-outline-info">
                  <div class="card-body">
                    <div class="row">

                      <div class="col-sm-12">
                        <h3>Texto</h3>
                        <hr />
                      </div>

                      <!-- Tamaño Texto -->
                      <div class="col-sm-12 form-group">
                        <label>Titulo:</label>
                        <input
                          name="Titulo"
                          class="form-control"
                          value="<?php echo $Serv['Titulo']; ?>"
                          autocomplete="off"
                        >
                      </div>
                      <!-- End Tamaño Texto -->

                      <!-- Text -->
                      <div class="col-sm-12 form-group">
                        <label>Texto:</label>
                        <textarea name="Contenido" class="form-control IncEditor"><?php echo $Serv['Contenido']; ?></textarea>
                      </div>

                      <!-- Tipo de letr --
                      <div class="col-sm-3 form-group">
                        <label>Tipo de letra:</label>
                        <select name="TextFk_Font" class="form-control chosen-select FontSel">
                          <option value="0"></option>
                          <?php
                            mysqli_data_seek($Fonts, 0);
                            while($Font = mysqli_fetch_array($Fonts)) {
                          ?>
                            <option value="<?php echo $Font['Id']; ?>" data-font="<?php echo $Font['Font']; ?>" <?php if( $Serv[TextFk_Font] == $Font['Id'] ){ echo "selected"; }elseif( !$Serv[Id] && ( $Font[Id] == '1' ) ){ echo "selected"; } ?>><?php echo $Font['Name']; ?></option>
                          <?php } ?>
                        </select>
                      </div>
                      <!-- End Tipo de letr -->

                      <!-- Tamaño Texto --
                      <div class="col-sm-3 form-group">
                        <label>Tamaño de la letra:</label>
                        <input name="TextSize" class="form-control" value="<?php if( $Serv['TextSize'] ){ echo $Serv['TextSize']; }else{ echo "14"; } ?>" autocomplete="off">
                      </div>
                      <!-- End Tamaño Texto -->

                      <!-- Separación de Linea --
                      <div class="col-sm-3 form-group">
                        <label>Separación de Linea:</label>
                        <input name="TextLineHeight" class="form-control" value="<?php if( $Serv[TextLineHeight] ){ echo $Serv[TextLineHeight]; }else{  } ?>" autocomplete="off">
                      </div>
                      <!-- End Separación de Linea -->

                      <!-- Formato de Texto --
                      <div class="col-sm-3 form-group">
                        <label>Formato de Texto</label>
                        <select data-required="true" name="TextFk_SizeFormats" class="form-control chosen-select">
                          <option></option>
                          <?php
                            mysqli_data_seek($FontsFormats, 0);
                            while($FontFormat = mysqli_fetch_array($FontsFormats)) {
                          ?>
                            <option value="<?php echo $FontFormat['Id']; ?>" <?php if( $Serv[TextFk_SizeFormats] == $FontFormat[Id] || (!$Serv[TextFk_SizeFormats] && $FontFormat[Id] == 1 ) ){ echo "selected"; } ?>><?php echo $FontFormat['Name'].' ('.$FontFormat['Format'].')'; ?></option>
                          <?php } ?>
                        </select>
                      </div>
                      <!-- End Formato de Texto -->

                      <!-- Text Alinear --
                      <div class="col-sm-3 form-group">
                        <label>Alineación</label>
                        <select name="TextAlign" class="form-control chosen-select">
                          <option value="0"></option>
                          <?php
                            mysqli_data_seek($Centers, 0);
                            while($Center = mysqli_fetch_array($Centers)) {
                          ?>
                            <option value="<?php echo $Center['Id']; ?>" <?php if( $Serv[TextAlign] == $Center[Id] ){ echo "selected"; }elseif( !$Serv[Id] && $Center[Id] == 1 ){ echo "selected"; } ?>><?php echo $Center['Name']; ?></option>
                          <?php } ?>
                        </select>
                      </div>
                      <!-- End Text Alinear -->

                      <!-- Color Texto --
                      <div class="col-sm-3 form-group">
                        <label>Color del texto:</label>
                        <input name="TextColor" type="text" class="colorpicker form-control" value="<?php if( $Serv['TextColor'] ){ echo $Serv['TextColor']; }else{ echo "#ffffff"; } ?>" />
                      </div>
                      <!-- End Color Texto -->

                      <!-- Texto Clase --
                      <div class="col-sm-3 form-group">
                        <label>Clase:</label>
                        <input
                          name="TextClass"
                          type="text"
                          class="form-control"
                          value="<?php echo $Serv[TextClass]; ?>"
                        />
                      </div>
                      <!-- End Texto Clase -->

                      <!-- End Text -->

                      <div class="col-sm-12">
                        <hr class="m-t-0">
                      </div>

                    </div>
                  </div>
                </div>
                <!-- End Texto-->

                <!-- Imagen -->
                <div class="card card-outline-info">
                  <div class="card-body">
                    <div class="row">

                      <div class="col-sm-12">
                        <h4 class="m-b-0">Imagen</h4>
                        <hr />
                      </div>

                      <!-- Imagen Principal -->
                      <div class="col-sm-6">
                        <h4>Imagen para escritorio:</h4>
                        <?php
                          $Image = $RootSite.'/images/banners/'.$Serv['Id'].'.jpg';
                          if (file_exists($Image)) {
                        ?>
                          <div class="m-b-10">
                            <img class="img-responsive" src="<?php echo $UrlSite.'/'.$UrlImgs.'/'.$Serv['Id'].'.jpg'; ?>">
                          </div>
                        <?php }else{ ?>
                          <div class="m-b-10">
                            <!--<img class="img-responsive" src="<?php echo $UrlSite.'/'.$UrlImgs.'/0.jpg'; ?>">-->
                          </div>
                        <?php } ?>

                      </div>
                      <div class="col-sm-6">
                        <label for="input-file-now-custom-1">La fotografía deberá estar en la siguiente resolución: 1800 pxw x 920 pxh y 72 dpi; <strong>solo se acepta formato jpg.</strong></label>
                        <input name="image" type="file" id="input-file-now-custom-1" class="dropify"/>
                      </div>
                      <!-- End Imagen Principal -->

                      <div class="col-sm-12">
                        <hr>
                      </div>

                      <?php if( $ShowImgMovil == 'Ok' ){ ?>
                        <!-- Imagen Movil -->
                        <div class="col-sm-6">
                          <h4>Imagen para móvil:</h4>
                          <?php
                          $Image = $RootSite.'/images/banners/'.$Serv['Id'].'-m.jpg';
                          if (file_exists($Image)) {
                          ?>
                            <div class="m-b-10">
                              <img class="img-responsive" src="<?php echo $UrlSite.'/'.$UrlImgs.'/'.$Serv['Id'].'-m.jpg'; ?>">
                            </div>
                          <?php }else{ ?>
                            <div class="m-b-10">
                              <!--<img class="img-responsive" src="<?php echo $UrlSite.'/'.$UrlImgs.'/0.jpg'; ?>">-->
                            </div>
                          <?php } ?>
                        </div>
                        <div class="col-sm-6">
                          <label for="input-file-now-custom-1">La fotografía deberá estar en la siguiente resolución: 478 pxw x 850 pxh y 72 dpi; <strong>solo se acepta formato jpg.</strong></label>
                          <input name="image<?php echo $ImgTraId; ?>-m" type="file" id="input-file-now-custom-1" class="dropify"/>
                        </div>
                        <!-- End Imagen Movil -->
                      <?php } ?>

                    </div>
                  </div>
                </div>
                <!-- End Imagen -->

              </div>
            </div>

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

      <?php require_once($Position.'footer.php'); ?>

    </div>

    <?php require_once($Position.'scripts.php'); ?>
    <script src="<?php echo $Position; ?>js/extra.js"></script>
    <script>
      $(document).ready(function(){

        //Areas de Texto
        tinymce.init({
            selector: ".IncEditor",
            theme: "modern",
            height: 300,
            force_br_newlines : true,
            force_p_newlines : false,
            forced_root_block : '',
            plugins: "paste",
            paste_as_text: true,
            plugins: [
                "advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
                "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                "save table contextmenu directionality emoticons template paste textcolor"
            ],
            toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | l      ink image | print preview media fullpage | forecolor backcolor emoticons",
        });
        //End Areas de Texto

        // Actualiza Imagenes
        $("img").each(function(){
          $(this).attr('src', $(this).attr('src')+'?'+Math.random());
        });

        //Date datepicker
        $('.datepicker').datepicker({
          autoclose: true,
          todayHighlight: true,
          format: "dd / MM / yyyy",
          startView: 2
        });
        //End Date datepicker

        //Seleccion de Fuente
        $(document.body).on('change', '.FontSel' ,function(){
          $("option:selected", this).each(function () {
            font = $( this ).data( "font" );
            console.log(font);
            $( this ).parents('.FontSel').css("font-family", font);
            $( this ).parents('.FontSel').parents('.form-group').find('.chosen-single').css("font-family", font);
          });
        });

      });
    </script>
    <!-- End Extra js -->

    <!-- Cerrar Conexion -->
    <?php require_once($Position.'cerrarconexion.php'); ?>
    <!-- End Cerrar Conexion -->

</body>

</html>
