<?php 
require_once ("config/db.php");
require_once ("config/conexion.php");
session_start();

// 1. Obtener Tasa Actual
$con_tasa = mysqli_query($con, "SELECT tasa FROM tasa WHERE id_tasa='1'");
$dato_tasa = mysqli_fetch_array($con_tasa);
$tasa_actual = $dato_tasa['tasa'];

// 2. Variables de entrada
$reporte_tienda = $_POST['reporte_tienda'];
$desde = $_POST['desde'];
$hasta = $_POST['hasta'];

// 3. Construir Filtros SQL dinámicos
$sWhere = " WHERE 1=1 "; 

if (!empty($reporte_tienda)) {
    $sql_t = mysqli_query($con, "SELECT id_tienda FROM tiendas WHERE nombre = '$reporte_tienda'");
    if($r_t = mysqli_fetch_array($sql_t)) {
        $id_tienda_f = $r_t['id_tienda'];
        $sWhere .= " AND almacen = '$id_tienda_f'";
    }
}

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'";
}

// --- 4. CÁLCULO DEL TOTAL GLOBAL (Independiente de la paginación) ---
// Esta consulta suma TODO el periodo filtrado sin importar el LIMIT de la tabla
$sql_global = "SELECT SUM(total_venta) as total_general, COUNT(*) as total_ops FROM facturas $sWhere";
$res_global = mysqli_query($con, $sql_global);
$row_global = mysqli_fetch_array($res_global);

$gran_total_usd = $row_global['total_general'];
$gran_total_ops = $row_global['total_ops'];
$gran_total_bsd = $gran_total_usd * $tasa_actual;

// 5. Paginación
include 'pagination.php';
$count_query = mysqli_query($con, "SELECT COUNT(DISTINCT almacen) AS numrows FROM facturas $sWhere");
$row_c = mysqli_fetch_array($count_query);
$numrows = $row_c['numrows'];

$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
$per_page = 30; 
$adjacents = 4;
$offset = ($page - 1) * $per_page;
$total_pages = ceil($numrows / $per_page);
$reload = './reportes.php';

// 6. Consulta Ranking (Para la tabla con LIMIT)
$sql = "SELECT almacen, COUNT(*) as operaciones, SUM(total_venta) as total_ventas 
        FROM facturas 
        $sWhere 
        GROUP BY almacen 
        ORDER BY total_ventas DESC 
        LIMIT $offset, $per_page";

$query = mysqli_query($con, $sql);
?>

<div class="row" style="margin-bottom: 20px;">
    <div class="col-md-12">
        <div style="background: #fff; border-radius: 8px; border: 1px solid #e0e0e0; padding: 20px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; border-left: 5px solid #31708f;">
            <div>
                <p style="color: #888; font-size: 11px; text-transform: uppercase; margin-bottom: 5px; letter-spacing: 1px; font-weight: bold;">Ventas Totales del Periodo</p>
                <h2 style="margin: 0; color: #2c3e50; font-weight: bold;">
                    $<?php echo number_format($gran_total_usd, 2, ",", "."); ?>
                </h2>
                <span class="text-success" style="font-weight: bold; font-size: 1.2em;">
                    <i class="glyphicon glyphicon-transfer"></i> <?php echo number_format($gran_total_bsd, 2, ",", "."); ?> BsD
                </span>
            </div>
            <div style="text-align: right;">
                <p style="color: #888; font-size: 11px; text-transform: uppercase; margin-bottom: 5px; font-weight: bold;">Operaciones Totales</p>
                <h3 style="margin: 0; color: #31708f;"><?php echo number_format($gran_total_ops, 0); ?> <small>Tickets</small></h3>
            </div>
        </div>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-hover table-striped" style="background: white;">
        <thead>
            <tr class="info">
                <th style="width: 50px;">#</th>
                <th>Tienda / Sucursal</th>
                <th class="text-center">Operaciones</th> 
                <th class="text-right">Monto Total</th>
            </tr>
        </thead>
        <tbody>
        <?php 
        if ($numrows > 0) {
            $item = $offset + 1;
            while ($dato = mysqli_fetch_array($query)) {
                $almacen_id = $dato['almacen'];
                $can = $dato['operaciones'];
                $mon_tot = $dato['total_ventas'];

                $sql_n = mysqli_query($con, "SELECT nombre FROM tiendas WHERE id_tienda='$almacen_id'");
                $r_n = mysqli_fetch_array($sql_n);
                $nombre_tienda = (isset($r_n['nombre'])) ? $r_n['nombre'] : "ID: $almacen_id";

                // Porcentaje visual de cuánto aporta esta tienda al total
                $porcentaje = ($gran_total_usd > 0) ? ($mon_tot / $gran_total_usd) * 100 : 0;
        ?>
            <tr style="vertical-align: middle;">
                <td><span class="badge" style="background: #31708f;"><?php echo $item++; ?></span></td>
                <td>
                    <strong style="font-size: 1.1em;"><?php echo $nombre_tienda; ?></strong><br>
                    <div class="progress" style="height: 4px; margin: 4px 0 0 0; width: 100px; background-color: #eee;">
                      <div class="progress-bar progress-bar-info" role="progressbar" style="width: <?php echo $porcentaje; ?>%"></div>
                    </div>
                </td>
                <td class="text-center">
                    <span class="label label-info" style="font-size: 11px;"><?php echo $can; ?> facturas</span>
                </td>
                <td class="text-right">
                    <strong style="font-size: 1.1em;">$<?php echo number_format($mon_tot, 2, ",", "."); ?></strong><br>
                    <small class="text-muted"><?php echo number_format($mon_tot * $tasa_actual, 2, ",", "."); ?> BsD</small>
                </td>
            </tr>
        <?php 
            } 
        } else { ?>
            <tr><td colspan="4" class="text-center">No se encontraron resultados para los filtros aplicados.</td></tr>
        <?php } ?>
        </tbody>
    </table>
</div>

<div class="text-center">
    <?php echo paginate($reload, $page, $total_pages, $adjacents); ?>
</div>