<!DOCTYPE html>
<?php
session_start();

// Verificar si la variable de sesión 'usuario' está definida y no está vacía
if (!isset($_SESSION['usuario']) || empty($_SESSION['usuario'])) {
    // Si no está definido, redirigir al login
    header('Location: ../../index.php');
    exit(); // Terminar el script para evitar que el código siguiente se ejecute
}

// Si sí está definida, asignamos el usuario a una variable local
$usuario = $_SESSION['usuario'];
?>

<html lang="es">
<head>
<meta charset="UTF-8" />
<title>URBANVIEW</title>
<link rel="shortcut icon" href="../../resources/img/logour.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<!-- Bootstrap y FontAwesome -->
<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" />

<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" crossorigin=""/>

<style>
html, body {
  height: 100%;
  margin: 0;
  overflow: hidden;
  font-family: Arial, Helvetica, sans-serif;
}

body {
  display: flex;
  flex-direction: column;
}

.topbar {
  height: 60px;
  background: #343a40;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.wrapper {
  display: flex;
  flex-grow: 1;
  margin-top: 60px;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: #343a40;
  padding: 20px;
  overflow-y: auto;
  flex-shrink: 0;
  transition: width 0.3s ease;
}

.sidebar.collapsed {
  width: 80px;
}

.sidebar a {
  color: #fff;
  text-decoration: none;
  padding: 12px;
  display: flex;
  align-items: center;
}

.main-content {
  flex-grow: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-left: 250px;
  transition: margin-left 0.3s ease;
}

.sidebar.collapsed ~ .main-content {
  margin-left: 80px;
}

#map {
  flex-grow: 1;
  width: 100%;
  height: 100%;
}

.info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

/* Responsive para móviles */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 60px;
    left: 0;
    height: calc(100% - 60px);
    z-index: 999;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
    width: 250px;
  }

  .sidebar.show {
    transform: translateX(0);
  }

  .main-content {
    margin-left: 0 !important;
  }

  .wrapper {
    flex-direction: column;
  }
}
</style>
</head>
<body>
<header class="topbar">
  <button class="btn btn-dark" onclick="toggleSidebar()" aria-label="Toggle sidebar">
    <i class="fas fa-bars"></i>
  </button>
  <span>URBANVIEW</span>
  <div class="info">
    <span><?=htmlspecialchars($_SESSION['usuario'], ENT_QUOTES, 'UTF-8');?></span>
    <span id="fechaActual"></span>
    <span id="horaActual"></span>
    <button class="btn btn-sm btn-danger" onclick="cerrar(event)" 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></main>
</div>

<!-- JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<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>
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" crossorigin=""></script>

<script>
function actualizarHora() {
  const ahora = new Date();
  const opF = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  const opH = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
  document.getElementById('fechaActual').textContent = ahora.toLocaleDateString('es-ES', opF);
  document.getElementById('horaActual').textContent = ahora.toLocaleTimeString('es-ES', opH);
}
setInterval(actualizarHora, 1000);
actualizarHora();

function toggleSidebar() {
  const sidebar = document.querySelector('.sidebar');
  if (window.innerWidth <= 768) {
    sidebar.classList.toggle('show');
  } else {
    sidebar.classList.toggle('collapsed');
  }
  setTimeout(() => map.invalidateSize(), 310);
}

document.addEventListener('click', function(e) {
  const sidebar = document.querySelector('.sidebar');
  const toggleBtn = e.target.closest('button[onclick="toggleSidebar()"]');
  if (window.innerWidth <= 768 && !sidebar.contains(e.target) && !toggleBtn) {
    sidebar.classList.remove('show');
    map.invalidateSize();
  }
});

function cerrar(e) {
  const b = e.currentTarget;
  Swal.fire({ title: '¿Cerrar sesión?', icon: 'warning', showCancelButton: true, confirmButtonText: 'Sí' }).then(r => {
    if (r.isConfirmed) {
      b.disabled = true;
      fetch('../../controllers/usuario.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ boton: 'cerrar' })
      })
      .then(r => r.ok ? location.href = '../../index.php' : Promise.reject('Error al cerrar sesión'))
      .catch(err => {
        b.disabled = false;
        Swal.fire('Error', err, 'error');
      });
    }
  });
}

const map = L.map('map').setView([-0.6794, -80.0977], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; OpenStreetMap'
}).addTo(map);

const iconoVerde = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.3/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

const iconoRojo = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.3/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

const marcadores = {};

async function cargarUbicaciones() {
  try {
    const res = await fetch('obtener_ubicaciones.php');
    if (!res.ok) throw new Error('Error al obtener ubicaciones');
    const data = await res.json();

    data.forEach(d => {
      const id = d.id_tablet, lat = +d.latitud, lng = +d.longitud, activo = +d.activa === 1;
      const popup = `Tablet: <strong>${id}</strong><br>Última actualización: ${d.fecha_hora}<br>Estado: ${activo ? 'Activa' : 'Inactiva'}`;
      const icon = activo ? iconoVerde : iconoRojo;

      if (marcadores[id]) {
        marcadores[id].setLatLng([lat, lng]).setIcon(icon).getPopup().setContent(popup);
      } else {
        marcadores[id] = L.marker([lat, lng], { icon }).addTo(map).bindPopup(popup);
      }
    });

    Object.keys(marcadores).forEach(id => {
      if (!data.find(d => d.id_tablet === id)) {
        map.removeLayer(marcadores[id]);
        delete marcadores[id];
      }
    });
  } catch (err) {
    console.error(err);
  }
}

cargarUbicaciones();
setInterval(cargarUbicaciones, 10000);
window.addEventListener('resize', () => map.invalidateSize());
</script>
</body>
</html>
.