<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once ("../config/db.php");
require_once ("../config/conexion.php");
session_start();

$reporte_tienda = isset($_POST['reporte_tienda']) ? mysqli_real_escape_string($con, $_POST['reporte_tienda']) : '';
$desde = isset($_POST['desde']) ? mysqli_real_escape_string($con, $_POST['desde']) : '';
$hasta = isset($_POST['hasta']) ? mysqli_real_escape_string($con, $_POST['hasta']) : '';
$donacion = "Donacion";
$id_tienda = "";

if (!empty($reporte_tienda)) {
    $query_t = mysqli_query($con, "SELECT id_tienda FROM tiendas WHERE nombre = '$reporte_tienda'");
    if ($row_t = mysqli_fetch_array($query_t)) {
        $id_tienda = $row_t['id_tienda'];
    }
} else {
    if (!empty($_SESSION['estado'])) {
        $id_tienda = $_SESSION['estado'];
    }
}

$sWhere = " WHERE condiciones != '$donacion'";
if (!empty($id_tienda)) {
    $sWhere .= " AND almacen = '$id_tienda'";
}

if (!empty($desde) && !empty($hasta)) {
    $sWhere .= " AND fecha_factura BETWEEN '$desde' AND '$hasta'";
} elseif (!empty($desde)) {
    $sWhere .= " AND fecha_factura = '$desde'";
} elseif (!empty($hasta)) {
    $sWhere .= " AND fecha_factura = '$hasta'";
}

$sOrder = " ORDER BY fecha_factura DESC";
$reload = './reportes.php';

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

$count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM facturas $sWhere");
$row = mysqli_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows / $per_page);

$sql_total = "SELECT * FROM facturas $sWhere";
$query_total = mysqli_query($con, $sql_total);

$t_total = 0;
$t_exento = 0; // siempre 0 en ventas gravadas
$t_base = 0;
$t_iva = 0;
$t_credito = 0;
$tasa_actual = 1;

$query_tasa = mysqli_query($con, "SELECT tasa FROM tasa WHERE id_tasa='1'");
if ($dato_tasa = mysqli_fetch_array($query_tasa)) {
    $tasa_actual = ($dato_tasa['tasa'] > 0) ? $dato_tasa['tasa'] : 1;
}

while ($r = mysqli_fetch_array($query_total)) {
    $total_v = floatval($r['total_venta']);
    $base = $total_v / (1 + (TAX / 100));
    $iva = $total_v - $base;
    $pagado_usd = floatval($r['condiciones_efed']) + ((floatval($r['condiciones_efe']) + floatval($r['condiciones_tra']) + floatval($r['condiciones_pun'])) / $tasa_actual);
    $credito = $total_v - $pagado_usd;
    if ($credito < 0) { $credito = 0; }

    $t_total += $total_v;
    $t_base += $base;
    $t_iva += $iva;
    $t_credito += $credito;
}

$sql = "SELECT f.*, c.nombre_cliente, c.rif_cliente FROM facturas f LEFT JOIN clientes c ON f.id_cliente = c.id_cliente $sWhere $sOrder LIMIT $offset, $per_page";
$query = mysqli_query($con, $sql);
?>

<div class="table-responsive">
    <table class="table table-bordered" style="font-size:11px;">
        <tr class="warning" style="font-size:11px; font-weight:bold;">
            <th>Monto Factura con IVA</th>
            <th>Exentas</th>
            <th>Base Imponible</th>
            <th>% IVA</th>
            <th>Débito Fiscal</th>
        </tr>
        <tr>
            <td>$ <?php echo number_format($t_total, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($t_total * $tasa_actual, 2, ',', '.'); ?></small></td>
            <td>$ 0,00<br><small class="text-muted">Bs 0,00</small></td>
            <td>$ <?php echo number_format($t_base, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($t_base * $tasa_actual, 2, ',', '.'); ?></small></td>
            <td><?php echo TAX; ?>%</td>
            <td>$ <?php echo number_format($t_iva, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($t_iva * $tasa_actual, 2, ',', '.'); ?></small></td>
        </tr>
    </table>
</div>

<div class="text-right" style="margin-bottom:10px;">
    <a href="imp_libro_ventas.php?desde=<?php echo $desde;?>&hasta=<?php echo $hasta;?>&tienda=<?php echo $id_tienda;?>" target="_blank" class="btn btn-danger">
        <span class="glyphicon glyphicon-print"></span> Descargar PDF
    </a>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover table-condensed" style="font-size:11px;">
        <thead>
            <tr class="info">
                <th>#</th>
                <th>Fecha</th>
                <th>RIF</th>
                <th>Cliente</th>
                <th>Factura</th>
                <th>Total c/IVA</th>
                <th>Exentas</th>
                <th>Base</th>
                <th>%</th>
                <th>IVA</th>
                <th>Estado</th>
            </tr>
        </thead>
        <tbody>
            <?php
            if ($numrows > 0) {
                $j = $offset + 1;
                while ($row = mysqli_fetch_array($query)) {
                    $total_v = floatval($row['total_venta']);
                    $base = $total_v / (1 + (TAX / 100));
                    $iva = $total_v - $base;
                    $pagado_usd = floatval($row['condiciones_efed']) + ((floatval($row['condiciones_efe']) + floatval($row['condiciones_tra']) + floatval($row['condiciones_pun'])) / $tasa_actual);
                    $credito_f = $total_v - $pagado_usd;
                    if ($credito_f < 0) { $credito_f = 0; }

                    if ($credito_f <= 0) { $text_estado = "Pagada"; $label_class = 'label-success'; }
                    else { $text_estado = "Por Cobrar"; $label_class = 'label-warning'; }
                    ?>
                    <tr>
                        <td><?php echo $j++; ?></td>
                        <td><?php echo date('d/m/Y', strtotime($row['fecha_factura'])); ?></td>
                        <td><?php echo $row['rif_cliente']; ?></td>
                        <td><?php echo $row['nombre_cliente']; ?></td>
                        <td><?php echo $row['numero_factura']; ?></td>
                        <td>$ <?php echo number_format($total_v, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($total_v * $tasa_actual, 2, ',', '.'); ?></small></td>
                        <td>$ 0,00<br><small class="text-muted">Bs 0,00</small></td>
                        <td>$ <?php echo number_format($base, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($base * $tasa_actual, 2, ',', '.'); ?></small></td>
                        <td><?php echo TAX; ?>%</td>
                        <td>$ <?php echo number_format($iva, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($iva * $tasa_actual, 2, ',', '.'); ?></small></td>
                        <td><span class="label <?php echo $label_class;?>"><?php echo $text_estado; ?></span></td>
                    </tr>
                <?php }
            } else {
                echo '<tr><td colspan="11" class="text-center">No se encontraron registros para los filtros seleccionados.</td></tr>';
            }
            ?>
        </tbody>
        <?php if ($numrows > 0) { ?>
        <tfoot>
            <tr class="info" style="font-weight:bold;">
                <td colspan="5" class="text-right">TOTALES</td>
                <td>$ <?php echo number_format($t_total, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($t_total * $tasa_actual, 2, ',', '.'); ?></small></td>
                <td>$ 0,00</td>
                <td>$ <?php echo number_format($t_base, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($t_base * $tasa_actual, 2, ',', '.'); ?></small></td>
                <td></td>
                <td>$ <?php echo number_format($t_iva, 2, ',', '.'); ?><br><small class="text-muted">Bs <?php echo number_format($t_iva * $tasa_actual, 2, ',', '.'); ?></small></td>
                <td>Deuda total: $<?php echo number_format($t_credito, 2, ',', '.'); ?></td>
            </tr>
        </tfoot>
        <?php } ?>
    </table>
    <div class="text-center">
        <?php echo paginate($reload, $page, $total_pages, $adjacents); ?>
    </div>
</div>
