<?php
require_once '../config/config.php';
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$negocio_id = $_SESSION['negocio_id'] ?? 0;

// === Consultar resumen rápido ===

// 1. Ventas de hoy
$stmtHoy = $conn->prepare("SELECT IFNULL(SUM(total), 0) AS ventas_hoy FROM pedidos WHERE negocio_id = ? AND DATE(fecha) = CURDATE() ");
$stmtHoy->bind_param("i", $negocio_id);
$stmtHoy->execute();
$resHoy = $stmtHoy->get_result()->fetch_assoc();
$ventasHoy = $resHoy['ventas_hoy'];
$stmtHoy->close();

// 2. Ventas de esta semana
$stmtSemana = $conn->prepare("SELECT IFNULL(SUM(total), 0) AS ventas_semana FROM pedidos WHERE negocio_id = ? AND YEARWEEK(fecha, 1) = YEARWEEK(CURDATE(), 1)");
$stmtSemana->bind_param("i", $negocio_id);
$stmtSemana->execute();
$resSemana = $stmtSemana->get_result()->fetch_assoc();
$ventasSemana = $resSemana['ventas_semana'];
$stmtSemana->close();

// 3. Producto destacado
$stmtTopProd = $conn->prepare("SELECT
    pro.nombre,
    COUNT(*) AS cantidad_vendida
FROM
    pedidos AS ped
    INNER JOIN pedido_items AS itm ON ped.id = itm.pedido_id
    INNER JOIN productos AS pro ON itm.producto_id = pro.id
WHERE
    ped.fecha >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
    AND ped.negocio_id = ?
GROUP BY
    pro.nombre
ORDER BY
    cantidad_vendida DESC
LIMIT 1;");
$stmtTopProd->bind_param("i", $negocio_id);
$stmtTopProd->execute();
$resTopProd = $stmtTopProd->get_result()->fetch_assoc();
$productoTop = $resTopProd['nombre'] ?? 'N/A';
$productoCantidad = $resTopProd['cantidad_vendida'] ?? 0;
$stmtTopProd->close();

// 4. Distribución de estados para gráfico
$stmtEstados = $conn->prepare("SELECT estado, COUNT(*) AS cantidad FROM pedidos WHERE negocio_id = ? AND fecha_hora_entrega >= CURDATE() - INTERVAL 7 DAY GROUP BY estado");
$stmtEstados->bind_param("i", $negocio_id);
$stmtEstados->execute();
$resEstados = $stmtEstados->get_result();

$estadosDistribucion = [];
while ($row = $resEstados->fetch_assoc()) {
    $estadosDistribucion[] = [
        'estado' => $row['estado'],
        'cantidad' => $row['cantidad']
    ];
}
$stmtEstados->close();

// 5. Ventas de Ayer
$stmtAyer = $conn->prepare("SELECT IFNULL(SUM(total), 0) AS ventas_ayer FROM pedidos WHERE negocio_id = ? AND DATE(fecha) = CURDATE() - INTERVAL 1 DAY");
$stmtAyer->bind_param("i", $negocio_id);
$stmtAyer->execute();
$resAyer = $stmtAyer->get_result()->fetch_assoc();
$ventasAyer = $resAyer['ventas_ayer'];
$stmtAyer->close();

// 6. Ticket Promedio Hoy
$stmtTickets = $conn->prepare("SELECT IFNULL(SUM(total), 0) AS total_hoy, COUNT(*) AS pedidos_hoy FROM pedidos WHERE negocio_id = ? AND DATE(fecha) = CURDATE()");
$stmtTickets->bind_param("i", $negocio_id);
$stmtTickets->execute();
$resTickets = $stmtTickets->get_result()->fetch_assoc();
$ticketPromedio = $resTickets['pedidos_hoy'] > 0 ? $resTickets['total_hoy'] / $resTickets['pedidos_hoy'] : 0;
$stmtTickets->close();

// 7. Top 5 Productos Vendidos Este Mes
$stmtTopProductos = $conn->prepare("
    SELECT pro.nombre, COUNT(*) AS cantidad_vendida
    FROM pedidos AS ped
    INNER JOIN pedido_items AS itm ON ped.id = itm.pedido_id
    INNER JOIN productos AS pro ON itm.producto_id = pro.id
    WHERE ped.fecha >= DATE_FORMAT(CURDATE(), '%Y-%m-01') AND ped.negocio_id = ?
    GROUP BY pro.nombre
    ORDER BY cantidad_vendida DESC
    LIMIT 5
");
$stmtTopProductos->bind_param("i", $negocio_id);
$stmtTopProductos->execute();
$resTopProductos = $stmtTopProductos->get_result();

$topProductos = [];
while ($row = $resTopProductos->fetch_assoc()) {
    $topProductos[] = [
        'nombre' => $row['nombre'],
        'cantidad' => $row['cantidad_vendida']
    ];
}
$stmtTopProductos->close();
// CONSULTA RESUMEN DE PEDIDOS
$stmtResumen = $conn->prepare("
    SELECT estado, COUNT(*) AS cantidad
    FROM pedidos
    WHERE negocio_id = ?
        AND estado='pendiente'

    GROUP BY estado
");
$stmtResumen->bind_param("i", $negocio_id);
$stmtResumen->execute();
$resResumen = $stmtResumen->get_result();

$datosResumen = [
    'pendientes' => 0,
    'preparacion' => 0,
    'entregados' => 0,
    'retiro' => 0,
    'delivery' => 0
];

while ($row = $resResumen->fetch_assoc()) {
    $estado = strtolower($row['estado']);
    if ($estado == 'pendiente') {
        $datosResumen['pendientes'] = $row['cantidad'];
    }
    if ($estado == 'preparando') {
        $datosResumen['preparacion'] = $row['cantidad'];
    }
    if ($estado == 'entregado') {
        $datosResumen['entregados'] = $row['cantidad'];
    }
    if ($estado == 'retiro') {
        $datosResumen['retiro'] = $row['cantidad'];
    }
    if ($estado == 'delivery') {
        $datosResumen['delivery'] = $row['cantidad'];
    }
}
$stmtResumen->close();
?>

<!-- Tarjetas: Pedidos -->
<div class="row g-4 mb-4">
  <div class="col-6 col-md-2">
    <div class="card shadow-sm p-3 bg-light" style="cursor:pointer;" onclick="filtrarPedidos('Pendiente')">
      <h6 class="text-primary mb-1">Pendientes</h6>
      <p class="fs-4 fw-bold"><?= $datosResumen['pendientes'] ?? 0 ?></p>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card shadow-sm p-3 bg-light">
      <h6 class="text-secondary mb-1">Ticket % Hoy</h6>
      <p class="fs-4 fw-bold">$<?= number_format($ticketPromedio, 0, ',', '.') ?></p>
    </div>
  </div>
  <div class="col-6 col-md-2">
    <div class="card shadow-sm p-3 bg-light">
      <h6 class="text-success mb-1">$ Hoy</h6>
      <p class="fs-4 fw-bold">$<?= number_format($ventasHoy, 0, ',', '.') ?></p>
    </div>
  </div>
  
  <div class="col-6 col-md-2">
    <div class="card shadow-sm p-3 bg-light">
      <h6 class="text-secondary mb-1">Ventas Ayer</h6>
      <p class="fs-4 fw-bold">$<?= number_format($ventasAyer, 0, ',', '.') ?></p>
    </div>
  </div>
  <div class="col-6 col-md-4">
    <div class="card shadow-sm p-3 bg-light">
      <h6 class="text-warning mb-1">$ Semana</h6>
      <p class="fs-4 fw-bold">$<?= number_format($ventasSemana, 0, ',', '.') ?></p>
    </div>
  </div>
  

</div>
<!-- Tarjetas: Ventas Ayer y Ticket Promedio -->
<div class="row g-4 mb-4">
  
<div class="col-6 col-md-6">
    <div class="card shadow-sm p-3 bg-light">
      <h6 class="text-info mb-1">Destacado</h6>
      <p class="fs-6 mb-1"><?= $productoCantidad ?> - <?= htmlspecialchars($productoTop) ?></p>
    </div>
  </div>
</div>

<div class="row g-4">
  <div class="col-12 col-md-4">
    <div class="card shadow-sm p-4 mt-4 h-100">
      <h5 class="mb-4 text-center">Top 5 Productos del Mes</h5>
      <div class="table-responsive">
        <table class="table table-striped table-bordered text-center align-middle">
          <thead class="table-light">
            <tr>
              <th>Producto</th>
              <th>Unidades Vendidas</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($topProductos as $prod): ?>
            <tr>
              <td><?= htmlspecialchars($prod['nombre']) ?></td>
              <td><?= $prod['cantidad'] ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <div class="col-12 col-md-8">
    <div class="card shadow-sm p-4 mt-4 h-100">
      <h5 class="mb-4 text-center">Top Productos - Gráfico de Barras</h5>
      <canvas id="graficoTopProductos" style="max-height:300px;"></canvas>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const ctxTop = document.getElementById('graficoTopProductos').getContext('2d');

  const dataTopProductos = {
    labels: <?= json_encode(array_column($topProductos, 'nombre')) ?>,
    datasets: [{
      label: 'Unidades Vendidas',
      data: <?= json_encode(array_column($topProductos, 'cantidad')) ?>,
      backgroundColor: '#007bff'
    }]
  };

  new Chart(ctxTop, {
    type: 'bar',
    data: dataTopProductos,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true
        }
      },
      plugins: {
        legend: {
          display: false
        }
      }
    }
  });
});
</script>

<!-- Script para filtros -->
<script>
function filtrarPedidos(filtro) {
    window.location.href = 'panel.php?view=pedidos&filtro=' + encodeURIComponent(filtro);
}
</script>

<!-- Chart.js para gráfico -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const ctx = document.getElementById('graficoEstados').getContext('2d');

  const dataEstados = {
    labels: <?= json_encode(array_column($estadosDistribucion, 'estado')) ?>,
    datasets: [{
      label: 'Pedidos',
      data: <?= json_encode(array_column($estadosDistribucion, 'cantidad')) ?>,
      backgroundColor: [
        '#007bff', '#ffc107', '#28a745', '#dc3545', '#6c757d', '#17a2b8', '#6610f2'
      ],
      borderWidth: 1
    }]
  };

  new Chart(ctx, {
    type: 'pie',
    data: dataEstados,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom'
        }
      }
    }
  });
});
</script>