<?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/index.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');
$loggedUser = $_SESSION['username'] ?? '';
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>SolutionPOS - Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="<?= esc(site('assets/style.css')) ?>">
<style>
/* Compact styles */
.tiles-row .price-card { min-height:120px; border-radius:14px; color:#fff; }
.pump-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;grid-auto-rows:220px}
.pump-card{background:#fff;border-radius:12px;border:1px solid #eef2f6;display:flex;flex-direction:column;align-items:center;padding:10px;cursor:pointer;overflow:hidden}
.pump-image{width:100%;height:120px;display:flex;align-items:center;justify-content:center;background:#fff;border-radius:8px;overflow:hidden}
.pump-image img{height:100%;width:auto;object-fit:contain}

/* Modal improvements */
.ps-modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;z-index:1050}
.ps-modal{background:#fff;width:96%;max-width:920px;border-radius:8px;overflow:hidden;display:flex;flex-direction:column;max-height:90vh}
.ps-modal .modal-header{padding:12px;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center;gap:12px}
.ps-modal .modal-controls { display:flex; gap:8px; align-items:center; }
.ps-modal .modal-body{padding:12px; overflow-y:auto; max-height:65vh; }
.ps-modal .modal-footer{padding:12px;border-top:1px solid #eee;text-align:right}

/* sticky header inside modal */
.sales-table { width:100%; border-collapse:collapse; }
.sales-table thead th { position: sticky; top:0; background:#fff; z-index:2; }
.sales-table th, .sales-table td { padding:8px 6px; border-bottom:1px solid #f1f1f1; font-size:14px; vertical-align:middle; }
.sales-no-data { padding:18px; text-align:center; color:#6c757d; }

@media (max-width:991px){ .pump-grid{grid-template-columns:1fr;grid-auto-rows:auto} .pump-image{height:100px} }
.print-btn{margin-left:8px}

/* Tanques Gauge styles */
.tank-status-section { margin-top: 40px; }
.tank-gauge-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #0001;
  padding: 16px 18px 14px 18px;
  margin-bottom: 20px;
  min-width: 270px;
}
.tank-gauge-title {
  font-weight: 600;
  margin-bottom: 2px;
}
.tank-gauge-cap {
  font-size: 13px;
  color: #888;
}
.tank-gauge-bar-wrap {
  width: 100%;
  height: 30px;
  background: #eee;
  border-radius: 12px;
  overflow: hidden;
  margin-top: 10px;
  margin-bottom: 2px;
  border: 1.5px solid #eee;
}
.tank-gauge-bar {
  height: 100%;
  border-radius: 12px;
  transition: width 1s cubic-bezier(.33,1.36,.63,1);
  background: linear-gradient(90deg, #6dce57 70%, #f7e02b 90%);
}
.tank-gauge-bar.low {
  background: linear-gradient(90deg, #fc4a4a 70%, #ffb43a 100%);
}
.tank-gauge-label {
  font-size: 14px;
  margin-top: 2px;
  font-weight: 500;
  letter-spacing: .5px;
}
.tank-gauge-pct {
  float:right; font-size:13px; color:#555;
}
@media (max-width:991px){ .tank-gauge-card{min-width:unset;} }
</style>
</head>
<body class="bg-light">

<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
  <div class="container">
    <a class="navbar-brand fw-bold" href="<?= esc(site('index.php')) ?>">
      SolutionPOS<?= $loggedUser ? ' - ' . esc($loggedUser) : '' ?>
    </a>
    <div class="ms-auto d-flex gap-2">
      <a class="btn btn-outline-primary btn-sm" href="<?= esc(site('pos/index.php')) ?>">Abrir POS</a>
      <a class="btn btn-outline-info btn-sm" href="<?= esc(site('admin/reports.php')) ?>">Ventas</a>
      <a class="btn btn-outline-secondary btn-sm" href="<?= esc(site('admin_login.php')) ?>">Logout</a>
    </div>
  </div>
</nav>

<div class="container-fluid mt-4">
  <div class="container">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <div>
        <h2 class="mb-0">Resumen</h2>
        <small class="text-muted">Última actualización: <span id="lastUpdate">—</span></small>
      </div>
    </div>

    <div id="priceTiles" class="row g-3 mb-4 tiles-row"></div>

    <div class="row">
      <div class="col-lg-9">
        <div class="chart-block mb-4 bg-white p-3 rounded shadow-sm">
          <div class="d-flex justify-content-between align-items-center mb-2">
            <h6 class="mb-0">Ventas por producto (últimos <span id="rangeLabel">7</span> días)</h6>
            <div><select id="chartRange" class="form-select form-select-sm"><option value="7">7 días</option><option value="14">14 días</option><option value="30">30 días</option></select></div>
          </div>
          <div style="height:260px;"><canvas id="productSalesChart" height="260"></canvas></div>
        </div>

        <div class="chart-panel mb-4 bg-white p-3 rounded shadow-sm">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">Ventas (diario)</h5>
            <div><select id="rangeSel" class="form-select form-select-sm"><option value="7">Últimos 7 días</option><option value="30">Últimos 30 días</option></select></div>
          </div>
          <div style="height:320px;"><canvas id="salesChart" height="320"></canvas></div>

          <div class="recent-sales mt-3">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <strong>Ventas recientes</strong>
              <small class="text-muted">Últimas 10</small>
            </div>
            <div id="recentList"><div class="no-data">Cargando...</div></div>
          </div>
        </div>

        <!-- Sección de tanques -->
        <div class="tank-status-section">
          <h4 class="mb-3">Estado de Tanques</h4>
          <div id="tankGauges" class="row g-3"></div>
        </div>
        <!-- Fin sección de tanques -->
      </div>

      <div class="col-lg-3">
        <div class="right-islands bg-white rounded shadow-sm p-3">
          <h6 class="mb-3">Islas / Bombas</h6>
          <div id="pumpsGrid" class="pump-grid"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal: pump sales -->
<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 text-muted" id="psModalSubtitle"></div>
      </div>
      <div class="modal-controls">
        <input id="psSearch" class="form-control form-control-sm" placeholder="Buscar ticket o producto..." style="min-width:200px">
        <button id="psExpandAll" class="btn btn-sm btn-outline-secondary">Expandir todo</button>
        <button id="psCollapseAll" class="btn btn-sm btn-outline-secondary">Contraer todo</button>
        <button id="psModalClose" class="btn btn-sm btn-outline-secondary">Cerrar</button>
      </div>
    </div>
    <div class="modal-body" id="psModalBody">
      <div id="psModalContent"><div class="sales-no-data">Cargando...</div></div>
    </div>
    <div class="modal-footer">
      <button id="psModalClose2" class="btn btn-secondary btn-sm">Cerrar</button>
    </div>
  </div>
</div>

<script>
  window.__FP_CONFIG = {
    api: <?= json_encode($apiUrl) ?>,
    pumpSvg: <?= json_encode($pumpSvg) ?>
  };
</script>

<!-- Chart.js before our 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>

<!-- BLOQUE PARA TANQUES, SOLO AGREGA ESTO, NO MODIFICA NADA MAS -->
<script>
// Tanques - carga y renderizado (no interfiere con dashboard.js)
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 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 barColorClass = pct <= 30 ? 'low' : '';
    wrap.innerHTML += `
      <div class="col-12 col-md-6 col-lg-4">
        <div class="tank-gauge-card">
          <div class="tank-gauge-title">${(t.producto_nombre || 'Tanque')}</div>
          <div class="tank-gauge-cap">Capacidad: <b>${parseFloat(t.capacidad).toLocaleString()} L</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">
            Disponible: <b>${parseFloat(disponible).toLocaleString()} L</b>
            <span class="tank-gauge-pct">${pctLabel}</span>
          </div>
        </div>
      </div>
    `;
  });
}
document.addEventListener('DOMContentLoaded', function(){
  fetchTanksCustom();
});
</script>
</body>
</html>