<?php
  $Seccion      = 'Facturacion';
  $SubSeccion   = 'Facturacion';
  $NameSec      = 'Consulta de Facturas';
  $SecLine      = array('Finanzas', 'Facturación', 'Consulta de Facturas');
  $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');
  require_once($Position.'funciones/paginador1.php');

  /*//Borrar
  if( $_POST['Borrar'] == 'Ok' && $_POST['Id'] ){

    $Id = addslashes(strip_tags( $_POST['Id'] ));
    //Elimina
    $Query = "DELETE FROM 2111 WHERE Id = '$Id'";
    $Result = mysqli_query($mysqli, $Query);

  }
  //End Borrar*/

  //Filtrar
  $Where = "
    WHERE fac.Id != '0'
    AND fac.Fk_Cuenta = '$Cuenta[Id]'
    AND fac.RfcEmisor = '$PerfilSel[Rfc]'
  ";
  if( $_GET[Filtrar] == 'Ok' ){
    //Variables
    $Filtrar     = 'Ok';
    $FilSer      = $_GET[Ser];
    $FilFol      = $_GET[Fol];
    $FilNom      = $_GET[Nom];
    $FilRfc      = $_GET[Rfc];
    $FilDes      = $_GET[Desde];
    $FilHas      = $_GET[Hasta];
    if( $FilSer ){ $Where .= "AND fac.Serie LIKE '%$FilSer%' "; }
    if( $FilFol ){ $Where .= "AND fac.Folio = '$FilFol' "; }
    if( $FilNom ){ $Where .= "AND fac.Receptor LIKE '%$FilNom%' "; }
    if( $FilRfc ){ $Where .= "AND fac.RfcReceptor LIKE '%$FilRfc%' "; }
    if( !empty($FilDes) && !empty($FilHas) ){

      $Des = CambioFechaCompleta($FilDes);
      $Has = CambioFechaCompleta($FilHas).' 23:59:59';
      $Where .= "AND ( fac.Fecha BETWEEN '$Des' AND '$Has' ) ";

      $FilDes = CambioFechaCompleta($FilDes);
      $FilHas = CambioFechaCompleta($FilHas);

    }else{
      if( !empty($FilDes) && empty($FilHas) ){
        $Des = CambioFechaCompleta($FilDes);
        $Where .= "AND fac.Fecha LIKE '$Des%' ";
      }
      if( empty($FilDes) && !empty($FilHas) ){
        $Has = CambioFechaCompleta($FilHas).' 23:59:59';
        $Where .= "AND fac.Fecha LIKE '$Has%' ";
      }

    }

  }else{

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

  }

  // Paginación
	if (isset($_GET['pgn']))
	{
		$pgn =  $_GET['pgn']; // $pg es la pagina actual
	}
	else{
    $pgn = 0;
  }
	$cantidad = 100; // cantidad de resultados por página
	$PagerLap = $cantidad / 10;
	$inicial = $pgn * $cantidad;

  // Facturas
  $Query = "
    SELECT
      fac.Id,
      fac.Sandbox,
      fac.Fecha, fac.RfcEmisor, fac.Emisor,
      fac.RfcReceptor, fac.Receptor,
      fac.Subtotal, fac.Impuesto, fac.Total,
      fac.Serie, fac.Folio, fac.IdFac, fac.Uuid,
      fac.Xml, fac.Pdf,
      fac.Cancelada, fac.FechaCancelacion
    FROM Facturas fac
    $Where
    ORDER BY fac.Id DESC, fac.Fecha DESC
    LIMIT $inicial, $cantidad;
  ";
  $Facs = $mysqli->query($Query);

  //Contar
  $Query = "
    SELECT
    COUNT(fac.Id) AS Total
    FROM Facturas fac
    $Where
  ";
  $Result = mysqli_query($mysqli, $Query);
  $TotalClis = mysqli_fetch_assoc($Result);
	$TotalItems = $TotalClis[Total];
	$pages = intval($TotalItems / $cantidad);

?>

<!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">
                        <!--<button type="button" class="btn btn-sm btn-secondary BtnFiltrar">Filtrar <i class="fa fa-search m-l-5"></i></button>-->

                        <!-- Btn Nueva Factura -->
                        <button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='../facturar'">Nueva Factura <i class="fa fa-plus m-l-5"></i></button>
                        <!-- End Btn Nueva Factura -->

                      </div>
                    </div>
                    <!-- End Botones -->

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

                      <!-- Buscador -->
                      <div id="Filtrar" <?php /*if( $Filtrar == 'Ok' ){}else{ echo "style='display:none;'"; }*/ ?>>

                        <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 $FilNom; ?>"
                                      >
                                  </div>
                                </div>
                                <!-- End Nombre -->

                                <!-- RFC -->
                                <div class="col-sm-3">
                                  <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 $FilRfc; ?>"
                                      >
                                  </div>
                                </div>
                                <!-- End RFC -->

                                <!-- Serie -->
                                <div class="col-sm-2">
                                  <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 -->

                                <!-- Folio -->
                                <div class="col-sm-2">
                                  <div class="form-group">
                                    <label class="control-label">Folio</label>
                                      <input
                                        name="Fol"
                                        type="text"
                                        class="form-control form-control-sm"
                                        autocomplete="off" placeholder="" value="<?php echo $FilFol; ?>">
                                  </div>
                                </div>
                                <!-- End Folio -->

                                <!-- 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="Filtrar" value="Ok" />
                                  </div>
                                </div>
                                <!-- End Filtrar -->

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

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

                      <div class="card">
                        <div class="card-body">
                          <h4 class="card-title">Facturas</h4>
                          <div class="table-responsive m-t-40">

                            <!-- Tabla Facturas -->
                            <table id="" class="display nowrap table table-hover table-striped table-bordered" cellspacing="0" width="100%">
                              <thead>
                                <tr>
                                  <!--<th>Id</th>-->
                                  <th>Folio</th>
                                  <th>Cliente</th>
                                  <th>Fecha</th>
                                  <th>Monto</th>
                                  <th width="20"></th>
                                  <th width="20"></th>
                                  <th width="20"></th>
                                </tr>
                              </thead>
                              <tbody>
                                <?php
                                  mysqli_data_seek($Facs, 0);
                                  while($Fac = mysqli_fetch_array($Facs)) {
                                ?>
                                  <tr>

                                    <!-- Id --
                                    <td><?php echo $Fac[Id]; ?></td>
                                    <!-- End Id -->

                                    <!-- Folio -->
                                    <td>
                                      <?php echo $Fac[Serie]; ?> - <?php echo $Fac[Folio]; ?>
                                      <div style="color:transparent;">
                                        Id: <?php echo $Fac[Id]; ?>
                                      </div>
                                    </td>
                                    <!-- End Folio -->

                                    <!-- Cliente -->
                                    <td>
                                      <div>
                                        <?php echo $Fac[Receptor]; ?>
                                      </div>
                                      <div>
                                        <?php echo $Fac['RfcReceptor']; ?>
                                      </div>
                                      <div>
                                        <hr />
                                      </div>
                                      <div>
                                        <i class="fa fa-file m-r-10"></i><?php echo $Fac['Uuid']; ?>
                                      </div>
                                      <div>
                                        <i class="fa fa-file m-r-10"></i><?php echo $Fac['IdFac']; ?>
                                      </div>
                                    </td>
                                    <!-- End Cliente -->

                                    <!-- Fecha -->
                                    <td>
                                      <?php echo CambioFechaInversa(date('Y-m-d', strtotime($Fac['Fecha']))); ?>
                                    </td>
                                    <!-- End Fecha -->

                                    <!-- Monto -->
                                    <td class="text-right">
                                      $ <?php echo number_format($Fac[Total],2,'.',','); ?>
                                    </td>
                                    <!-- End Monto -->

                                    <!-- Pdf -->
                                    <td>
                                      <?php //if( $Fac[Pdf] ){ ?>
                                        <div class="m-b-10">
                                          <button onclick="window.open('pdf?Id=<?php echo $Fac['Id']; ?>')" class="btn btn-success btn-sm" >
                                            PDF<i class="fa fa-file m-l-10"></i>
                                          </button>
                                        </div>
                                      <?php //} ?>

                                      <?php if( $Fac[Xml] ){ ?>
                                        <button onclick="window.open('xml.php?Id=<?php echo $Fac['Id']; ?>')" class="btn btn-success btn-sm" >
                                          XML<i class="fa fa-file m-l-10"></i>
                                        </button>
                                      <?php } ?>

                                    </td>
                                    <!-- End Pdf -->

                                    <!-- Send Fac Mail -->
                                    <td>
                                      <?php //if( $Fac[Pdf] ){ ?>
                                        <button data-toggle="modal" data-target="#Mailk<?php echo $Fac[Id]; ?>" type="button" class="btn btn-success btn-sm" >
                                          Mail<i class="fa fa-envelope m-l-10"></i>
                                        </button>

                                        <!-- Modal Envio Mail Factura -->
                                        <form class="Form-SendMail" method="post" data-validate="parsley" role="form">
                                          <div id="Mailk<?php echo $Fac[Id]; ?>" class="modal fade Modal-SendMail" 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">Enviar Factura por correo</h4>
                                                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                                </div>
                                                <div class="modal-body">

                                                  <?php
                                                  //Correo de Cliente
                                                  $Query = "
                                                    SELECT
                                                      cli.Id, cli.Rfc, cli.Email
                                                    FROM CatalogoClientes cli
                                                    WHERE cli.Rfc = '$Fac[RfcReceptor]'
                                                  ";
                                                  $Result = mysqli_query($mysqli, $Query);
                                                  $Correo    = mysqli_fetch_assoc($Result);
                                                  ?>

                                                  <!-- Correo -->
                                                  <div class="form-group">
                                                    <label>Correo</label>
                                                    <!-- Input Correo -->
                                                    <input
                                                      data-required="true"
                                                      data-type="email"
                                                      class="form-control"
                                                      autocomplete="off"
                                                      name="Correo"
                                                      value="<?php echo $Correo[Email]; ?>"
                                                    />
                                                    <!-- End Input Correo -->
                                                  </div>
                                                  <!-- End Correo -->

                                                  <!-- Mensaje -->
                                                  <div class="form-group">
                                                    <label>Mensaje</label>
                                                    <!-- Textarea Mensaje -->
                                                    <textarea
                                                      data-required="true"
                                                      name="Mensaje"
                                                      class="form-control"
                                                    ><?php ?></textarea>
                                                    <!-- End Textarea Mensaje -->
                                                  </div>
                                                  <!-- End Mensaje -->

                                                </div>
                                                <div class="modal-footer">

                                                  <!-- Btn Send Mail -->
                                                  <button
                                                    type="button"
                                                    class="btn btn-success BtnSendMail"
                                                  >
                                                    Enviar
                                                    <i class="fa fa-send m-l-10"></i>
                                                  </button>
                                                  <!-- End Btn Send Mail -->

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

                                                  <input type="hidden" name="SendMail" value="Ok">
                                                  <input type="hidden" name="IdFac" value="<?php echo $Fac[Id]; ?>">
                                                </div>
                                              </div>
                                              <!-- /.modal-content -->
                                            </div>
                                            <!-- /.modal-dialog -->

                                          </div>
                                        </form>
                                        <!-- End Modal Envio Mail Factura -->

                                      <?php //} ?>
                                    </td>
                                    <!-- End Send Fac Mail -->

                                    <!-- Cancelada -->
                                    <td>
                                      <?php if( $Fac[Cancelada] == '1' ){ ?>
                                        <div>
                                          <a href="factura?Id=<?php echo $Fac['Id']; ?>">
                                            <button
                                              class="btn btn-success btn-sm"
                                            >
                                              <i class="fa fa-file m-r-5"></i>
                                              Ver Factura
                                            </button>
                                          </a>
                                        </div>
                                        <div>
                                          <button
                                            class="btn btn-sm btn-danger"
                                            type="button"
                                          >
                                          <i class="fa fa-file m-r-5"></i>
                                          Cancelada
                                        </button>
                                        </div>
                                      <?php }else{ ?>
                                        <a href="factura?Id=<?php echo $Fac['Id']; ?>">
                                          <button
                                            type="button"
                                            class="btn btn-success btn-sm"
                                          >
                                            <i class="fa fa-file m-r-5"></i>
                                            Ver Factura
                                          </button>
                                        </a>
                                        <?php if( $Fac[Sandbox] == '1' ){ ?>
                                          <!-- Origne Api -->
                                          <div>
                                            <span class="label label-success">
                                              Sanbox
                                            </span>
                                          </div>
                                          <!-- End Origne Api -->
                                        <?php } ?>
                                      <?php } ?>
                                    </td>
                                    <!-- End Cancelada -->

                                  </tr>
                                <?php } ?>
                              </tbody>
                            </table>
                            <!-- End Tabla Facturas -->

                          </div>

                          <!-- Paginador -->
                          <section class="BtnPaginador" style="display: table; width: 100%; height: 30px;">
                             <div class="btn-toolbar col-sm-12">
            		                <div class="btn-group" style="right: 0px;position: absolute;">
            										  <?php
            										  $cantRegistros  = $TotalItems / $PagerLap;
            										  $pgnActual      = $_GET['pgn'];
            										  $pag            = new Paginador();
            										  $datos          = $pag->paginar($pgnActual, $cantRegistros);
            										  if ($datos) {
            										  'Pagina: ' . ($_GET['pgn'] + 1) . ' de ' . $pag->getCantidadPaginas() . '<br />';
            										  foreach ($datos as $enlace) {
            										  ?>
                                    <a href="?pgn=<?php echo $enlace['numero'];
              										  if($Filtrar){
              										  	echo "&Filtrar=".$Filtrar;
                                      echo "&Desde=".$FilDes;
              										  	echo "&Hasta=".$FilHas;
                                      echo "&Ser=".$FilSer;
                                      echo "&Fol=".$FilFol;
                                      echo "&Nom=".$FilNom;
                                      echo "&Rfc=".$FilRfc;
              										  }
              										   ?>">
              		                     <button type="button" class="btn btn-secondary"><?php echo $enlace['vista']; ?></button>
                                    </a>
                                  <?php }} ?>
            		                </div>
                             </div>
                          </section>
                          <!-- /Paginador -->

                        </div>
                      </div>

                    </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>
      $('#example23').DataTable({
        dom: 'Bfrtip',
        searching: false,
        pageLength: 20,
        order: [],
        ordering: true
        //paging: false,
      });

      //Envio de Factura Mail
      $(document.body).on('click', '.BtnSendMail' ,function(){
        Formulario = $(this).parents('.Form-SendMail');
        Formulario.parsley().validate();
        if( Formulario.parsley().isValid() ){

          //Campos de Formulario
          var data = Formulario.serializeArray();
          //End Campos de Formulario

          //Hide Modal
          $('.Modal-SendMail').modal('hide');
          //End Hide Modal

          swal({
            imageUrl: '<?php echo $Position; ?>images/wait/wait1.gif',
            title: "Enviando Factura",
            text: "Espera por favor.",
            showConfirmButton: false
          });

          console.log('Aqui...');

          //Envia a Guardar Formulario
          $.post("sendmail/index.php", data,
          function(datos){
            console.log('Envaido...');
            console.log(datos);
            var obj = JSON.parse(datos);
            console.log(datos);

            if( obj.Sended == 'Ok' ){

              swal({
                title: "Enviado",
                text: "Factura enviada.",
                showConfirmButton: true
              });

            }else{

              swal({
                title: "Error",
                text: "La factura no pudo ser enviada.",
                showConfirmButton: true
              });

            }

          });
          //End Envia a Guardar Formulario

        }
      });
      //End Envio de Factura Mail

    </script>

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

</body>

</html>
