<?php
  $Seccion      = 'Clientes';
  $SubSeccion   = 'Clientes';
  $NameSec      = 'Catálogo de Clientes';
  $NameSin      = 'Cliente';
  $SecLine      = array('Facturación', 'Catálogo de Clientes');
  $Position   = '../../';
  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');

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

    //Datos a Guardar
    $Nombre 		   = addslashes(strip_tags($_POST['Nombre']));
    $Rfc 		       = addslashes(strip_tags($_POST['Rfc']));
    $Uso 		       = addslashes(strip_tags($_POST['Uso']));
    $Calle	       = addslashes(strip_tags($_POST['Calle']));
    $NoExt 		     = addslashes(strip_tags($_POST['NoExt']));
    $NoInt 		     = addslashes(strip_tags($_POST['NoInt']));
    $CodigoPostal  = addslashes(strip_tags($_POST['CodigoPostal']));
    $Colonia 		   = addslashes(strip_tags($_POST['Colonia']));
    $Pais 		     = addslashes(strip_tags($_POST['Pais']));
    $Estado 		   = addslashes(strip_tags($_POST['Estado']));
    $Municipio 	   = addslashes(strip_tags($_POST['Municipio']));
    $Email 	       = addslashes(strip_tags($_POST['Email']));

    //Guarda Registro Nuevo
    if( $_POST['New'] == 'Ok' ){
      $Query = "
        INSERT INTO CatalogoClientes
        (
          Fk_Cuenta,
          Email,
          Nombre, Rfc, Fk_FacturaUso,
          Calle, NoExterior, NoInterior, CodigoPostal, Colonia,
          Fk_Pais, Fk_Estado, Fk_Municipio
         )
      	VALUES
        (
          '$Cuenta[Id]',
          '$Email',
          '$Nombre', '$Rfc', '$Uso',
          '$Calle', '$NoExt', '$NoInt', '$CodigoPostal', '$Colonia',
          '$Pais', '$Estado', '$Municipio'
        )
      ";
      $Result = mysqli_query($mysqli, $Query);
      $Id = mysqli_insert_id($mysqli);
    }

    //Edita Registro
    if( $_POST['Id'] ){
      $Id = $_POST['Id'];
      $Query = "
        UPDATE CatalogoClientes
        SET
          Nombre = '$Nombre', Rfc = '$Rfc', Fk_FacturaUso = '$Uso',
          Email = '$Email',
          Calle = '$Calle', NoExterior  = '$NoExt', NoInterior = '$NoInt',
          CodigoPostal = '$CodigoPostal', Colonia = '$Colonia',
          Fk_Pais = '$Pais', Fk_Estado = '$Estado', Fk_Municipio = '$Municipio'
        WHERE Id = '$Id'
      ";
      $Result = mysqli_query($mysqli, $Query);
      $Save = 'Ok';
    }
    //End Edita Registro

    //Direcciona en caso de guardar nuevo Registro
    if ( $_POST['New'] == "Ok" && $Id ) {
    	echo '<script type="text/javascript">document.location.href="edit.php?Id='.$Id.'&New=Ok"</script>';
    }

  }
  //End Guardar Registro

  if( $_GET[Id] ){
    //CatalogoCliente
    $Query = "
      SELECT
        cli.Id, cli.Nombre, cli.Rfc, cli.Fk_FacturaUso, cli.Email,
        cli.Calle, cli.NoExterior, cli.NoInterior, cli.CodigoPostal,
        cli.Colonia, cli.Fk_Pais, cli.Fk_Estado, cli.Fk_Municipio
      FROM CatalogoClientes cli
      WHERE cli.Id = '$_GET[Id]' AND cli.Fk_Cuenta = '$Cuenta[Id]'
    ";
    $Result = mysqli_query($mysqli, $Query);
    $Cli    = mysqli_fetch_assoc($Result);
    if( $Cli[Id] ){}else{
      echo '<script type="text/javascript">document.location.href="index.php"</script>';
    }

  }

  //Usos
  $Query = "
    SELECT
      uso.Id, uso.Clave, uso.Uso
    FROM FacturasUsos uso
    WHERE ( uso.Pre = 'P' OR uso.Pre = 'G' OR uso.Pre = 'I' )
    ORDER BY uso.Clave ASC
  ";
  $Usos = $mysqli->query($Query);

  //Paises
  $Query = "
    SELECT
      pai.Id, pai.Nombre
    FROM Paises pai
    WHERE pai.Activo = '1'
    ORDER BY pai.Nombre ASC
  ";
  $Paises = $mysqli->query($Query);

  //Estados
  $Query = "
    SELECT
      est.Id, est.Nombre
    FROM Estados est
    WHERE est.Fk_Pais = '$Cli[Fk_Pais]'
    ORDER BY est.Nombre ASC
  ";
  $Estados = $mysqli->query($Query);

  //Municipios
  $Query = "
    SELECT
      mun.Id, mun.Nombre
    FROM Municipios mun
    WHERE mun.Fk_Estado = '$Cli[Fk_Estado]'
    ORDER BY mun.Nombre ASC
  ";
  $Municipios = $mysqli->query($Query);

?>

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

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

<body class="fix-sidebar fix-header card-no-border">
    <!-- ============================================================== -->
    <!-- Preloader - style you can find in spinners.css -->
    <!-- ============================================================== -->
    <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>
    <!-- ============================================================== -->
    <!-- Main wrapper - style you can find in pages.scss -->
    <!-- ============================================================== -->
    <div id="main-wrapper">
        <?php require_once($Position.'header.php'); ?>
        <?php require_once($Position.'menu.php'); ?>

        <!-- ============================================================== -->
        <!-- Page wrapper  -->
        <!-- ============================================================== -->
        <div class="page-wrapper">
            <!-- ============================================================== -->
            <!-- Container fluid  -->
            <!-- ============================================================== -->
            <div class="container-fluid">
              <form method="post" enctype="multipart/form-data" data-validate="parsley" role="form" id="FormPer">
                <!-- ============================================================== -->
                <!-- Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <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">
                        <!-- Btn Regresar -->
                        <button
                          type="button"
                          class="btn btn-sm btn-secondary"
                          onclick="window.location.href='index.php'"
                        >
                          <i class="fa fa-arrow-left m-r-5"></i>
                          Regresar
                        </button>
                        <!-- End Btn Regresar -->

                        <!--<button type="button" class="btn btn-secondary" onclick="window.location.href='edit.php'">Nuevo</button>-->

                        <!-- Btn Guardar -->
                        <button type="submit" class="btn btn-sm btn-success">
                          Guardar
                          <i class="fa fa-check m-l-5"></i>
                        </button>
                        <!-- End Btn Guardar -->

                        <input type="hidden" name="Save" value="Ok">
                        <?php if( !empty($Cli['Id']) ){ ?>
                          <input type="hidden" name="Id" value="<?php echo $Cli['Id']; ?>">
                        <?php }else{ ?>
                          <input type="hidden" name="New" value="Ok">
                        <?php } ?>
                      </div>
                    </div>
                    <!-- End Botones -->

                </div>
                <!-- ============================================================== -->
                <!-- End Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <!-- ============================================================== -->
                <!-- Page Content -->
                <!-- ============================================================== -->
                <div class="row inner-fixed-content">
                  <div class="col-12">

                    <?php /*if( $Save == 'Ok' || $_GET['New'] == Ok ){ ?>
                      <!-- Alerta Save -->
                      <div class="alert alert-success"> <i class="fa fa-check m-r-10"></i> Guardado !
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button>
                      </div>
                      <!-- End Alerta Save -->
                    <?php }*/ ?>

                    <!-- Card -->
                    <div class="card">
                      <div class="card-body">
                        <h4 class="card-title"><?php if( $Cli['Id'] ){ echo "Editar "; }else{ echo "Nuevo "; } echo $NameSin; ?></h4>
                        <h6 class="card-subtitle"><?php echo $NameSec; ?></h6>

                        <div class="row">

                          <!-- Nombre -->
                          <div class="form-group col-sm-12">
                            <label>Nombre / Razón Social <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Nombre" value="<?php echo $Cli['Nombre']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Nombre -->

                          <!-- Rfc -->
                          <div class="form-group col-sm-6">
                            <label>Rfc <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Rfc" value="<?php echo $Cli['Rfc']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Rfc -->

                          <!-- Uso Factura -->
                          <div class="form-group col-sm-6">
                            <label>Uso de la Factura <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Uso" name="Uso" data-required="true" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Usos, 0);
                                while($Uso = mysqli_fetch_array($Usos)) {
                                ?>
                                  <option <?php if( $Uso['Id'] == $Cli['Fk_FacturaUso'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Uso['Id']; ?>"><?php echo $Uso['Clave'].' - '.$Uso['Uso']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Uso Factura -->

                          <!-- Email -->
                          <div class="form-group col-sm-6">
                            <label>Email <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" data-type="email" name="Email" value="<?php echo $Cli['Email']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Email -->

                          <!-- Titulo -->
                          <div class="col-sm-12">
                            <h4>Dirección</h4>
                            <hr />
                          </div>

                          <!-- Calle -->
                          <div class="form-group col-sm-12">
                            <label>Calle <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Calle" value="<?php echo $Cli['Calle']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Calle -->

                          <!-- NoExt -->
                          <div class="form-group col-sm-4">
                            <label>Número Exterior <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="NoExt" value="<?php echo $Cli['NoExterior']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End NoExt -->

                          <!-- NoInt -->
                          <div class="form-group col-sm-4">
                            <label>Número Interior</label>
                            <div class="controls">
                              <input name="NoInt" value="<?php echo $Cli['NoInterior']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End NoInt -->

                          <!-- Codigo Postal -->
                          <div class="form-group col-sm-4">
                            <label>Código Postal <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="CodigoPostal" value="<?php echo $Cli['CodigoPostal']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Codigo Postal -->

                          <!-- Colonia -->
                          <div class="form-group col-sm-12">
                            <label>Colonia <span class="text-danger">*</span></label>
                            <div class="controls">
                              <input data-required="true" name="Colonia" value="<?php echo $Cli['Colonia']; ?>" type="text" class="form-control" autocomplete="off">
                            </div>
                          </div>
                          <!-- End Colonia -->

                          <!-- Pais -->
                          <div class="form-group col-sm-4">
                            <label>País <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Pais" name="Pais" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Paises, 0);
                                while($Pai = mysqli_fetch_array($Paises)) {
                                ?>
                                  <option <?php if( $Pai['Id'] == $Cli['Fk_Pais'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Pai['Id']; ?>"><?php echo $Pai['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Pais -->

                          <!-- Estado -->
                          <div class="form-group col-sm-4">
                            <label>Estado <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Estado" name="Estado" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Estados, 0);
                                while($Est = mysqli_fetch_array($Estados)) {
                                ?>
                                  <option <?php if( $Est['Id'] == $Cli['Fk_Estado'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Est['Id']; ?>"><?php echo $Est['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Estado -->

                          <!-- Municipio -->
                          <div class="form-group col-sm-4">
                            <label>Municipio <span class="text-danger">*</span></label>
                            <div class="controls">
                              <select id="Municipio" name="Municipio" class="form-control chosen-select">
                                <option></option>
                                <?php
                                mysqli_data_seek($Municipios, 0);
                                while($Mun = mysqli_fetch_array($Municipios)) {
                                ?>
                                  <option <?php if( $Mun['Id'] == $Cli['Fk_Municipio'] ){ echo 'selected="selected"'; } ?> value="<?php echo $Mun['Id']; ?>"><?php echo $Mun['Nombre']; ?></option>
                                <?php } ?>
                              </select>
                            </div>
                          </div>
                          <!-- End Municipio -->

                        </div>

                      </div>
                    </div>
                    <!-- End Card -->

                  </div>
                </div>
              </form>
              <!-- ============================================================== -->
              <!-- End Page Content -->
              <!-- ============================================================== -->
            </div>
            <!-- ============================================================== -->
            <!-- End Container fluid  -->
            <!-- ============================================================== -->

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

        </div>
        <!-- ============================================================== -->
        <!-- End Page wrapper  -->
        <!-- ============================================================== -->
    </div>

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

      $(".chosen-select").chosen();

      //Pais-Estados
      $("#Pais").change(function () {
        $("option:selected", this).each(function () {
          pai = $(this).val();
          //Actualiza Estados
          $.post("estados.php", { pai: pai }, function(data){
            $('#Estado').html(data);
            $('#Estado').trigger("chosen:updated");
          });
        });
      });
      //End Pais-Estados

      //Estado-Municipios
      $("#Estado").change(function () {
        $("option:selected", this).each(function () {
          est = $(this).val();
          //Actualiza Estados
          $.post("municipios.php", { est: est }, function(data){
            $('#Municipio').html(data);
            $('#Municipio').trigger("chosen:updated");
          });
        });
      });
      //End Estado-Municipios

      <?php if( $Save == 'Ok' ){ ?>
      $( document ).ready(function() {
          swal({
            title: "Elemento Guardado!",
            text: "...",
            timer: 2000,
            showConfirmButton: false
          });
      });
      <?php } ?>

    </script>

</body>

</html>
