<?php
/*-------------------------
Autor: Delmar Lopez
Web: www.softwys.com
Mail: softwysop@gmail.com
---------------------------*/
include 'is_logged.php';
require_once "../db.php";
require_once "../php_conexion.php";
require_once "../funciones.php";
include "../permisos.php";
$user_id = $_SESSION['id_users'];
get_cadena($user_id);
$modulo = "Ventas";
permisos($modulo, $cadena_permisos);

$action = (isset($_REQUEST['action']) && $_REQUEST['action'] != null) ? $_REQUEST['action'] : '';
if ($action == 'ajax') {
    $q = mysqli_real_escape_string($conexion, (strip_tags($_REQUEST['q'], ENT_QUOTES)));

    // Consulta con JOIN explícito
    $sTable = "creditos";
    $sJoin  = "INNER JOIN clientes ON creditos.id_cliente = clientes.id_cliente
               INNER JOIN users ON creditos.id_vendedor = users.id_users";
    $sWhere = " WHERE 1=1";

    if ($_GET['q'] != "") {
        $sWhere .= " AND (clientes.nombre_cliente LIKE '%$q%' OR creditos.numero_factura LIKE '%$q%')";
    }

    $sWhere .= " ORDER BY creditos.id_credito DESC";

    include 'pagination.php';
    $page      = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
    $per_page  = 10;
    $adjacents = 4;
    $offset    = ($page - 1) * $per_page;

    $count_query = mysqli_query($conexion, "SELECT COUNT(*) AS numrows FROM $sTable $sJoin $sWhere");
    $row         = mysqli_fetch_array($count_query);
    $numrows     = $row['numrows'];
    $total_pages = ceil($numrows / $per_page);
    $reload      = '../reportes/facturas.php';

    $sql = "SELECT creditos.*, clientes.*, users.*
            FROM $sTable $sJoin $sWhere LIMIT $offset,$per_page";
    $query = mysqli_query($conexion, $sql);

    if ($numrows > 0) {
        ?>
        <div class="table-responsive">
          <table class="table table-sm table-striped table-hover shadow-sm">
             <thead class="thead-light">
                <tr>
                    <th># Factura</th>
                    <th>Fecha</th>
                    <th>Cliente</th>
                    <th>Estado</th>
                    <th class='text-right'>Crédito</th>
                    <th class='text-right'>Saldo</th>
                    <th class='text-right'>Abonos</th>
                    <th class='text-center'>Acciones</th>
                </tr>
            </thead>
            <tbody>
            <?php
            while ($row = mysqli_fetch_array($query)) {
                $numero_factura   = $row['numero_factura'];
                $fecha            = date("d/m/Y", strtotime($row['fecha_credito']));
                $nombre_cliente   = $row['nombre_cliente'];
                $estado_factura   = $row['estado_credito'];
                if ($estado_factura == 2) {
                    $text_estado = "Pagada";
                    $label_class = 'badge-success';
                } else {
                    $text_estado = "Pendiente";
                    $label_class = 'badge-danger';
                }
                $total_venta    = $row['monto_credito'];
                $saldo          = $row['saldo_credito'];
                // Cálculo correcto de abonos
                $total_abonos   = $total_venta - $saldo;
                if ($total_abonos < 0) $total_abonos = 0; // Por seguridad
                $simbolo_moneda = get_row('perfil', 'moneda', 'id_perfil', 1);
                ?>
                <tr>
                    <td><label class='badge badge-purple'><?php echo $numero_factura; ?></label></td>
                    <td><?php echo $fecha; ?></td>
                    <td><?php echo $nombre_cliente; ?></td>
                    <td><span class="badge <?php echo $label_class; ?>"><?php echo $text_estado; ?></span></td>
                    <td class='text-right'><b><?php echo $simbolo_moneda . ' ' . number_format($total_venta, 2); ?></b></td>
                    <td class='text-right'><b><?php echo $simbolo_moneda . ' ' . number_format($saldo, 2); ?></b></td>
                    <td class='text-right'><b><?php echo $simbolo_moneda . ' ' . number_format($total_abonos, 2); ?></b></td>
                    <td class="text-center">
                        <div class="btn-group dropdown">
                            <button type="button" class="btn btn-warning btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                <i class='fa fa-cog'></i> <i class="caret"></i>
                            </button>
                            <div class="dropdown-menu dropdown-menu-right">
                               <?php if ($permisos_editar == 1) { ?>
                               <a class="dropdown-item" href="abonos_cxc.php?numero_factura=<?php echo $numero_factura; ?>">
                                   <i class='fa fa-search'></i> Ver Abonos
                               </a>
                               <?php } ?>
                               <?php if ($permisos_eliminar == 1) { ?>
                               <!-- <a class="dropdown-item" href="#" data-toggle="modal" data-target="#dataDelete" data-id="<?php echo $row['id_factura']; ?>"><i class='fa fa-trash'></i> Eliminar</a> -->
                               <?php } ?>
                           </div>
                       </div>
                   </td>
               </tr>
               <?php
            }
            ?>
           </tbody>
           <tfoot>
              <tr>
                  <td colspan="8">
                      <span class="pull-right"><?php echo paginate($reload, $page, $total_pages, $adjacents); ?></span>
                  </td>
              </tr>
           </tfoot>
        </table>
    </div>
    <?php
    } else {
        ?>
        <div class="alert alert-warning" role="alert" align="center">
            <strong>Aviso!</strong> No hay Registro de Créditos
        </div>
        <?php
    }
}
?>