<?php
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']) : '';
$q = isset($_POST['q']) ? mysqli_real_escape_string($con, $_POST['q']) : '';

// Si no es gerencia, limitar a la tienda del usuario
if ($_SESSION['rol'] != "gerencia") {
    $reporte_tienda = $_SESSION['estado'];
}

$sWhere = " WHERE 1=1 ";

if (!empty($reporte_tienda)) {
    $sWhere .= " AND u.estado = '$reporte_tienda'";
}

if (!empty($q)) {
    if (ctype_digit($q)) {
        $sWhere .= " AND (u.user_id = '$q' OR CONCAT(u.firstname, ' ', u.lastname) LIKE '%$q%' OR u.firstname LIKE '%$q%' OR u.lastname LIKE '%$q%' OR u.user_name LIKE '%$q%')";
    } else {
        $sWhere .= " AND (CONCAT(u.firstname, ' ', u.lastname) LIKE '%$q%' OR u.firstname LIKE '%$q%' OR u.lastname LIKE '%$q%' OR u.user_name LIKE '%$q%')";
    }
}

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

// Cálculo totals
$sql_global = "SELECT COUNT(DISTINCT u.user_id) as total_vendedores, SUM(f.total_venta) as total_ventas
               FROM facturas f
               JOIN users u ON f.id_vendedor = u.user_id
               $sWhere";
$result_global = mysqli_query($con, $sql_global);
$row_global = mysqli_fetch_array($result_global);
$total_vendedores = intval($row_global['total_vendedores']);
$gran_total_ventas = floatval($row_global['total_ventas']);

// Paginación
include 'pagination.php';
$count_query = mysqli_query($con, "SELECT COUNT(DISTINCT u.user_id) AS numrows
                                   FROM facturas f
                                   JOIN users u ON f.id_vendedor = u.user_id
                                   $sWhere");
$row_c = mysqli_fetch_array($count_query);
$numrows = intval($row_c['numrows']);
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? intval($_REQUEST['page']) : 1;
$per_page = 30;
$adjacents = 4;
$offset = ($page - 1) * $per_page;
$total_pages = ($numrows > 0) ? ceil($numrows / $per_page) : 1;

// Consulta principal con agrupación y ordenamiento
$sql = "SELECT u.user_id,
               CONCAT(u.firstname, ' ', u.lastname) AS nombre_vendedor,
               u.estado AS tienda_vendedor,
               COUNT(f.id_factura) AS cantidad_ventas,
               SUM(f.total_venta) AS acumulado_ventas
        FROM facturas f
        JOIN users u ON f.id_vendedor = u.user_id
        $sWhere
        GROUP BY u.user_id, u.firstname, u.lastname, u.estado
        ORDER BY acumulado_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;">Total General de Ventas</p>
                <h2 style="margin: 0; color: #2c3e50; font-weight: bold;">
                    $<?php echo number_format($gran_total_ventas, 2, ",", "."); ?>
                </h2>
            </div>
            <div style="text-align: right;">
                <p style="color: #888; font-size: 11px; text-transform: uppercase; margin-bottom: 5px; font-weight: bold;">Vendedores en el reporte</p>
                <h3 style="margin: 0; color: #31708f;"><?php echo number_format($total_vendedores, 0); ?> <small>vendedores</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>ID Vendedor</th>
                <th>Nombre</th>
                <th>Tienda</th>
                <th class="text-center"># Ventas</th>
                <th class="text-right">Total Ventas</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($numrows > 0) {
                $item = $offset + 1;
                while ($row = mysqli_fetch_array($query)) {
            ?>
                <tr>
                    <td><span class="badge" style="background: #31708f;"><?php echo $item++; ?></span></td>
                    <td><?php echo $row['user_id']; ?></td>
                    <td><?php echo $row['nombre_vendedor']; ?></td>
                    <?php
                    $tienda_nombre = 'Sin tienda';
                    if (!empty($row['tienda_vendedor'])) {
                        $sql_t = mysqli_query($con, "SELECT nombre FROM tiendas WHERE id_tienda = '" . $row['tienda_vendedor'] . "'");
                        if ($r_t = mysqli_fetch_array($sql_t)) {
                            $tienda_nombre = $r_t['nombre'];
                        }
                    }
        ?>
        <td><?php echo $tienda_nombre; ?></td>
                    <td class="text-center"><?php echo number_format($row['cantidad_ventas'], 0); ?></td>
                    <td class="text-right"><strong>$<?php echo number_format($row['acumulado_ventas'], 2, ",", "."); ?></strong></td>
                </tr>
            <?php }
            } else { ?>
                <tr><td colspan="6" class="text-center">No se encontraron resultados para los filtros aplicados.</td></tr>
            <?php } ?>
        </tbody>
    </table>
</div>

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