<?php
  $Seccion      = 'Facturacion';
  $SubSeccion   = 'Prefacturas';
  $NameSec      = 'Prefacturas';
  $SecLine      = array('Facturación', 'Prefacturas');
  $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');

  //Inhabilitar PreFacturas
  if( $_POST['Borrar'] == 'Ok' && $_POST['Id'] ){
    $Id = addslashes(strip_tags( $_POST['Id'] ));
    $Hoy = date('Y-m-d H:s:i');
    //Elimina
    // $Query = "UPDATE FacturasPre SET Borrar = '1', FechaBorrar = '$Hoy' WHERE Id = '$Id'";
    $Query = "
      DELETE FROM FacturasPre
      WHERE Id = '$Id'
    ";
    $Result = mysqli_query($mysqli, $Query);

    $Query = "
      DELETE FROM FacturasPreConceptos
      WHERE Fk_FacturaPre = '$Id'
    ";
    $Result = mysqli_query($mysqli, $Query);

  }
  //End Borrar

  //Realiza Facturación
  if( $_POST['DoFacGo'] == 'Ok' ){

    $GoFacs = $_POST[GoFacs];
    $Cant = 0;
    $PreIds = '';
    foreach( $GoFacs AS $GoFac ){
      $Cant = $Cant + 1;
      //echo $GoFac.'<br>';
      $PreIds = $PreIds.','.$GoFac;
    }
    $PreIds = ltrim($PreIds,',');

    //Inserta Registro
    $Fecha = date('Y-m-d H:i:s');
    $Query = "
      INSERT INTO FacturasPreMultiples
      (
        Fk_Usuario, Fecha,
        CantidadPrefacturas, Prefacturas
      ) VALUES (
        '$User[Id]', '$Fecha',
        '$Cant', '$PreIds'
      )
    ";
    $Result = mysqli_query($mysqli, $Query);

    if( $CreditosFac >= $Cant ){
      echo "Go Fac";
      if( $PlataformaFac[Id] ){
        //Variable para Timbrar
        $DoTimbrado = 'Ok';
        require_once('plataformas/facturama.php');
      }
    }else{
      //echo "Sin Saldo";
      $SinSaldo = 'Ok';
    }
  }
  //End Realiza Facturación

  //Filtrar
  $Where = "
    WHERE fac.Id != '0'
    AND fac.Borrar = '0'
    AND fac.Fk_Cuenta = '$Cuenta_Id'
    AND fac.Fk_Perfil = '$PerfilSel_Id'
  ";

  if( $_GET[Filtrar] == 'Ok' ){
    //Variables
    $Filtrar     = 'Ok';
    $NomSel      = $_GET[Nom];
    $RfcSel      = $_GET[Rfc];
    $FilSer      = $_GET[Ser];
    $FilOri      = $_GET[Ori];
    $FilDes      = CambioFechaCompleta($_GET[Desde]);
    $FilHas      = CambioFechaCompleta($_GET[Hasta]);
    if( $FilSer ){ $Where .= "AND fac.Serie LIKE '%$FilSer%' "; }
    if( $CliSel ){ $Where .= "AND fac.Receptor LIKE '%$NomSel%' "; }
    if( $RfcSel ){ $Where .= "AND fac.RfcReceptor LIKE '%$RfcSel%' "; }
    if( $FilOri ){ $Where .= "AND fac.Fk_Origen = '$FilOri' "; }
    if( !empty($FilDes) && !empty($FilHas) ){
      $Where .= "AND ( fac.Fecha BETWEEN '$FilDes' AND '$FilHas' ) ";
    }

  }else{

    $FilDes      = date('Y-m-01');
    $FilHas      = date('Y-m-t');
    if( !empty($FilDes) && !empty($FilHas) ){
      $Where .= "AND ( fac.Fecha BETWEEN '$FilDes' AND '$FilHas' ) ";
    }

  }

  //Filtra Validados para generar facturas
  if( $_GET[DoFac] == 'Ok' ){
    $Where .= "AND fac.Validacion = '1' ";
  }
  //End Filtra Validados para generar facturas

  // PreFacturas
  $Query = "
    SELECT
      fac.Id, fac.Fk_Origen,
      fac.Fk_Factura,
      fac.Fk_Status, fac.Fk_Factura, fac.Fecha, fac.Serie,
      fac.RfcEmisor, fac.Emisor,
      fac.RfcReceptor, fac.Receptor,
      fac.Subtotal, fac.Impuesto, fac.Total
    FROM FacturasPre fac
    $Where
    ORDER BY fac.Fecha DESC
  ";
  $Prefacs = $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">
                <!-- ============================================================== -->
                <!-- Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <div class="row page-titles">

                    <?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">

                        <!-- Realizar Prefactura -->
                        <button
                          type="button"
                          class="btn btn-sm btn-secondary"
                          onclick="window.location.href='prefactura'"
                        >
                          <i class="fa fa-plus m-r-5"></i>
                          Realizar Prefactura
                        </button>
                        <!-- End Realizar Prefactura -->

                        <?php if( $_GET[DoFac] == 'Ok' ){}else{ ?>
                          <!--<button
                            type="button"
                            class="btn btn-sm btn-secondary"
                            onclick="window.location.href='?DoFac=Ok'"
                          >
                            Facturar
                            <i class="fa fa-file-o m-l-10"></i>
                          </button>-->
                        <?php } ?>

                        <!-- <button type="button" class="btn btn-secondary" onclick="window.location.href='prefactura.php'">Nueva Pre-Factura <i class="fa fa-plus m-l-5"></i></button> -->
                        <?php
                          if( $_GET[DoFac] == 'Ok' ){
                        ?>
                          <?php
                            if( $PlataformaFac[Id] == 1 || $PlataformaFac[Id] == 2 ){
                              //Si la conección con Proveedor de Facturas es valido
                              $curl = curl_init();
                              curl_setopt_array($curl, array(
                                CURLOPT_URL => $PlataformaFac[UrlConexion],
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_ENCODING => "",
                                CURLOPT_MAXREDIRS => 10,
                                CURLOPT_TIMEOUT => 30,
                                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                CURLOPT_CUSTOMREQUEST => "GET",
                                CURLOPT_HTTPHEADER => array(
                                  "Authorization: $PlataformaFac[Autorization]",
                                  "Cache-Control: no-cache",
                                  "Content-Type: application/json",
                                  "Postman-Token: $PlataformaFac[Token]"
                                ),
                              ));

                              $response = curl_exec($curl);
                              $err = curl_error($curl);
                              curl_close($curl);
                              $response;
                            	$obj = json_decode($response);

                          ?>
                            <?php if($obj->Plan == 'API') { ?>
                              <button
                                type="button"
                                class="btn btn-secondary"
                              >
                                <?php echo $CreditosFac; ?> Creditos
                              </button>
                              <button
                                type="button"
                                class="btn btn-success BtnDoFac"
                              >
                                <?php
                                  if( $PlataformaFac[Sandbox] == 1 ){
                                ?>
                                  Sanbox
                                <?php } ?>
                                Facturar <i class="fa fa-file m-l-10"></i>
                              </button>
                              <!-- Modal Facturar -->
                              <div id="ModalFacturar" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                  <div class="modal-content">
                                    <div class="modal-header">
                                      <h4 class="modal-title" id="myModalLabel">Facturar</h4>
                                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                    </div>
                                    <div class="modal-body text-center">
                                      <h5>Realizar Facturación</h5>
                                      <p>
                                        ¿Estas seguro de realizar esta acción?
                                      </p>
                                    </div>
                                    <div class="modal-footer">
                                      <button type="button" class="btn btn-success waves-effect BtnGoFac">Si. Realizar facturas</button>
                                      <button type="button" class="btn btn-secondary waves-effect" data-dismiss="modal">No</button>
                                    </div>
                                  </div>
                                  <!-- /.modal-content -->
                                </div>
                                <!-- /.modal-dialog -->
                              </div>
                              <!-- End Modal Facturar -->
                            <?php } ?>
                          <?php } ?>
                        <?php } ?>
                      </div>
                    </div>
                    <!-- End Botones -->

                </div>
                <!-- ============================================================== -->
                <!-- End Bread crumb and right sidebar toggle -->
                <!-- ============================================================== -->
                <!--  Factura Mensual -->

                <!--  End Factura Mensual -->
                <!-- ============================================================== -->
                <!-- Page Content -->
                <!-- ============================================================== -->
                <div class="row">
                    <div class="col-12">

                      <!-- Buscador -->
                      <div>

                        <div class="card">
                          <div class="card-body">
                            <form method="get">
                              <div class="row">

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

                                <!-- Nombre -->
                                <div class="col-sm-5">
                                  <div class="form-group">
                                    <label class="control-label">Cliente</label>
                                    <input
                                      name="Nom"
                                      type="text"
                                      class="form-control form-control-sm"
                                      autocomplete="off"
                                      placeholder=""
                                      value="<?php echo $NomSel; ?>"
                                    >
                                  </div>
                                </div>
                                <!-- End Nombre -->

                                <!-- RFC -->
                                <div class="col-sm-4">
                                  <div class="form-group">
                                    <label class="control-label">RFC</label>
                                    <input
                                      name="Rfc"
                                      type="text"
                                      class="form-control form-control-sm"
                                      autocomplete="off"
                                      placeholder=""
                                      value="<?php echo $RfcSel; ?>"
                                    >
                                  </div>
                                </div>
                                <!-- End RFC -->

                                <!-- Serie -->
                                <div class="col-sm-3">
                                  <div class="form-group">
                                    <label class="control-label">Serie</label>
                                      <input
                                        name="Ser"
                                        type="text"
                                        class="form-control form-control-sm"
                                        autocomplete="off"
                                        placeholder=""
                                        value="<?php echo $FilSer; ?>"
                                      >
                                  </div>
                                </div>
                                <!-- End Serie -->

                                <!-- Origen -->
                                <div class="col-sm-3">
                                  <div class="form-group">
                                    <label class="control-label">Origen</label>
                                    <select
                                      name="Ori"
                                      id="Origen"
                                      class="form-control chosen-select"
                                    >
                                      <option value="">Todos</option>
                                      <?php
                                        //Origenes
                                        $Query = "
                                          SELECT
                                            ori.Id, ori.Origen
                                          FROM FacturasOrigenes ori
                                          ORDER BY ori.Origen DESC
                                        ";
                                        $Oris = $mysqli->query($Query);
                                        mysqli_data_seek($Oris, 0);
                                        while($Ori = mysqli_fetch_array($Oris)) {
                                      ?>
                                        <option
                                          value="<?php echo $Ori[Id]; ?>"
                                          <?php
                                            if( $Ori[Id] == $FilOri ){
                                          ?>
                                            selected="selected"
                                          <?php } ?>
                                        >
                                          <?php echo $Ori['Origen']; ?>
                                        </option>
                                      <?php } ?>
                                    </select>
                                  </div>
                                </div>
                                <!-- End Origen -->

                                <!-- Desde -->
                                <div class="col-sm-3">
                                  <div class="form-group">
                                    <label class="control-label">Desde</label>
                                    <input
                                      name="Desde"
                                      value="<?php echo CambioFechaInversa($FilDes); ?>"
                                      type="text"
                                      class="form-control form-control-sm datepicker"
                                      placeholder=""
                                    >
                                  </div>
                                </div>
                                <!-- End Desde -->

                                <!-- Hasta -->
                                <div class="col-sm-3">
                                  <div class="form-group">
                                    <label class="control-label">Hasta</label>
                                    <input
                                      name="Hasta"
                                      value="<?php echo CambioFechaInversa($FilHas); ?>"
                                      type="text"
                                      class="form-control form-control-sm datepicker"
                                      placeholder=""
                                    >
                                  </div>
                                </div>
                                <!-- End Hasta -->

                                <!-- Filtrar -->
                                <div class="col-sm-3">
                                  <div class="form-group">
                                    <label class="control-label">.</label>
                                    <button class="btn btn-success btn-block" type="submit" name="button">Filtrar <i class="fa fa-search mar-l-5"></i></button>
                                    <input type="hidden" name="DoFac" value="<?php echo $_GET['DoFac']; ?>" />
                                    <input type="hidden" name="Filtrar" value="Ok" />
                                  </div>
                                </div>
                                <!-- End Filtrar -->

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

                      </div>
                      <!-- End Buscador -->

                      <!-- Pre facturas -->
                      <div class="card">
                        <div class="card-body">

                          <!-- Title -->
                          <div class="row">
                            <div class="col-sm-6">
                              <h4 class="card-title m-0"><?php echo $NameSec; ?></h4>
                            </div>
                            <div class="col-sm-6">
                              <!--
                              <div class="input-group">
                                <ul
                                  class="icheck-list ListLi"
                                  style="padding:0px !important;"
                                >
                                  <li style="float:right;text-align: right;">
                                    <label class="m-r-10" for="ValPre">Seleccionar todas</label>
                                    <input
                                      type="checkbox"
                                      class="all check"
                                      value="1"
                                      data-checkbox="icheckbox_square-blue"
                                    >
                                  </li>
                                </ul>
                              </div>
                              -->
                            </div>
                          </div>
                          <!-- End Title -->

                          <div class="table-responsive m-t-20">
                            <table id="example23" class="display nowrap table table-hover table-striped table-bordered" cellspacing="0" width="100%">
                              <thead>
                                <tr>
                                  <th>Serie</th>
                                  <th>Cliente</th>
                                  <th>Fecha</th>
                                  <th width="150">Monto</th>
                                  <th style="width:20px;"></th>
                                  <th style="width:20px;"></th>
                                </tr>
                              </thead>
                              <tbody>
                              <?php
                                mysqli_data_seek($Prefacs, 0);
                                while($Prefac = mysqli_fetch_array($Prefacs)) {
                              ?>
                                  <tr>

                                    <!-- Seria -->
                                    <td>
                                      <?php echo $Prefac['Serie']; ?>
                                      <div style="color:#fff;">
                                        <?php echo $Prefac[Id]; ?>
                                      </div>
                                    </td>
                                    <!-- End Serie -->

                                    <!-- Cliente -->
                                    <td>
                                      <div>
                                        <?php echo $Prefac['Receptor']; ?>
                                      </div>
                                      <div>
                                        <?php echo $Prefac['RfcReceptor']; ?>
                                      </div>
                                    </td>
                                    <!-- End Cliente -->

                                    <!-- Fecha -->
                                    <td>
                                      <span style="display:none;"><?php echo $Prefac['Fecha']; ?></span>
                                      <div>
                                        <?php
                                          echo CambioFechaInversa(date('Y-m-d', strtotime($Prefac['Fecha'])));
                                        ?>
                                      </div>
                                      <div>
                                        <?php echo date('H:i', strtotime($Prefac['Fecha'])); ?> hrs
                                      </div>
                                    </td>
                                    <!-- End Fecha -->

                                    <!-- Monto -->
                                    <td>
                                      $ <?php echo number_format($Prefac[Total],2,'.',','); ?>
                                    </td>
                                    <!-- End Monto -->

                                    <!-- Btn Ver -->
                                    <td>
                                      <div class="text-left">

                                        <button
                                          type="button"
                                          onclick="window.location.href='prefactura?Id=<?php echo $Prefac['Id']; ?>'"
                                          class="btn btn-sm btn-secondary">
                                          Ver Pre Factura<i class="fa fa-file m-l-10"></i>
                                        </button>

                                        <?php if( $Prefac[Fk_Origen] == '1' ){ ?>
                                        <?php }elseif( $Prefac[Fk_Origen] == '2' ){ ?>
                                          <!-- Origne Api -->
                                          <div>
                                            <span class="label label-success">
                                              Api
                                            </span>
                                          </div>
                                          <!-- End Origne Api -->
                                        <?php } ?>

                                        <?php if( $Prefac[Fk_Status] == 1 ){ ?>

                                        <?php }else{ ?>

                                          <?php if( $Prefac['Fk_Factura'] ){ ?>
                                            <!-- Btn ver Factura --
                                            <button
                                              type="button"
                                              onclick="window.location.href='<?php echo $Position; ?>finanzas/facturacion/facturas/factura.php?Id=<?php echo $Prefac['Fk_Factura']; ?>'"
                                              class="btn btn-sm btn-warning m-r-10"
                                            >
                                              <i class="fa fa-file m-r-10"></i>
                                              Ver Factura Timbrada
                                            </button>
                                            <!-- End Ver Factura -->
                                          <?php } ?>

                                        <?php } ?>

                                      </div>
                                    </td>
                                    <!-- En Btn Ver -->

                                    <!-- Btn Borrar -->
                                    <td>
                                      <div class="text-right">

                                        <?php if( $_GET[DoFac] == 'Ok' ){ ?>
                                          <?php if( $Prefac[Fk_Status] == 1 ){ ?>
                                            <div class="input-group">
                                              <ul
                                                class="icheck-list ListLi"
                                                style="padding:0px !important;"
                                              >
                                                <li>
                                                  <input
                                                    type="checkbox"
                                                    class="check BtnCheckFac"
                                                    name="GoFacs[]"
                                                    value="<?php echo $Prefac[Id]; ?>"
                                                    data-checkbox="icheckbox_square-blue"
                                                    <?php if($ExisteRelacion['Id']){ ?> checked="checked"<?php }?>
                                                  >
                                                  <!--<label for="ValPre">Facturar</label>-->
                                                </li>
                                              </ul>
                                            </div>
                                          <?php } ?>
                                        <?php }else{ ?>

                                          <?php if( $Prefac[Fk_Factura] ){ ?>

                                            <button
                                              onclick="window.location.href='<?php echo $Position; ?>facturacion/facturas/factura?Id=<?php echo $Prefac['Fk_Factura']; ?>'"
                                              class="btn btn-sm btn-warning"
                                            >
                                              Ver Factura
                                              <i class="fa fa-file m-l-10"></i>
                                            </button>

                                          <?php }else{ ?>

                                            <button
                                              value="<?php echo $Prefac[Id]; ?>"
                                              data-datos="<?php echo CambioFechaInversa(date('Y-m-d', strtotime($Prefac['Fecha']))); echo '<br>'.$Prefac['Receptor'].'<br>'.$Prefac['RfcReceptor'].'<br>Monto: $ '.$Prefac[Total]; ?>"
                                              data-datos="test"
                                              type="button"
                                              class="btn btn-sm btn-danger DelPre">
                                              <i class="fa fa-times"></i>
                                            </button>

                                          <?php } ?>

                                        <?php } ?>
                                      </div>
                                    </td>
                                    <!-- End Btn Borrar -->

                                  </tr>
                              <?php } ?>
                              </tbody>
                            </table>
                          </div>

                        </div>
                      </div>
                      <!-- End Pre Facturas -->

                      <!-- Modal Borrar -->
                      <form method="post">
                        <div id="DelPreModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                          <div class="modal-dialog">
                            <div class="modal-content">
                              <div class="modal-header">
                                <h4 class="modal-title" id="myModalLabel">Eliminar Prefactura</h4>
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                              </div>
                              <div class="modal-body text-center">
                                <h5>¿Estás seguro de Eliminar esta Prefactura ?</h5>
                                <p id="DelData"></p>
                              </div>
                              <div class="modal-footer">

                                <!-- Btn Eliminar -->
                                <button
                                  type="submit"
                                  class="btn btn-danger"
                                >
                                  Eliminar
                                </button>
                                <!-- End Btn Eliminar -->

                                <!-- Btn No -->
                                <button
                                  type="button"
                                  class="btn btn-secondary waves-effect"
                                  data-dismiss="modal"
                                >
                                  No
                                </button>
                                <!-- End Btn No -->

                                <input type="hidden" name="Borrar" value="Ok">
                                <input id="DelId" type="hidden" name="Id" value="">
                              </div>
                            </div>
                            <!-- /.modal-content -->
                          </div>
                          <!-- /.modal-dialog -->

                        </div>
                      </form>
                      <!-- End Modal Borrar -->

                    </div>
                </div>
                <!-- ============================================================== -->
                <!-- 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();

      $('#example23').DataTable({
        dom: 'Bfrtip',
        searching: false,
        pageLength: 20,
        order: [],
        ordering: true
        //paging: false,
      });

      //Boton borrar
      $(document.body).on('click', '.DelPre' ,function(){
        console.log('Ver test');
      });

      $(document.body).on('click', '.DelPre' ,function(){
        id    = $(this).val();
        msn   = $(this).data('datos');
        console.log(id);
        console.log(msn);
        $('#DelId').val(id);
        $('#DelData').html(msn);
        $('#DelPreModal').modal('show');
      });
      //End Boton borrar

      //Botones para Facturar
      $( ".BtnDoFac" ).click(function() {
        $('#ModalFacturar').modal('show');
      });

      $( ".BtnGoFac" ).click(function() {
        $('#ModalFacturar').modal('hide');
        swal({
          title: "¡Timbrando Facturas!",
          text: "Esto puede demorar algun tiempo, por favor espera.",
          showConfirmButton: false
        });
        $('#FormDoFac').submit();
      });
      //End Botones para Facturar

      <?php if( $SinSaldo == 'Ok' ){ ?>
        //Sin saldo
        swal({
          title: "¡No hay suficientes créditos!",
          text: "Por favor, agrega más créditos para realizar esta acción.",
          showConfirmButton: true
        });
        //End Sin Saldo
      <?php } ?>

    </script>

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

</body>

</html>
