<?php
require __DIR__ . '/init.php';
@ini_set('display_errors', '0');
@ini_set('log_errors', '1');
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['user_id'])) {
    header('Location: ' . site('admin_login.php'));
    exit;
}

if (!function_exists('esc')) {
    function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

$apiUrl = site('api.php');
$pumpSvg = site('assets/pump.svg');
$imagenFolder = site('imagen/');

// ✅ OBTENER NOMBRE DEL USUARIO CON FALLBACKS MEJORADO
$pdo = pdo();
$loggedUser = 'Usuario';
$fullName = 'Usuario';

try {
    $user_id = $_SESSION['user_id'] ?? 0;
    
    if ($user_id > 0) {
        // Detectar columnas disponibles
        $fullNameCol = null;
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='users' AND COLUMN_NAME=?");
        $stmt->execute(['full_name']);
        if ((int)$stmt->fetchColumn() > 0) {
            $fullNameCol = 'full_name';
        }
        
        // Construir query dinámicamente
        $cols = ['id', 'username'];
        if ($fullNameCol) $cols[] = $fullNameCol;
        
        $sql = "SELECT " . implode(', ', $cols) . " FROM users WHERE id = ? LIMIT 1";
        $userStmt = $pdo->prepare($sql);
        $userStmt->execute([$user_id]);
        $userData = $userStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($userData) {
            $loggedUser = $userData['username'] ?? 'Usuario';
            if ($fullNameCol && !empty($userData[$fullNameCol])) {
                $fullName = $userData[$fullNameCol];
            } else {
                $fullName = $loggedUser;
            }
        }
    }
    
    // Fallback a sesión
    if ($fullName === 'Usuario' && !empty($_SESSION['username'])) {
        $loggedUser = $_SESSION['username'];
        $fullName = $_SESSION['full_name'] ?? $loggedUser;
    }
    
} catch (Exception $e) {
    error_log("Error obteniendo datos del usuario: " . $e->getMessage());
    $loggedUser = $_SESSION['username'] ?? 'Usuario';
    $fullName = $_SESSION['full_name'] ?? $loggedUser;
}

// ✅ OBTENER COLORES DE PRODUCTOS PARA LOS TANQUES
$productColors = [];
try {
    $stmt = $pdo->query("SELECT id, name, bg_color FROM products");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $productColors[$row['id']] = [
            'name' => $row['name'],
            'color' => $row['bg_color'] ?? ''
        ];
    }
} catch (Exception $e) {
    error_log("Error obteniendo colores de productos: " . $e->getMessage());
}

// ✅ OBTENER INFO DE LA ESTACIÓN DESDE TABLA STATIONS
$stationName = 'SolutionPOS';
try {
    $stationStmt = $pdo->query("SELECT name, nombre FROM stations LIMIT 1");
    $stationData = $stationStmt->fetch(PDO::FETCH_ASSOC);
    if ($stationData) {
        $stationName = $stationData['name'] ?? $stationData['nombre'] ?? 'SolutionPOS';
    }
} catch (Exception $e) {
    error_log("Error obteniendo datos de estación: " . $e->getMessage());
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= esc($stationName) ?> - Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<link rel="stylesheet" href="<?= esc(site('assets/style.css')) ?>">
<link rel="stylesheet" href="<?= esc(site('assets/css/pump_styles.css')) ?>">
<style>
/* ========================================
   DISEÑO MODERNO Y PROFESIONAL
======================================== */

:root {
  --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  --success-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  --danger-gradient: linear-gradient(135deg, #ee0979 0%, #ff6a00 100%);
  --warning-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  --info-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  --card-shadow: 0 10px 30px rgba(0,0,0,0.1);
  --card-shadow-hover: 0 15px 40px rgba(0,0,0,0.15);
}

body {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* ========== NAVBAR MEJORADO ========== */
.navbar {
  background: white !important;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
  padding: 15px 0;
  border-bottom: 3px solid #667eea;
}

.navbar-brand {
  font-size: 20px;
  font-weight: 700;
  background: var(--primary-gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.navbar-brand i {
  font-size: 24px;
}

/* ✅ TEXTO DEL USUARIO SIN ÓVALO - SOLO TEXTO NEGRO */
.user-text {
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.user-text i {
  font-size: 16px;
  color: #667eea;
}

.nav-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.nav-actions .btn {
  border-radius: 12px;
  padding: 10px 18px;
  font-weight: 600;
  border: none;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  font-size: 14px;
}

.btn-pos {
  background: var(--success-gradient);
  color: white;
}

.btn-pos:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(17, 153, 142, 0.4);
}

.btn-admin {
  background: var(--warning-gradient);
  color: white;
}

.btn-admin:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(240, 147, 251, 0.4);
}

.btn-reports {
  background: var(--info-gradient);
  color: white;
}

.btn-reports:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4);
}

.btn-close-shift {
  background: var(--primary-gradient);
  color: white;
}

.btn-close-shift:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.btn-logout {
  background: white;
  color: #ef4444;
  border: 2px solid #ef4444;
}

.btn-logout:hover {
  background: #ef4444;
  color: white;
  transform: translateY(-2px);
}

/* ========== CONTENEDOR PRINCIPAL ========== */
.main-container {
  background: white;
  border-radius: 20px 20px 0 0;
  margin-top: 20px;
  padding: 30px;
  box-shadow: var(--card-shadow);
  min-height: calc(100vh - 100px);
}

/* ========== HEADER DEL DASHBOARD ========== */
.dashboard-header {
  background: var(--primary-gradient);
  color: white;
  padding: 15px 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.dashboard-header h2 {
  margin: 0;
  font-weight: 700;
  font-size: 22px;
}

.dashboard-header small {
  opacity: 0.9;
  font-size: 12px;
}

/* ========== TARJETAS DE PRECIOS (60% MÁS PEQUEÑAS) ========== */
.tiles-row .price-card {
  min-height: 60px;
  border-radius: 12px;
  color: white;
  padding: 12px 15px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.tiles-row .price-card::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: rgba(255,255,255,0.1);
  border-radius: 50%;
  transition: all 0.6s ease;
}

.tiles-row .price-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.tiles-row .price-card:hover::before {
  top: -60%;
  right: -60%;
}

.price-amount {
  font-size: 20px;
  font-weight: 800;
  margin-bottom: 3px;
  line-height: 1;
}

.price-name {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 5px;
  line-height: 1.1;
}

.price-sub {
  font-size: 10px;
  opacity: 0.9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* ========== GRÁFICAS ========== */
.chart-block, .chart-panel {
  background: white;
  border-radius: 20px;
  padding: 25px;
  box-shadow: var(--card-shadow);
  margin-bottom: 30px;
  transition: all 0.3s ease;
}

.chart-block:hover, .chart-panel:hover {
  box-shadow: var(--card-shadow-hover);
}

.chart-block h6 {
  font-weight: 700;
  color: #2c3e50;
  font-size: 18px;
}

.chart-panel h5 {
  font-weight: 700;
  color: #2c3e50;
  font-size: 20px;
}

/* ========== GRID DE BOMBAS (COMPACTO Y MODERNO) ========== */
.right-islands {
  background: white;
  border-radius: 20px;
  padding: 25px;
  box-shadow: var(--card-shadow);
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 120px);
  overflow-y: auto;
}

.right-islands h6 {
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 18px;
}

.pump-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  grid-auto-rows: 200px;
}

.pump-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 15px;
  border: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.pump-card:hover {
  transform: translateY(-5px) scale(1.02);
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.pump-image-wrapper {
  position: relative;
  width: 100%;
  height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.pump-image {
  width: 75px;
  height: 75px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  position: relative;
}

.pump-image img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

/* INDICADOR DE ESTADO (BOLITA) */
.pump-status-indicator {
  position: absolute;
  top: 2px;
  right: calc(50% - 42px);
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 3px solid white;
  box-shadow: 0 3px 10px rgba(0,0,0,0.3);
  z-index: 10;
  transition: all 0.3s ease;
}

.pump-status-indicator.idle {
  background: #10b981;
}

.pump-status-indicator.calling,
.pump-status-indicator.starting {
  background: #f59e0b;
  animation: pulse-indicator 1.5s ease-in-out infinite;
}

.pump-status-indicator.fuelling {
  background: #3b82f6;
  animation: pulse-indicator 1.5s ease-in-out infinite;
}

.pump-status-indicator.closed,
.pump-status-indicator.error {
  background: #ef4444;
}

@keyframes pulse-indicator {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 3px 10px rgba(0,0,0,0.3);
  }
  50% {
    transform: scale(1.15);
    box-shadow: 0 5px 14px rgba(0,0,0,0.5);
  }
}

.pump-meta {
  width: 100%;
  text-align: center;
}

.pump-name {
  font-weight: 700;
  font-size: 14px;
  margin-bottom: 5px;
  color: #2c3e50;
}

.pump-last {
  font-size: 16px;
  font-weight: 800;
  color: #10b981;
  margin-bottom: 3px;
}

.pump-datetime {
  font-size: 11px;
  color: #6b7280;
  margin-bottom: 3px;
}

.pump-status {
  font-size: 10px;
  color: #9ca3af;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  font-weight: 600;
}

/* ========== TANQUES CON COLORES DE PRODUCTOS ========== */
.tank-status-section {
  margin-bottom: 30px;
}

.tank-status-section h4 {
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 20px;
}

.tank-gauge-card {
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.15);
  padding: 25px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  color: white;
}

.tank-gauge-card::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: rgba(255,255,255,0.1);
  border-radius: 50%;
  transition: all 0.6s ease;
}

.tank-gauge-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(0,0,0,0.25);
}

.tank-gauge-card:hover::before {
  top: -60%;
  right: -60%;
}

.tank-gauge-title {
  font-weight: 700;
  font-size: 18px;
  color: white;
  margin-bottom: 8px;
  position: relative;
  z-index: 1;
}

.tank-gauge-cap {
  font-size: 14px;
  color: rgba(255,255,255,0.95);
  margin-bottom: 15px;
  position: relative;
  z-index: 1;
}

.tank-gauge-bar-wrap {
  width: 100%;
  height: 35px;
  background: rgba(255,255,255,0.3);
  border-radius: 20px;
  overflow: hidden;
  margin-bottom: 10px;
  border: 2px solid rgba(255,255,255,0.4);
  position: relative;
  z-index: 1;
}

.tank-gauge-bar {
  height: 100%;
  border-radius: 18px;
  transition: all 1.2s cubic-bezier(0.4, 0.0, 0.2, 1);
  background: rgba(255,255,255,0.9);
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.2);
}

.tank-gauge-bar.low {
  background: linear-gradient(90deg, #dc2626 0%, #ef4444 50%, #f87171 100%);
  animation: pulse-low 2s ease-in-out infinite;
}

@keyframes pulse-low {
  0%, 100% {
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.2), 0 0 10px rgba(220, 38, 38, 0.5);
  }
  50% {
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.2), 0 0 20px rgba(220, 38, 38, 0.8);
  }
}

.tank-gauge-label {
  font-size: 15px;
  font-weight: 600;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 1;
}

.tank-gauge-pct {
  font-size: 14px;
  color: rgba(255,255,255,0.95);
  font-weight: 700;
}

.tank-gauge-card.low-alert {
  animation: pulse-card-low 2s ease-in-out infinite;
}

@keyframes pulse-card-low {
  0%, 100% {
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
  }
  50% {
    box-shadow: 0 10px 30px rgba(220, 38, 38, 0.4);
  }
}

/* ========== MODAL MEJORADO ========== */
.ps-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.7);
  backdrop-filter: blur(5px);
  display: none;
  align-items: center;
  justify-content: center;
  z-index: 1050;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.ps-modal {
  background: white;
  width: 96%;
  max-width: 1000px;
  border-radius: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
  box-shadow: 0 20px 60px rgba(0,0,0,0.3);
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(50px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.ps-modal .modal-header {
  padding: 20px;
  border-bottom: 2px solid #e5e7eb;
  background: var(--primary-gradient);
  color: white;
}

.ps-modal .modal-body {
  padding: 20px;
  overflow-y: auto;
  max-height: 65vh;
}

.ps-modal .modal-footer {
  padding: 15px 20px;
  border-top: 2px solid #e5e7eb;
  background: #f9fafb;
}

.sales-table {
  width: 100%;
  border-collapse: collapse;
}

.sales-table thead th {
  position: sticky;
  top: 0;
  background: var(--primary-gradient);
  color: white;
  z-index: 2;
  padding: 12px 10px;
  font-weight: 600;
  text-transform: uppercase;
  font-size: 12px;
  letter-spacing: 0.5px;
}

.sales-table td {
  padding: 12px 10px;
  border-bottom: 1px solid #f1f1f1;
  font-size: 14px;
}

.sales-table tbody tr:hover {
  background: #f8f9fa;
}

/* ========== RESPONSIVE ========== */
@media (max-width: 991px) {
  .pump-grid {
    grid-template-columns: 1fr;
    grid-auto-rows: auto;
  }
  
  .right-islands {
    position: relative;
    max-height: none;
  }
  
  .nav-actions {
    display: none;
  }
  
  .nav-actions-mobile {
    display: block !important;
  }
}

@media (min-width: 992px) {
  .nav-actions-mobile {
    display: none !important;
  }
}

/* ========== BOTONES MEJORADOS ========== */
.btn {
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.btn:hover {
  transform: translateY(-2px);
}

#btnRefreshTanks {
  background: var(--info-gradient);
  color: white;
  border: none;
  box-shadow: 0 4px 10px rgba(79, 172, 254, 0.3);
}

#btnRefreshTanks:hover {
  box-shadow: 0 6px 20px rgba(79, 172, 254, 0.5);
}

/* ========== SCROLLBAR PERSONALIZADO ========== */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: var(--primary-gradient);
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}
</style>
</head>
<body>

<!-- NAVBAR -->
<nav class="navbar navbar-expand-lg navbar-light">
  <div class="container-fluid">
    <!-- ✅ BRAND CON NOMBRE DE ESTACIÓN Y USUARIO SIN ÓVALO -->
    <div class="navbar-brand">
      <i class="bi bi-fuel-pump-fill"></i>
      <span><?= esc($stationName) ?></span>
      <span class="user-text">
        <i class="bi bi-person-circle"></i>
        <?= esc($fullName) ?>
      </span>
    </div>

    <!-- Mobile dropdown -->
    <div class="nav-actions-mobile ms-auto">
      <div class="dropdown">
        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
          <i class="bi bi-list"></i> Menú
        </button>
        <ul class="dropdown-menu dropdown-menu-end">
          <li><a class="dropdown-item" href="<?= esc(site('pos/index.php')) ?>"><i class="bi bi-cart3"></i> Abrir POS</a></li>
          <li><a class="dropdown-item" href="<?= esc(site('ncf/facturas.php')) ?>"><i class="bi bi-receipt"></i> Comprobantes</a></li>
          <li><a class="dropdown-item" href="<?= esc(site('admin/index.php')) ?>"><i class="bi bi-gear"></i> Admin</a></li>
          <li><a class="dropdown-item" href="<?= esc(site('admin/reports.php')) ?>"><i class="bi bi-graph-up"></i> Ventas</a></li>
          <li><a class="dropdown-item" href="<?= esc(site('cierre_ventas.php')) ?>"><i class="bi bi-file-lock"></i> Cerrar turno</a></li>
          <li><hr class="dropdown-divider"></li>
          <li><a class="dropdown-item text-danger" href="<?= esc(site('admin_login.php')) ?>"><i class="bi bi-box-arrow-right"></i> Salir</a></li>
        </ul>
      </div>
    </div>

    <!-- Desktop buttons -->
    <div class="ms-auto nav-actions">
      <a class="btn btn-pos btn-sm" href="<?= esc(site('pos/index.php')) ?>">
        <i class="bi bi-cart3-fill"></i> Abrir POS
      </a>
      
      <a class="btn btn-pos btn-sm" href="<?= esc(site('ncf/facturas.php')) ?>">
        <i class="bi bi-receipt-cutoff"></i> Comprobantes
      </a>

      <a class="btn btn-admin btn-sm" href="<?= esc(site('admin/index.php')) ?>">
        <i class="bi bi-gear-fill"></i> Admin
      </a>

      <a class="btn btn-reports btn-sm" href="<?= esc(site('admin/reports.php')) ?>">
        <i class="bi bi-graph-up-arrow"></i> Ventas
      </a>

      <a class="btn btn-close-shift btn-sm" href="<?= esc(site('cierre_ventas.php')) ?>">
        <i class="bi bi-file-earmark-lock-fill"></i> Cerrar turno
      </a>

      <a class="btn btn-logout btn-sm" href="<?= esc(site('admin_login.php')) ?>">
        <i class="bi bi-box-arrow-right"></i> Salir
      </a>
    </div>
  </div>
</nav>

<!-- MAIN CONTAINER -->
<div class="container-fluid">
  <div class="main-container">
    
    <!-- DASHBOARD HEADER -->
    <div class="dashboard-header">
      <h2><i class="bi bi-speedometer2"></i> Dashboard de Ventas</h2>
      <small><i class="bi bi-clock-fill"></i> Última actualización: <span id="lastUpdate">—</span></small>
    </div>

    <div class="row">
      <!-- COLUMNA IZQUIERDA: CONTENIDO PRINCIPAL -->
      <div class="col-lg-9">
        
        <!-- 1. ESTADO DE TANQUES -->
        <div class="tank-status-section">
          <div class="d-flex align-items-center justify-content-between mb-3">
            <h4><i class="bi bi-droplet-fill"></i> Estado de Tanques</h4>
            <button id="btnRefreshTanks" type="button" class="btn btn-sm">
              <i class="bi bi-arrow-clockwise"></i> Actualizar
            </button>
          </div>
          <div id="tankGauges" class="row g-4"></div>
        </div>

        <!-- 2. VENTAS POR PRODUCTO -->
        <div class="chart-block">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h6><i class="bi bi-bar-chart-fill"></i> Ventas por producto (últimos <span id="rangeLabel">7</span> días)</h6>
            <select id="chartRange" class="form-select form-select-sm" style="width:auto">
              <option value="7">7 días</option>
              <option value="14">14 días</option>
              <option value="30">30 días</option>
            </select>
          </div>
          <div style="height:280px;">
            <canvas id="productSalesChart" height="280"></canvas>
          </div>
        </div>

        <!-- 3. VENTAS DIARIAS -->
        <div class="chart-panel">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5><i class="bi bi-graph-up"></i> Ventas diarias</h5>
            <select id="rangeSel" class="form-select form-select-sm" style="width:auto">
              <option value="7">Últimos 7 días</option>
              <option value="30">Últimos 30 días</option>
            </select>
          </div>
          <div style="height:340px;">
            <canvas id="salesChart" height="340"></canvas>
          </div>
        </div>

        <!-- 4. PRECIOS DE COMBUSTIBLES -->
        <div class="mb-4">
          <h5 class="mb-3" style="font-weight: 700; color: #2c3e50;">
            <i class="bi bi-fuel-pump"></i> Precios de Combustibles
          </h5>
          <div id="priceTiles" class="row g-2 tiles-row"></div>
        </div>

      </div>

      <!-- COLUMNA DERECHA: BOMBAS -->
      <div class="col-lg-3">
        <div class="right-islands">
          <h6><i class="bi bi-fuel-pump"></i> Islas / Bombas</h6>
          <div id="pumpsGrid" class="pump-grid"></div>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- MODAL -->
<div id="psModal" class="ps-modal-backdrop" aria-hidden="true">
  <div class="ps-modal" role="dialog" aria-modal="true">
    <div class="modal-header">
      <div style="flex:1">
        <strong id="psModalTitle">Ventas - Bomba</strong>
        <div class="small" id="psModalSubtitle" style="opacity:0.9"></div>
      </div>
      <div class="d-flex gap-2 align-items-center">
        <input id="psSearch" class="form-control form-control-sm" placeholder="Buscar..." style="width:200px">
        <button id="psExpandAll" class="btn btn-sm btn-outline-light">Expandir</button>
        <button id="psCollapseAll" class="btn btn-sm btn-outline-light">Contraer</button>
        <button id="psModalClose" class="btn btn-sm btn-light">
          <i class="bi bi-x-lg"></i>
        </button>
      </div>
    </div>
    <div class="modal-body" id="psModalBody">
      <div id="psModalContent"><div class="text-center text-muted py-4">Cargando...</div></div>
    </div>
    <div class="modal-footer">
      <button id="psModalClose2" class="btn btn-secondary btn-sm">
        <i class="bi bi-x-circle"></i> Cerrar
      </button>
    </div>
  </div>
</div>

<script>
  window.__FP_CONFIG = {
    api: <?= json_encode($apiUrl) ?>,
    pumpSvg: <?= json_encode($pumpSvg) ?>,
    imagenFolder: <?= json_encode($imagenFolder) ?>,
    pumpStatusApi: <?= json_encode(site('api_pump_status.php')) ?>
  };
  
  window.__PRODUCT_COLORS = <?= json_encode($productColors) ?>;
</script>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>
<script src="<?= esc(site('assets/js/dashboard.js')) ?>"></script>
<script src="<?= esc(site('assets/js/pump_monitor.js')) ?>"></script>

<script>
function fetchTanksCustom() {
  let url = window.__FP_CONFIG.api + '?action=get_tanques_status';
  fetch(url, {cache:'no-store'}).then(res => res.json()).then(j => {
    if (j.ok && Array.isArray(j.tanques)) {
      renderTankGaugesCustom(j.tanques);
    } else {
      document.getElementById('tankGauges').innerHTML = '<div class="col"><div class="alert alert-warning">No se pudo cargar el estado de tanques.</div></div>';
    }
  }).catch(e => {
    document.getElementById('tankGauges').innerHTML = '<div class="col"><div class="alert alert-danger">Error obteniendo tanques.</div></div>';
  });
}

function getProductColorByName(productName) {
  const colorMap = {
    'gasolina regular': 'linear-gradient(135deg, #52a868 0%, #3d8f53 100%)',
    'gasolina premium': 'linear-gradient(135deg, #ff2e00 0%, #d42600 100%)',
    'diesel regular': 'linear-gradient(135deg, #000000 0%, #2c2c2c 100%)',
    'diesel optimo': 'linear-gradient(135deg, #7f7f83 0%, #5a5a5d 100%)',
    'keroseno': 'linear-gradient(135deg, #6c757d 0%, #495057 100%)',
    'racing': 'linear-gradient(135deg, #2b8aef 0%, #1166d6 100%)'
  };
  
  const nameKey = productName.toLowerCase().trim();
  return colorMap[nameKey] || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
}

function renderTankGaugesCustom(tanques) {
  let wrap = document.getElementById('tankGauges');
  if (!wrap) return;
  wrap.innerHTML = '';
  
  if (!tanques.length) {
    wrap.innerHTML = '<div class="col"><div class="alert alert-info">No hay tanques registrados.</div></div>';
    return;
  }
  
  tanques.forEach(t => {
    let disponible = Number(t.disponible_real);
    let capacidad = Number(t.capacidad);
    let pct = capacidad > 0 ? Math.round((disponible / capacidad) * 100) : 0;
    let pctLabel = pct > 100 ? "¡Sobrellenado!" : pct + "%";
    
    let isLow = pct <= 33;
    let barColorClass = isLow ? 'low' : '';
    let cardLowClass = isLow ? 'low-alert' : '';
    
    let unidad = t.sku ? t.sku : 'L';
    let bgColor = getProductColorByName(t.producto_nombre || 'default');
    
    let warningIcon = isLow ? '<i class="bi bi-exclamation-triangle-fill ms-2" style="color: #fef08a;"></i>' : '';
    
    wrap.innerHTML += `
      <div class="col-12 col-md-6 col-xl-4">
        <div class="tank-gauge-card ${cardLowClass}" style="background: ${bgColor};">
          <div class="tank-gauge-title">
            <i class="bi bi-droplet-fill"></i> ${(t.producto_nombre || 'Tanque')}${warningIcon}
          </div>
          <div class="tank-gauge-cap">
            Capacidad: <b>${parseFloat(t.capacidad).toLocaleString()} ${unidad}</b>
          </div>
          <div class="tank-gauge-bar-wrap">
            <div class="tank-gauge-bar ${barColorClass}" style="width:${Math.min(pct,100)}%"></div>
          </div>
          <div class="tank-gauge-label">
            <span>Disponible: <b>${parseFloat(disponible).toLocaleString()} ${unidad}</b></span>
            <span class="tank-gauge-pct">${pctLabel}</span>
          </div>
        </div>
      </div>
    `;
  });
}

document.addEventListener('DOMContentLoaded', function(){
  fetchTanksCustom();

  let btnRefreshTanks = document.getElementById('btnRefreshTanks');
  if (btnRefreshTanks) {
    btnRefreshTanks.addEventListener('click', function() {
      btnRefreshTanks.disabled = true;
      btnRefreshTanks.innerHTML = '<i class="bi bi-arrow-clockwise"></i> Actualizando...';
      fetchTanksCustom();
      setTimeout(() => {
        btnRefreshTanks.disabled = false;
        btnRefreshTanks.innerHTML = '<i class="bi bi-arrow-clockwise"></i> Actualizar';
      }, 1200);
    });
  }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>