<?php
include 'header.php';
include '../config/conexion.php';

try {
    // Apertura de conexión según tu estructura
    $database = new Connection();
    $db = $database->open();

    // Fechas de filtro
    $fechainicio = isset($_POST['fechainicio']) ? $_POST['fechainicio'] : date('Y-m-d');
    $fechafin    = isset($_POST['fechafin']) ? $_POST['fechafin'] : date('Y-m-d');

    // Consulta de accesos geolocalizados
    $sql = "SELECT a.id, u.fullname, u.usuario, u.rol, a.latitud, a.longitud, a.fecha
            FROM accesos_usuarios a
            INNER JOIN usuarios u ON u.id = a.usuario_id
            WHERE DATE(a.fecha) BETWEEN :fechainicio AND :fechafin
            ORDER BY a.fecha DESC";

    $stmt = $db->prepare($sql);
    $stmt->bindParam(':fechainicio', $fechainicio);
    $stmt->bindParam(':fechafin', $fechafin);
    $stmt->execute();
    $accesos = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Error en DB: " . $e->getMessage());
}
?>

<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

<div class="content mt-3">
  <div class="animated fadeIn">
    <div class="card shadow-sm border-0">
      <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fa fa-map-marker"></i> Mapa de accesos de usuarios</h5>
      </div>

      <div class="card-body">
        <!-- Filtro de fechas -->
        <form method="POST" class="row g-3 mb-3">
          <div class="col-md-4">
            <label><strong>Fecha inicio:</strong></label>
            <input type="date" name="fechainicio" value="<?= $fechainicio ?>" class="form-control border-primary" required>
          </div>
          <div class="col-md-4">
            <label><strong>Fecha fin:</strong></label>
            <input type="date" name="fechafin" value="<?= $fechafin ?>" class="form-control border-primary" required>
          </div>
          <div class="col-md-4 d-flex align-items-end">
            <button type="submit" class="btn btn-success w-100">
              <i class="fa fa-search"></i> Consultar
            </button>
          </div>
        </form>

        <!-- Mapa -->
        <div id="map" style="height: 550px; border-radius: 10px; position: relative;"></div>

        <!-- Leyenda -->
        <div id="legend" style="
            background: white;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 0 5px rgba(0,0,0,0.3);
            position: absolute;
            bottom: 30px;
            left: 30px;
            font-size: 14px;
        ">
          <strong>Leyenda:</strong><br>
          <img src='https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png' width='15'> Administrador<br>
          <img src='https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png' width='15'> Chofer<br>
          <img src='https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png' width='15'> Técnico<br>
          <img src='https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-yellow.png' width='15'> Otros
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
  var accesos = <?= json_encode($accesos) ?>;

  // Inicializa el mapa centrado en Lima por defecto
  var map = L.map('map').setView([-12.0464, -77.0428], 12);
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap'
  }).addTo(map);

  // Iconos por rol
  var icons = {
      "Administrador": L.icon({
          iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png',
          shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
          iconSize: [25, 41],
          iconAnchor: [12, 41],
          popupAnchor: [1, -34]
      }),
      "Chofer": L.icon({
          iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png',
          shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
          iconSize: [25, 41],
          iconAnchor: [12, 41],
          popupAnchor: [1, -34]
      }),
      "Tecnico": L.icon({
          iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
          shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
          iconSize: [25, 41],
          iconAnchor: [12, 41],
          popupAnchor: [1, -34]
      }),
      "default": L.icon({
          iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-yellow.png',
          shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
          iconSize: [25, 41],
          iconAnchor: [12, 41],
          popupAnchor: [1, -34]
      })
  };

  // Mostrar los marcadores
  if (accesos.length > 0) {
      map.setView([accesos[0].latitud, accesos[0].longitud], 13);

      accesos.forEach(function(acc) {
          if (acc.latitud && acc.longitud) {
              var icono = icons[acc.rol] || icons["default"];
              var marker = L.marker([acc.latitud, acc.longitud], { icon: icono }).addTo(map);

              marker.bindPopup(
                  "<b>👤 Usuario:</b> " + acc.fullname + "<br>" +
                  "<b>Rol:</b> " + acc.rol + "<br>" +
                  "<b>Cuenta:</b> " + acc.usuario + "<br>" +
                  "<b>📅 Fecha y Hora:</b> " + acc.fecha
              );

              marker.bindTooltip(acc.fullname + " (" + acc.rol + ")", {
                  permanent: false,
                  direction: 'top',
                  offset: [0, -10]
              });
          }
      });
  } else {
      Swal.fire({
          title: "Sin resultados",
          text: "No se encontraron accesos en el rango de fechas indicado.",
          icon: "info"
      });
  }
</script>

<?php include 'footer.php'; ?>
