<?php

  $Seccion          = 'Desarrollos';
  $SubSeccion       = 'Desarrollos';
  $NameSec          = 'Desarrollos';
  $Position         = '../../';
  $UrlImgs          = 'images/desarrollos';
  $Pagina           = '1';
  $ShowTextFormats  = '0';

  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'];
    $Nombre             = addslashes($_POST['Nombre']);
    $Ubicacion          = addslashes($_POST['Ubicacion']);
    $TextoBoton         = addslashes($_POST['TextoBoton']);
    $Activo             = addslashes($_POST['Activo']);

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

      //Inserta
      $Query = "
        INSERT INTO Desarrollos
        (
          Nombre, Ubicacion, TextoBoton, Activo
        )
        VALUES (
          '$Nombre', '$Ubicacion', '$TextoBoton', '$Activo'
        )
      ";
      $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 Desarrollos
        SET
          Nombre = '$Nombre', Ubicacion = '$Ubicacion',
          TextoBoton = '$TextoBoton', Activo = '$Activo'
        WHERE Id = '$Id'
      ";
      $Result = mysqli_query($mysqli, $Query);

      $Saved = 'Ok';

    }
    //End Edita datos

    //Sube Imagen
    $Imagen = "imagen";
    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 = "800";
          if ($width > $max_width){
            $scale = $max_width/$width;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(600, 460, 'crop');
            $resizeObj -> saveImage($ImageUp, 100);
          }else{
            $scale = 1;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(600, 460, '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="?&Id='.$Id.'&New=Ok"</script>';
    }
    //End Redirecciona

  }

  $SecLine = array('Desarrollos');

  //Depa
  $Query = "
    SELECT
      des.Id,
      des.Nombre, des.Ubicacion, des.TextoBoton, des.Activo
    FROM Desarrollos des
    WHERE des.Id = '$_GET[Id]'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Desa = 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['cat']; ?>'">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='?cat=<?php echo $_GET['cat']; ?>'">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($Desa['Id']) ){ ?>
                      <input type="hidden" name="Id" value="<?php echo $Desa['Id']; ?>">
                      <input type="hidden" name="Edit" value="Ok">
                    <?php }else{ ?>
                      <input type="hidden" name="New" value="Ok">
                    <?php } ?>
                    <input type="hidden" name="Fk_Banner" 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">

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

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

                      <div class="col-sm-12 row">

                        <div class="col-sm-4 m-b-20">
                          <img class="img-responsive" src="<?php echo $UrlSite; ?>/<?php echo $UrlImgs; ?>/<?php echo $Desa[Id]; ?>.jpg" />
                        </div>

                        <div class="col-sm-4 m-b-20">
                          <div style="width:100%;">
                            <label>Agregar Imagen</label>
                            <input name="imagen" type="file" id="input-file-now-custom-1" class="dropify"/>
                          </div>
                        </div>

                      </div>

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

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

                      <div class="col-sm-12"><br>
                        <h3>Información</h3>
                        <hr />
                      </div>

                      <!-- Nombre -->
                      <div class="col-sm-12 form-group">
                        <label>Nombre</label>
                        <input data-required="true" autocomplete="off" name="Nombre" class="form-control" value="<?php echo $Desa['Nombre']; ?>" />
                      </div>
                      <!-- End Nombre -->

                      <!-- Ubicación --
                      <div class="col-sm-12 form-group">
                        <label>Ubicación</label>
                        <input data-required="true" autocomplete="off" name="Ubicacion" class="form-control" value="<?php echo $Desa['Ubicacion']; ?>" />
                      </div>
                      <!-- End Ubicación -->

                      <!-- TextoBoton --
                      <div class="col-sm-12 form-group">
                        <label>TextoBoton</label>
                        <input data-required="true" autocomplete="off" name="TextoBoton" class="form-control" value="<?php echo $Desa['TextoBoton']; ?>" />
                      </div>
                      <!-- End TextoBoton -->

                      <!-- Activo -->
                      <div class="col-sm-12 form-group">
                        <label>Visible</label>
                        <select name="Activo" class="form-control chosen-select">
                          <option value="1" <?php if( $Depa['Activo'] == 1 || !$Depa['Id'] ){ echo "selected"; } ?>>Si</option>
                          <option value="0" <?php if( $Depa['Activo'] == 0 && $Depa['Id'] ){ echo "selected"; } ?>>No</option>
                        </select>
                      </div>
                      <!-- End Activo -->

                    </div>
                  </div>
                </div>
                <!-- Info -->

                <?php
                  //Areas
                  $Query = "
                    SELECT
                      are.Id, are.Title
                    FROM DesarrollosAreas are
                    ORDER BY are.Sort ASC
                  ";
                  $Areas = $mysqli->query($Query);
                  mysqli_data_seek($Areas, 0);
                  while($Area = mysqli_fetch_array($Areas)) {
                ?>
                  <!-- End Area -->
                  <div class="card card-outline-info Areas">
                    <div class="card-body">
                      <div class="row">

                        <div class="col-sm-12">
                          <h3><?php echo $Area[Title]; ?></h3>
                          <hr />
                        </div>

                        <div class="AreaItems m-b-20 col-sm-12">
                          <?php
                            //AreaItems
                            $Query = "
                              SELECT
                                ite.Id, ite.Text
                              FROM LandingDepartamentoAreasItems ite
                              WHERE ite.Fk_Departamento = '$Desa[Id]' AND ite.Fk_Area = '$Area[Id]'
                              ORDER BY ite.Sort ASC
                            ";
                            $Items = $mysqli->query($Query);
                            mysqli_data_seek($Items, 0);
                            while($Item = mysqli_fetch_array($Items)) {
                          ?>
                            <div class="card Item">
                              <div class="card-body">
                                <button class="btn btn-danger BtnDelItem" type="button" style="position:absolute;top:0px;right:0px;">
                                  <i class="fa fa-times"></i>
                                </button>
                                <input class="form-control" name="Item[<?php echo $Area[Id]; ?>][Text][]" value="<?php echo $Item[Text]; ?>" autocomplete="off" />
                              </div>
                            </div>
                          <?php } ?>
                        </div>

                        <div class="col-sm-12">
                          <button type="button" class="btn btn-secondary BtnAddArea" data-area="<?php echo $Area[Id]; ?>">
                            Agregar <i class="fa fa-plus m-l-10"></i>
                          </button>
                        </div>

                      </div>
                    </div>
                  </div>
                  <!-- End Area -->
                <?php } ?>

              </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);
          });
        });

        //Del Img
        $(document.body).on('click', '.BtnDelImg' ,function(){
          $(this).parents('.ImgBox').remove();
        });
        //End Del Img

        //Agregar Item
        $(document.body).on('click', '.BtnAddArea' ,function(){
          var Area = $(this).data('area');
          console.log(Area);
          $(this).parents('.Areas').find('.AreaItems').append('<div class="card Item"><div class="card-body"><button class="btn btn-danger BtnDelItem" type="button" style="position:absolute;top:0px;right:0px;"><i class="fa fa-times"></i></button><input class="form-control" name="Item['+Area+'][Text][]" value="" autocomplete="off" /></div></div>');
        });
        //End Agregar Item

        //Del Img
        $(document.body).on('click', '.BtnDelItem' ,function(){
          $(this).parents('.Item').remove();
        });
        //End Del Img

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

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

</body>

</html>
