<?php

  $Seccion      = 'SiteConfig';
  $SubSeccion   = 'SiteConfig';
  $NameSec      = 'Configuración';
  $Position     = '../';
  $UrlImgs      = 'images';
  $Pagina       = '1';

  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
    $SiteName              = $_POST['SiteName'];
    $CodeGoogleAnalytics   = addslashes($_POST['CodeGoogleAnalytics']);
    $CodeFacebookChat      = addslashes($_POST['CodeFacebookChat']);
    $CodeFacebookPixel     = addslashes($_POST['CodeFacebookPixel']);

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

      $Id		= $_POST['Id'];

      //Update
      $Query = "UPDATE LandingConfig
      SET
      SiteName = '$SiteName',
      CodeGoogleAnalytics = '$CodeGoogleAnalytics',
      CodeFacebookChat = '$CodeFacebookChat',
      CodeFacebookPixel = '$CodeFacebookPixel'
      WHERE Id = '$Id'";
      $Result = mysqli_query($mysqli, $Query);

      $Saved = 'Ok';

    }
    //End Edita datos

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

        //RootSite del Sitio Seleccionado
        $ImageUp = $RootSite.'/'.$UrlImgs."/logo.png";

        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, 985, 'crop');
            $resizeObj -> saveImage($ImageUp, 100);
          }else{
            $scale = 1;
            $resizeObj = new resize($ImageUp);
            $resizeObj -> resizeImage(1800, 985, '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='.$Fk_Banner.'&Id='.$Id.'&New=Ok"</script>';
    }
    //End Redirecciona

  }

  $SecLine      = array('Configuración');

  //Config
  $Query = "
  SELECT
  con.Id,
  con.SiteName, con.CodeGoogleAnalytics,
  con.CodeFacebookChat, con.CodeFacebookPixel
  FROM LandingConfig con
  WHERE con.Id = '1'
  ";
  $Result = mysqli_query($mysqli, $Query);
  $Item = 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='../'">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($Item['Id']) ){ ?>
                      <input type="hidden" name="Id" value="<?php echo $Item['Id']; ?>">
                      <input type="hidden" name="Edit" value="Ok">
                    <?php }else{ ?>
                      <input type="hidden" name="New" value="Ok">
                    <?php } ?>
                  </div>
                </div>
                <!-- End Botones -->

            </div>

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

                      <div class="col-sm-12">
                        <h4 class="m-b-0"><?php echo $NameSec; ?></h4>
                        <hr />
                      </div>

                      <!-- SiteName -->
                      <div class="col-sm-12 form-group">
                        <label>Nombre del sitio:</label>
                        <input name="SiteName" class="form-control" value="<?php echo $Item[SiteName]; ?>" autocomplete="off">
                      </div>
                      <!-- End SiteName -->

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

                      <!-- Logo -->
                      <div class="col-sm-6 form-group">
                        <h4>Logotipo:</h4>
                        <?php
                        $Image = $RootSite.'/'.$UrlImgs.'/logo.png';
                        if (file_exists($Image)) {
                        ?>
                          <div class="m-b-10">
                            <img class="img-responsive" src="<?php echo $UrlSite.'/'.$UrlImgs.'/logo.png'; ?>">
                          </div>
                        <?php } ?>
                      </div>
                      <div class="col-sm-6 form-group">
                        <label for="input-file-now-custom-1">Tamaño de Logo: 400 pxw x 100 pxh y 72 dpi; <strong>solo se acepta formato png.</strong></label>
                        <input name="logo" type="file" id="input-file-now-custom-1" class="dropify"/>
                      </div>
                      <!-- End Logo -->

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

                      <!-- CodeGoogleAnalytics -->
                      <div class="col-sm-12 form-group">
                        <label>Insertar código de Google Analytics:</label>
                        <textarea name="CodeGoogleAnalytics" class="form-control"><?php echo $Item[CodeGoogleAnalytics]; ?></textarea>
                      </div>
                      <!-- End CodeGoogleAnalytics -->

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

                      <!-- CodeFacebookChat -->
                      <div class="col-sm-12 form-group">
                        <label>Insertar código de Facebook Chat:</label>
                        <textarea name="CodeFacebookChat" class="form-control"><?php echo $Item[CodeFacebookChat]; ?></textarea>
                      </div>
                      <!-- End CodeFacebookChat -->

                    </div>

                  </div>
                </div>
              </div>
            </div>
            <!-- Información del Banner -->

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

    <!-- Date Picker Plugin JavaScript -->
    <script src="<?php echo $Position; ?>assets/plugins/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>

    <!-- ============================================================== -->
    <!-- Plugins for this page -->
    <!-- ============================================================== -->
    <!-- jQuery file upload -->
    <script src="<?php echo $Position; ?>assets/plugins/dropify/dist/js/dropify.min.js"></script>
    <script>
    $(document).ready(function() {
        // Basic
        $('.dropify').dropify();

        // Translated
        $('.dropify-fr').dropify({
            messages: {
                default: 'Glissez-déposez un fichier ici ou cliquez',
                replace: 'Glissez-déposez un fichier ou cliquez pour remplacer',
                remove: 'Supprimer',
                error: 'Désolé, le fichier trop volumineux'
            }
        });

        // Used events
        var drEvent = $('#input-file-events').dropify();

        drEvent.on('dropify.beforeClear', function(event, element) {
            return confirm("Do you really want to delete \"" + element.file.name + "\" ?");
        });

        drEvent.on('dropify.afterClear', function(event, element) {
            alert('File deleted');
        });

        drEvent.on('dropify.errors', function(event, element) {
            console.log('Has Errors');
        });

        var drDestroy = $('#input-file-to-destroy').dropify();
        drDestroy = drDestroy.data('dropify')
        $('#toggleDropify').on('click', function(e) {
            e.preventDefault();
            if (drDestroy.isDropified()) {
                drDestroy.destroy();
            } else {
                drDestroy.init();
            }
        })
    });
    </script>
    <!-- ============================================================== -->
    <!-- Style switcher -->
    <!-- ============================================================== -->
    <script src="<?php echo $Position; ?>assets/plugins/styleswitcher/jQuery.style.switcher.js"></script>

    <!-- Extra js -->
    <script src="<?php echo $Position; ?>js/extra.js"></script>
    <script>
      $(document).ready(function(){

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