34849-vm/recaudo_esperado.php
2026-02-03 02:29:54 +00:00

247 lines
10 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 ---
$fecha_inicio_str = $_POST['fecha_inicio'] ?? '';
$fecha_fin_str = $_POST['fecha_fin'] ?? '';
$params = [];
$date_where_clause = "";
if (!empty($fecha_inicio_str) && !empty($fecha_fin_str)) {
$date_where_clause = " WHERE p.fecha_pedido BETWEEN ? AND ?";
$params[] = $fecha_inicio_str;
$params[] = $fecha_fin_str;
}
// --- 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
{$date_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_vendidos = [];
$ventas_por_asesor = [];
try {
$sql_productos_base = "SELECT
p.cantidad as cantidades_pedido,
p.producto_id as productos_pedido_ids,
pr.id as producto_id,
pr.nombre as producto_nombre,
pr.precio as producto_precio,
u.nombre_asesor
FROM
pedidos p
JOIN
productos pr ON FIND_IN_SET(pr.id, REPLACE(p.producto_id, ' ', ''))
LEFT JOIN
users u ON p.asesor_id = u.id
{$date_where_clause}";
$stmt_productos = $pdo->prepare($sql_productos_base);
$stmt_productos->execute($params);
$result_productos = $stmt_productos->fetchAll(PDO::FETCH_ASSOC);
if ($result_productos) {
foreach ($result_productos as $row) {
$todos_productos_ids = explode(',', $row['productos_pedido_ids']);
$todas_cantidades = explode(',', $row['cantidades_pedido']);
$product_index = array_search($row['producto_id'], $todos_productos_ids);
if ($product_index !== false && isset($todas_cantidades[$product_index])) {
$cantidad_producto = (int)trim($todas_cantidades[$product_index]);
$producto_nombre = $row['producto_nombre'];
$asesor_nombre = $row['nombre_asesor'] ?? 'Sin Asesor';
$monto_producto = $cantidad_producto * (float)$row['producto_precio'];
// Acumular para "Resumen General de Productos Vendidos"
if (!isset($productos_vendidos[$producto_nombre])) {
$productos_vendidos[$producto_nombre] = ['unidades' => 0, 'monto' => 0];
}
$productos_vendidos[$producto_nombre]['unidades'] += $cantidad_producto;
$productos_vendidos[$producto_nombre]['monto'] += $monto_producto;
// Acumular para "Desglose de Ventas por Asesor"
if (!isset($ventas_por_asesor[$asesor_nombre])) {
$ventas_por_asesor[$asesor_nombre] = [];
}
if (!isset($ventas_por_asesor[$asesor_nombre][$producto_nombre])) {
$ventas_por_asesor[$asesor_nombre][$producto_nombre] = ['unidades' => 0, 'monto' => 0];
}
$ventas_por_asesor[$asesor_nombre][$producto_nombre]['unidades'] += $cantidad_producto;
$ventas_por_asesor[$asesor_nombre][$producto_nombre]['monto'] += $monto_producto;
}
}
}
} catch (PDOException $e) {
error_log("Error en RESUMEN DE PRODUCTOS: " . $e->getMessage());
}
include 'layout_header.php';
?>
<div class="container mt-4">
<h1 class="mb-4">Recaudo Esperado</h1>
<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_str && $fecha_fin_str): ?>
<div class="alert alert-info">
Mostrando resultados para el período desde <strong><?= htmlspecialchars($fecha_inicio_str) ?></strong> hasta <strong><?= htmlspecialchars($fecha_fin_str) ?></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_vendidos)): ?>
<tr>
<td colspan="3" class="text-center">No hay datos disponibles.</td>
</tr>
<?php else: ?>
<?php foreach ($productos_vendidos as $producto_nombre => $datos): ?>
<tr>
<td><?= htmlspecialchars($producto_nombre) ?></td>
<td><?= $datos['unidades'] ?> 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($ventas_por_asesor)): ?>
<p class="text-center">No hay datos de ventas para mostrar.</p>
<?php else: ?>
<?php foreach ($ventas_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>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['unidades'] ?> 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'; ?>