34849-vm/recaudo_esperado.php
2026-02-03 01:43:03 +00:00

279 lines
11 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'Administrador') {
header('Location: pedidos.php');
exit;
}
$pdo = db();
// --- DATE FILTER (from finanzas.php) ---
$fecha_inicio_str = $_POST['fecha_inicio'] ?? '';
$fecha_fin_str = $_POST['fecha_fin'] ?? '';
$fecha_inicio_obj = null;
if (!empty($fecha_inicio_str)) {
$fecha_inicio_obj = DateTime::createFromFormat('Y-m-d', $fecha_inicio_str);
}
$fecha_fin_obj = null;
if (!empty($fecha_fin_str)) {
$fecha_fin_obj = DateTime::createFromFormat('Y-m-d', $fecha_fin_str);
}
$where_clause = '';
$params = [];
if ($fecha_inicio_obj && $fecha_fin_obj) {
$where_clause = ' WHERE p.created_at BETWEEN ? AND ?';
$params[] = $fecha_inicio_obj->format('Y-m-d 00:00:00');
$params[] = $fecha_fin_obj->format('Y-m-d 23:59:59');
}
// --- RECAUDO ESPERADO POR ASESORA ---
$asesoras_recuado = [];
try {
$sql_asesoras = "
SELECT
u.nombre_asesor AS asesora_nombre,
SUM(p.monto_total) AS monto_total,
COUNT(p.id) AS cantidad_pedidos
FROM users u
JOIN pedidos p ON u.id = p.asesor_id
{$where_clause}
GROUP BY u.id, u.nombre_asesor
ORDER BY monto_total DESC
";
$stmt_asesoras = $pdo->prepare($sql_asesoras);
$stmt_asesoras->execute($params);
$asesoras_recuado = $stmt_asesoras->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log("Error en RECAUDO POR ASESORA: " . $e->getMessage());
}
// --- RESUMEN GENERAL Y POR ASESOR ---
$productos_resumen = [];
$resumen_por_asesor = [];
try {
// Consulta para obtener el resumen de productos vendidos
$sql_resumen = "
SELECT
p.producto,
p.cantidad,
p.monto_total,
COALESCE(u.nombre_asesor, u.username, 'Sin Asesor') AS asesor_nombre
FROM pedidos p
LEFT JOIN users u ON p.asesor_id = u.id
{$where_clause}
";
$stmt_resumen = $pdo->prepare($sql_resumen);
$stmt_resumen->execute($params);
$pedidos_resumen = $stmt_resumen->fetchAll(PDO::FETCH_ASSOC);
$temp_resumen = [];
$temp_asesor = [];
foreach ($pedidos_resumen as $pedido) {
$asesor = $pedido['asesor_nombre'];
$productos_pedido = explode(',', $pedido['producto']);
$cantidades_pedido = explode(',', $pedido['cantidad']);
// Solo si el pedido tiene un único producto, asignamos el monto total.
$monto_a_distribuir = (count($productos_pedido) == 1) ? $pedido['monto_total'] : 0;
foreach ($productos_pedido as $index => $nombre_prod) {
$nombre_prod = trim($nombre_prod);
if (empty($nombre_prod)) continue;
$cantidad = isset($cantidades_pedido[$index]) ? (int)trim($cantidades_pedido[$index]) : 0;
// Resumen general
if (!isset($temp_resumen[$nombre_prod])) {
$temp_resumen[$nombre_prod] = ['cantidad' => 0, 'monto' => 0, 'num_pedidos' => 0];
}
$temp_resumen[$nombre_prod]['cantidad'] += $cantidad;
$temp_resumen[$nombre_prod]['monto'] += $monto_a_distribuir;
$temp_resumen[$nombre_prod]['num_pedidos']++;
// Desglose por asesor
if (!isset($temp_asesor[$asesor][$nombre_prod])) {
$temp_asesor[$asesor][$nombre_prod] = ['cantidad' => 0, 'monto' => 0, 'num_pedidos' => 0];
}
$temp_asesor[$asesor][$nombre_prod]['cantidad'] += $cantidad;
$temp_asesor[$asesor][$nombre_prod]['monto'] += $monto_a_distribuir;
$temp_asesor[$asesor][$nombre_prod]['num_pedidos']++;
}
}
// Ordenar resultados
uasort($temp_resumen, function($a, $b) { return $b['cantidad'] <=> $a['cantidad']; });
foreach ($temp_asesor as &$prods) {
uasort($prods, function($a, $b) { return $b['cantidad'] <=> $a['cantidad']; });
}
unset($prods);
$productos_resumen = $temp_resumen;
$resumen_por_asesor = $temp_asesor;
} catch (PDOException $e) {
error_log("Error en RESUMEN GENERAL DE PRODUCTOS: " . $e->getMessage());
// Dejar las variables vacías para que la UI muestre "No hay datos"
$productos_resumen = [];
$resumen_por_asesor = [];
}
include 'layout_header.php';
?>
<div class="container mt-4">
<h1 class="mb-4">Recaudo Esperado</h1>
<!-- Date Filter Form (from finanzas.php) -->
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title">Filtrar por Fecha</h5>
<form method="POST" action="recaudo_esperado.php" class="row g-3">
<div class="col-md-5">
<label for="fecha_inicio" class="form-label">Fecha de Inicio</label>
<input type="date" class="form-control" id="fecha_inicio" name="fecha_inicio" value="<?= htmlspecialchars($fecha_inicio_str) ?>">
</div>
<div class="col-md-5">
<label for="fecha_fin" class="form-label">Fecha de Fin</label>
<input type="date" class="form-control" id="fecha_fin" name="fecha_fin" value="<?= htmlspecialchars($fecha_fin_str) ?>">
</div>
<div class="col-md-2 d-flex align-items-end">
<button type="submit" class="btn btn-primary w-100">Filtrar</button>
<a href="recaudo_esperado.php" class="btn btn-secondary w-100 ms-2">Limpiar</a>
</div>
</form>
</div>
</div>
<?php if ($fecha_inicio_obj && $fecha_fin_obj): ?>
<div class="alert alert-info">
Mostrando resultados para el período desde <strong><?= htmlspecialchars($fecha_inicio_obj->format('d/m/Y')) ?></strong> hasta <strong><?= htmlspecialchars($fecha_fin_obj->format('d/m/Y')) ?></strong>.
</div>
<?php endif; ?>
<!-- Recaudo por Asesora -->
<div class="card mb-4">
<div class="card-header">
<h2>Recaudo Esperado por Asesora</h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Asesora</th>
<th>Cantidad de Pedidos</th>
<th>Monto Total Esperado</th>
</tr>
</thead>
<tbody>
<?php if (empty($asesoras_recuado)): ?>
<tr>
<td colspan="3" class="text-center">No hay datos disponibles.</td>
</tr>
<?php else: ?>
<?php foreach ($asesoras_recuado as $recuado): ?>
<tr>
<td><?= htmlspecialchars($recuado['asesora_nombre']) ?></td>
<td><?= htmlspecialchars($recuado['cantidad_pedidos']) ?></td>
<td>S/ <?= number_format($recuado['monto_total'], 2) ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Resumen General de Productos -->
<div class="card">
<div class="card-header">
<h2>Resumen General de Productos Vendidos</h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Producto</th>
<th>Unidades Vendidas</th>
<th>Monto Total</th>
</tr>
</thead>
<tbody>
<?php if (empty($productos_resumen)): ?>
<tr>
<td colspan="3" class="text-center">No hay datos disponibles.</td>
</tr>
<?php else: ?>
<?php foreach ($productos_resumen as $producto_nombre => $datos): ?>
<tr>
<td><?= htmlspecialchars($producto_nombre) ?></td>
<td><?= $datos['cantidad'] ?> unidades</td>
<td>S/ <?= number_format($datos['monto'], 2) ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Desglose de Ventas por Asesor -->
<div class="card mt-4">
<div class="card-header">
<h2>Desglose de Ventas por Asesor</h2>
</div>
<div class="card-body">
<?php if (empty($resumen_por_asesor)): ?>
<p class="text-center">No hay datos de ventas para mostrar.</p>
<?php else: ?>
<?php foreach ($resumen_por_asesor as $asesor => $productos): ?>
<h3 class="mt-4"><?= htmlspecialchars($asesor) ?></h3>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Producto</th>
<th>Cantidad de Pedidos</th>
<th>Unidades Vendidas</th>
<th>Monto Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($productos as $nombre_producto => $datos):
?>
<tr>
<td><?= htmlspecialchars($nombre_producto) ?></td>
<td><?= $datos['num_pedidos'] ?></td>
<td><?= $datos['cantidad'] ?> unidades</td>
<td>S/ <?= number_format($datos['monto'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</div>
<?php include 'layout_footer.php'; ?>