<?php

  $Seccion      = 'Acerca';
  $SubSeccion   = 'Acerca';
  $NameSec      = 'Acerca';
  $Position     = '../';
  $UrlImgs      = 'images/textos';
  $Pagina       = '2';
  $SecLine      = array('Nosotros');

  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
    $ImgNew             = $_POST['ImgNew'];

    $Sec        = addslashes($_POST['Sec']);
    $Titulo     = addslashes($_POST['Titulo']);
    $Contenido  = addslashes($_POST['Contenido']);


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

      //Inserta Banner
      $Query = "
        INSERT INTO Textos
        (
          Fk_Pagina, TextHorizontal, TextVetical,
          Title, TitleFk_Font, TitleSize,
          TitleLineHeight, TitleFk_SizeFormats,
          TitleColor, TitleAlign, TitleClass,
          SubTitle, SubTitleFk_Font, SubTitleSize,
          SubTitleLineHeight, SubTitleFk_SizeFormats,
          SubTitleColor, SubTitleAlign, SubTitleClass,
          Text, TextFk_Font, TextSize,
          TextLineHeight, TextFk_SizeFormats,
          TextColor, TextAlign, TextClass
        )
        VALUES (
          '$Pagina', '$TextHorizontal', '$TextVetical',
          '$Title', '$TitleFk_Font', '$TitleSize',
          '$TitleLineHeight', '$TitleFk_SizeFormats',
          '$TitleColor', '$TitleAlign', '$TitleClass',
          '$SubTitle', '$SubTitleFk_Font', '$SubTitleSize',
          '$SubTitleLineHeight', '$SubTitleFk_SizeFormats',
          '$SubTitleColor', '$SubTitleAlign', '$SubTitleClass',
          '$Text', '$TextFk_Font', '$TextSize',
          '$TextLineHeight', '$TextFk_SizeFormats',
          '$TextColor', '$TextAlign', '$TextClass'
        )
      ";
      // $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 Textos
        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(330, 450, 'crop');
            $resizeObj -> saveImage($ImageUp, 100);
          }else{
            $scale = 1;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(330, 450, '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

  }

  //Textos
  $Query = "
    SELECT
      txt.Id,
      txt.Titulo, txt.Contenido
    FROM Textos txt
    WHERE txt.Id = '1'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Text = 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($Text['Id']) ){ ?>
                      <input type="hidden" name="Id" value="<?php echo $Text['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">

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

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

                      <!-- Titulo -->
                      <div class="col-sm-12 form-group">
                        <label>Titulo:</label>
                        <input
                          name="Titulo"
                          type="text"
                          class="form-control"
                          value="<?php echo $Text[Titulo]; ?>"
                        />
                      </div>
                      <!-- End Titulo -->

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

                    </div>
                  </div>
                </div>
                <!-- Titulo -->

                <!-- 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-3">
                        <h4>Imagen:</h4>
                        <?php
                          $Image = $RootSite.'/images/textos/'.$Text['Id'].'.jpg';
                          if (file_exists($Image)) {
                        ?>
                          <div class="m-b-10">
                            <img class="img-responsive" src="<?php echo $UrlSite.'/'.$UrlImgs.'/'.$Text['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-9">
                        <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 -->

                    </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>
