<?php
session_start();
/*if (!isset($_SESSION['usuario']) || empty($_SESSION['usuario'])) {
    header('Location: ../../index.php');
    exit();
}*/
$usuario = $_SESSION['usuario'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <title>URBANVIEW</title>
  <link rel="shortcut icon" href="https://laganamass.com/urbanviews/resources/img/logour.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <!-- CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet" />
  <link href="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css" rel="stylesheet" />

  <style>
    html, body {height:100%; margin:0; font-family:Arial,sans-serif; overflow:hidden;}
    .topbar {
      height: 60px; background:#343a40; color:#fff;
      display:flex; justify-content:space-between; align-items:center;
      padding:0 20px; position:fixed; top:0; left:0; right:0; z-index:1000;
    }
    .wrapper { display: flex; height: calc(100vh - 60px); margin-top: 60px; overflow: hidden;}
    .sidebar {
      width: 250px; background:#343a40; color:#fff; padding:20px; overflow-y:auto;
      transition: width 0.3s ease; flex-shrink:0;
    }
    .sidebar.collapsed { width: 80px;}
    .sidebar a { color:#fff; text-decoration:none; display:block; padding:12px 10px;}
    .main-content {
      flex-grow:1; margin-left:250px; transition:margin-left 0.3s ease; height:100%; overflow:hidden; display:flex;
    }
    .sidebar.collapsed ~ .main-content { margin-left: 80px;}
    #map { height: 100%; width: 100%; flex: 1; }
    .info { display:flex; gap:1rem; align-items:center;}
    /* --------- Panel de detalles ----------- */
    .details-panel {
      width: 370px; background: #fff; box-shadow: -1px 0 8px #0002; z-index: 1;
      padding: 22px 22px 14px 22px; overflow-y: auto; border-left: 1px solid #e7e7e7;
      display: flex; flex-direction: column; gap: 8px;
      transition: right 0.3s;
    }
    .details-panel.hidden { right: -380px; }
    .details-title { font-weight:bold; font-size:1.35rem; color:#343a40; letter-spacing:0.2px;}
    .details-label { color: #888; font-size: 15px; font-weight: 600; min-width: 90px; display:inline-block;}
    .details-value { color: #222; font-weight: 500;}
    .bat-bar {
      display: inline-block; vertical-align: middle; margin: 0 8px 0 3px; height: 11px; width: 62px;
      border-radius: 5px; background: #eee; position: relative; box-shadow: 0 1px 4px #0001; overflow: hidden;
    }
    .bat-bar-inner {
      height: 100%; border-radius: 4px;
      background: linear-gradient(90deg, #c8fa00, #fdd835, #f44336);
      position: absolute; top:0; left:0; transition: width 0.4s cubic-bezier(.7,1.5,.4,1);
    }
    .details-close {
      position:absolute; top:7px; right:13px; font-size:1.3rem; color:#bcbcbc; border:none; background:transparent; cursor:pointer; z-index:3;
    }
    /* --------- Mapbox Custom Popup Styles ----------- */
    .mapboxgl-popup-content { box-shadow:none!important; background:#fff!important; padding:0!important; border-radius:16px!important; min-width:340px; border:none; position:relative; overflow:visible!important;}
    .mapboxgl-popup-tip { width:28px!important; height:20px!important; background:transparent!important; margin:-2px 0 0 0!important; left:50%!important; transform:translateX(-50%)!important;}
    .mapboxgl-popup-tip:after { content:''; position:absolute; left:50%; transform:translateX(-50%); top:0; width:0; height:0; border-left:18px solid transparent; border-right:18px solid transparent; border-top:18px solid #fff;}
    .mapboxgl-popup-close-button { display:none!important;}
    .mapboxgl-popup { font-family:'Segoe UI',Arial,sans-serif; font-size:16px;}
    .popup-main { padding:18px 18px 10px 18px; border-radius:16px; background:#fff;}
    .popup-title-row { display:flex; align-items:center; gap:8px; margin-bottom:8px;}
    .popup-title { color:#222; font-weight:bold; font-size:22px; letter-spacing:0.2px; text-shadow:none; margin-right:3px;}
    .popup-placa { background:#ededed; color:#111; font-size:16px; font-weight:700; border-radius:7px; padding:2px 10px 2px 10px; margin-left:4px;}
    .popup-label { color:#888; font-size:15px; font-weight:600; min-width:85px; display:inline-block;}
    .popup-value { color:#222; font-weight:500;}
    .popup-row { margin-bottom:7px; display:flex; align-items:center; gap:8px;}
    .popup-bat-bar { display:inline-block; vertical-align:middle; margin:0 8px 0 3px; height:11px; width:62px; border-radius:5px; background:#eee; position:relative; box-shadow:0 1px 4px #0001; overflow:hidden;}
    .popup-bat-bar-inner { height:100%; border-radius:4px; background:linear-gradient(90deg,#c8fa00,#fdd835,#f44336); position:absolute; top:0; left:0; transition:width 0.4s cubic-bezier(.7,1.5,.4,1);}
    .popup-status { background:#e6fbe4; color:#26a842; padding:1.5px 14px; border-radius:7px; font-weight:600; font-size:15px; margin-left:0;}
    @media (max-width: 1000px) {
      .details-panel { width:100vw; max-width:99vw; left:0; right:unset; border-left:none; border-top:1px solid #e7e7e7; top:unset; bottom:0; height:260px;}
      .main-content { flex-direction:column;}
      #map {height:100%; min-height:200px;}
    }
    .marker-animate { animation:pulse 2s infinite; box-shadow:0 0 0 0 #f8d90f99; border-radius:50%;}
    @keyframes pulse { 0%{box-shadow:0 0 0 0 #f8d90f60;} 70%{box-shadow:0 0 0 18px #f8d90f00;} 100%{box-shadow:0 0 0 0 #f8d90f00;} }
  </style>
</head>
<body>
  <header class="topbar">
    <button class="btn btn-dark" onclick="toggleSidebar()" aria-label="Menú"><i class="fas fa-bars"></i></button>
    <span>URBANVIEW</span>
    <div class="info">
      <span><?= htmlspecialchars($usuario) ?></span>
      <span id="fechaActual"></span>
      <span id="horaActual"></span>
      <!-- Botón en la cabecera -->
<button id="btnCerrarSesion" class="btn btn-sm btn-danger" aria-label="Cerrar sesión">
  <i class="fas fa-sign-out-alt"></i>
</button>

    </div>
  </header>

  <div class="wrapper">
    <nav class="sidebar"><?php include "menu.php"; ?></nav>
    <main class="main-content">
      <div id="map"></div>
      <div id="detailsPanel" class="details-panel" style="display:none;position:relative;"></div>
    </main>
  </div>

  <!-- JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <!-- MAPBOX debe ir antes del script type="module" -->
  <script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>
  <!-- FIREBASE + MAPBOX Y LÓGICA DEL MAPA -->
  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/11.9.1/firebase-app.js";
    import { getDatabase, ref, onValue } from "https://www.gstatic.com/firebasejs/11.9.1/firebase-database.js";

    const firebaseConfig = {
      apiKey: "AIzaSyBLkRsp1MdZKJRb-drr6mXMG-_2DTOdhFk",
      authDomain: "urbanoview-18dee.firebaseapp.com",
      databaseURL: "https://urbanoview-18dee-default-rtdb.firebaseio.com",
      projectId: "urbanoview-18dee",
      storageBucket: "urbanoview-18dee.appspot.com",
      messagingSenderId: "903862593621",
      appId: "1:903862593621:web:5d190c50278cc0eb088cdc",
      measurementId: "G-JD4E1J58VT"
    };

    const app = initializeApp(firebaseConfig);
    const db = getDatabase(app);

    mapboxgl.accessToken = 'pk.eyJ1Ijoid2lsc29za2kyOSIsImEiOiJjbTd2NHVidWwwN2t1MnZvazk2MDBmcTM0In0.Bd1HlYKT7U1wXIsrsAfaZg';
    const map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/navigation-night-v1',
      center: [-80.0977, -0.6794],
      zoom: 13,
      attributionControl: false
    });
    map.addControl(new mapboxgl.NavigationControl());

    function createTaxiIcon() {
      const el = document.createElement('div');
      el.style.width = '32px';
      el.style.height = '32px';
      el.style.background = '#f8d90f';
      el.style.borderRadius = '50%';
      el.style.display = 'flex';
      el.style.alignItems = 'center';
      el.style.justifyContent = 'center';
      el.className = 'marker-animate';
      el.innerHTML = `
        <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
          <rect x="4" y="10" width="20" height="9" rx="4" fill="#fff"/>
          <rect x="8" y="6" width="12" height="6" rx="2.2" fill="#fff"/>
          <circle cx="8.5" cy="22.5" r="2.2" fill="#222"/>
          <circle cx="19.5" cy="22.5" r="2.2" fill="#222"/>
          <rect x="10" y="9" width="8" height="2" rx="1" fill="#F8D90F"/>
          <rect x="12" y="7" width="4" height="2" rx="1" fill="#F8D90F"/>
        </svg>
      `;
      return el;
    }

    function buildPanelHtml(data) {
      let html = `
        <button class="details-close" onclick="document.getElementById('detailsPanel').style.display='none'">&times;</button>
        <div class="details-title">${data.nombre || data.nombre_chofer || '-'}</div>
        <div><span class="details-label">Placa:</span> <span class="details-value">${data.placa || ''}</span></div>
      `;
      const omitFields = ['nombre', 'nombre_chofer', 'placa', 'ubicacion', 'nivel_bateria', 'ultima_conexion', 'conexion'];
      Object.keys(data).forEach(key => {
        if (!omitFields.includes(key)) {
          html += `<div><span class="details-label">${key.replace(/_/g, ' ').toUpperCase()}:</span> <span class="details-value">${data[key]}</span></div>`;
        }
      });
      const bat = Number(data.nivel_bateria) || 0;
      html += `
        <div>
          <span class="details-label">Batería:</span>
          <span class="bat-bar"><span class="bat-bar-inner" style="width:${bat}%;"></span></span>
          <span class="details-value">${bat}%</span>
        </div>
      `;
      html += `<div><span class="details-label">Estado:</span> <span class="details-value">${data.conexion || '-'}</span></div>`;
      let lastSeen = "-";
      if (typeof data.ultima_conexion === "string") {
        try {
          lastSeen = new Date(data.ultima_conexion).toLocaleString();
        } catch { lastSeen = data.ultima_conexion; }
      }
      html += `<div><span class="details-label">Última conexión:</span> <span class="details-value">${lastSeen}</span></div>`;
      let lat = 0, lng = 0;
      if (data.ubicacion && typeof data.ubicacion.lat !== "undefined") lat = data.ubicacion.lat;
      if (data.ubicacion && typeof data.ubicacion.lng !== "undefined") lng = data.ubicacion.lng;
      html += `<div><span class="details-label">Ubicación:</span> <span class="details-value">${Number(lat).toFixed(5)}, ${Number(lng).toFixed(5)}</span></div>`;
      return html;
    }

    function buildPopup(data) {
      const lat = data.ubicacion?.lat ?? 0;
      const lng = data.ubicacion?.lng ?? 0;
      const bat = Number(data.nivel_bateria) || 0;
      let lastSeen = "-";
      if (typeof data.ultima_conexion === "string") {
        try {
          lastSeen = new Date(data.ultima_conexion).toLocaleString();
        } catch { lastSeen = data.ultima_conexion; }
      }
      return `
        <div class="popup-main">
          <div class="popup-title-row">
            <span class="popup-title">${data.nombre || data.nombre_chofer || '-'}</span>
            <span class="popup-placa">${data.placa || ''}</span>
          </div>
          <div class="popup-row">
            <span class="popup-label">Batería</span>
            <span class="popup-bat-bar">
              <span class="popup-bat-bar-inner" style="width:${bat}%;"></span>
            </span>
            <span class="popup-value">${bat}%</span>
          </div>
          <div class="popup-row">
            <span class="popup-label">Estado</span>
            <span class="popup-status">${data.conexion || '-'}</span>
          </div>
          <div class="popup-row">
            <span class="popup-label">Últ. conexión</span>
            <span class="popup-value">${lastSeen}</span>
          </div>
          <div class="popup-row">
            <span class="popup-label">Ubicación</span>
            <span class="popup-value">${Number(lat).toFixed(5)}, ${Number(lng).toFixed(5)}</span>
          </div>
          <div class="popup-row" style="margin-top:9px; font-size:13px;">
            ${Object.keys(data).filter(k=>!['nombre','nombre_chofer','placa','ubicacion','nivel_bateria','ultima_conexion','conexion'].includes(k)).map(
              key => `<span style="color:#666;">${key.replace(/_/g,' ').toUpperCase()}:</span> <span>${data[key]}</span>`
            ).join("<br>")}
          </div>
        </div>
      `;
    }

    // ----------------- Markers con animación -----------------
    const taxis = {};
    let taxiSeleccionado = null;

    function lerp(a, b, t) { return a + (b - a) * t; }

    function animateMarker(taxiId) {
      const obj = taxis[taxiId];
      if (!obj || !obj.from || !obj.to) return;
      const now = performance.now();
      const duration = 900;
      const t = Math.min((now - obj.lastUpdateTime) / duration, 1);
      const currLat = lerp(obj.from.lat, obj.to.lat, t);
      const currLng = lerp(obj.from.lng, obj.to.lng, t);
      obj.marker.setLngLat([currLng, currLat]);
      if (obj.popup && obj.popup.isOpen()) {
        obj.popup.setLngLat([currLng, currLat]);
        obj.popup.setHTML(buildPopup(obj.lastData));
      }
      if (taxiSeleccionado === taxiId) {
        actualizarPanelDetalles(obj.lastData);
      }
      if (t < 1) {
        obj.animFrame = requestAnimationFrame(() => animateMarker(taxiId));
      } else {
        obj.from = {...obj.to};
        obj.animFrame = null;
      }
    }

    function actualizarPanelDetalles(data) {
      const panel = document.getElementById('detailsPanel');
      panel.innerHTML = buildPanelHtml(data);
      panel.style.display = 'flex';
    }

    function updateOrCreateTaxiMarker(id, data) {
      const lat = data.ubicacion?.lat ?? 0;
      const lng = data.ubicacion?.lng ?? 0;
      if (!taxis[id]) {
        // Nuevo taxi
        const marker = new mapboxgl.Marker(createTaxiIcon())
          .setLngLat([lng, lat])
          .addTo(map);
        const popup = new mapboxgl.Popup({ closeOnClick: false, closeButton: false, offset: 24, anchor: "bottom" })
          .setHTML(buildPopup(data));
        marker.setPopup(popup);
        marker.getElement().addEventListener('click', () => {
          Object.values(taxis).forEach(t => t.popup.remove());
          popup.addTo(map);
          taxiSeleccionado = id;
          actualizarPanelDetalles(data);
        });
        taxis[id] = {
          marker,
          popup,
          from: { lat, lng },
          to: { lat, lng },
          lastUpdateTime: performance.now(),
          animFrame: null,
          lastData: data
        };
      } else {
        const obj = taxis[id];
        obj.from = obj.marker.getLngLat();
        obj.to = { lat, lng };
        obj.lastUpdateTime = performance.now();
        obj.lastData = data;
        if (!obj.animFrame) {
          obj.animFrame = requestAnimationFrame(() => animateMarker(id));
        }
        if (obj.popup && obj.popup.isOpen()) {
          obj.popup.setHTML(buildPopup(data));
        }
        if (taxiSeleccionado === id) {
          actualizarPanelDetalles(data);
        }
      }
    }

    // Escuchar la base de datos en tiempo real:
    onValue(ref(db, 'taxis'), snapshot => {
      const taxisData = snapshot.val() || {};
      const idsVistos = new Set();
      Object.entries(taxisData).forEach(([id, data]) => {
        updateOrCreateTaxiMarker(id, data);
        idsVistos.add(id);
      });
      Object.keys(taxis).forEach(id => {
        if (!idsVistos.has(id)) {
          taxis[id].marker.remove();
          taxis[id].popup.remove();
          if (taxis[id].animFrame) cancelAnimationFrame(taxis[id].animFrame);
          delete taxis[id];
        }
      });
      // Si el taxi seleccionado ya no existe, oculta panel
      if (taxiSeleccionado && !idsVistos.has(taxiSeleccionado)) {
        document.getElementById('detailsPanel').style.display = 'none';
        taxiSeleccionado = null;
      }
    });

    // -------- Sidebar y otras funciones igual que antes --------
    function actualizarHora() {
      const ahora = new Date();
      document.getElementById('fechaActual').textContent = ahora.toLocaleDateString('es-ES', {
        weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
      });
      document.getElementById('horaActual').textContent = ahora.toLocaleTimeString('es-ES', {
        hour: '2-digit', minute: '2-digit', second: '2-digit'
      });
    }

    function toggleSidebar() {
      const sidebar = document.querySelector('.sidebar');
      if (window.innerWidth <= 768) {
        sidebar.classList.toggle('show');
      } else {
        sidebar.classList.toggle('collapsed');
        document.querySelector('.main-content').style.marginLeft = sidebar.classList.contains('collapsed') ? '80px' : '250px';
      }
      setTimeout(() => map.resize(), 310);
    }

    // Función cerrar sesión
function cerrarSesion() {
  Swal.fire({
    title: '¿Cerrar sesión?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Sí',
    cancelButtonText: 'No'
  }).then(result => {
    if (result.isConfirmed) {
      fetch('../../controllers/usuario.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({ boton: 'cerrar' })
      })
      .then(res => {
        if (res.ok) {
          location.href = '../../index.php';
        } else {
          throw new Error('Error al cerrar sesión');
        }
      })
      .catch(err => {
        Swal.fire('Error', err.message, 'error');
      });
    }
  });
}

// Registrar el botón al DOM
document.getElementById('btnCerrarSesion')?.addEventListener('click', cerrarSesion);



    setInterval(actualizarHora, 1000);
    actualizarHora();

    // Responsive: sidebar fuera si haces click fuera de ella en móviles
    document.addEventListener('click', e => {
      const sidebar = document.querySelector('.sidebar');
      if (window.innerWidth <= 768 && sidebar.classList.contains('show')) {
        const btn = e.target.closest('button[onclick="toggleSidebar()"]');
        if (!btn && !sidebar.contains(e.target)) {
          sidebar.classList.remove('show');
          map.resize();
        }
      }
    });
    window.addEventListener('resize', () => map.resize());

    // Para evitar error en onclick del botón cerrar, lo definimos global
    window.document.getElementById('detailsPanel').onclick = function(e){
      if(e.target.classList.contains('details-close')){
        this.style.display = 'none';
        taxiSeleccionado = null;
      }
    }
  </script>
</body>
</html>
