<?php
session_start();

require_once("connection_sql.php");
?>

<head>
    <!-- Add Leaflet CSS & JS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.1/dist/leaflet.markercluster.css" />
    <script src="https://unpkg.com/leaflet.markercluster@1.5.1/dist/leaflet.markercluster.js"></script>
</head>

<style>
    hr {
        margin-top:5px !important;
        margin-bottom:5px !important;
    }
    body {
    overflow: hidden;
    height: 100%;
}
</style>

<body>
    <div class="container mt-5" style="padding-top:30px">
        <div class="card shadow">
            <div class="card-body">
                

                <div class="row justify-content-center" style="padding-top:20px">
                    <div class="col-md-4">
                        <label for="start_date">Start Date</label>
                        <input type="date" id="start_date" class="form-control" onchange="fetchLocations()">
                    </div>
                    <div class="col-md-4">
                        <label for="end_date">End Date</label>
                        <input type="date" id="end_date" class="form-control" onchange="fetchLocations()">
                    </div>

                    <div class="col-md-4">
                        <label for="user_select">Select User</label>
                        <select id="user_select" class="form-control" onchange="fetchLocations()">
                            <option value="">Select User</option>
                            <?php
                            require_once("connection_sql.php");
                            $sql = "SELECT user_name FROM user_mast";
                            $result = $conn->query($sql);
                            while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
                                echo '<option value="' . htmlspecialchars($row['user_name']) . '">' . htmlspecialchars($row['user_name']) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="container mt-5" style="padding-top:30px">
        <div class="col-md-12">
            <div id="map" style="height: 500px; width: 100%; margin-top: 20px;"></div>
        </div>
    </div>

    <script>
    
    
let map;
let markersLayer;

function initializeMap() {
    if (!map) {
        map = L.map('map').setView([7.8731, 80.7718], 8); // Set initial center and zoom level
    }

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    
    markersLayer = L.layerGroup();
    markersLayer.addTo(map);
}

function fetchLocations() {
    let startDate = document.getElementById("start_date").value;
    let endDate = document.getElementById("end_date").value;
    let userName = document.getElementById("user_select").value;

    if (!startDate || !endDate || !userName) {
        console.warn("Please select both start and end dates and a user.");
        return;
    }

    $.ajax({
        url: "location_report_data.php",
        type: "POST",
        data: {
            start_date: startDate,
            end_date: endDate,
            user_name: userName
        },
        dataType: "json",
        success: function(response) {
            if (response.status === "success") {
                displayLocationsOnMap(response.data);
            } else {
                alert("No locations found for the selected date range.");
                displayLocationsOnMap([]);
            }
        },
        error: function(xhr, status, error) {
            console.error("Error fetching location data:", error);
        }
    });
}
 
 function displayLocationsOnMap(locations) {
    if (!map) {
        initializeMap();
    }

  
    markersLayer.clearLayers();

    if (locations.length === 0) {
        console.warn("No location data available.");
        return;
    }

    
    let locationGroups = {};
    const roundingPrecision = 5;  

    locations.forEach(location => {
        let lat = parseFloat(location.latitude);
        let lon = parseFloat(location.longitude);

        if (isNaN(lat) || isNaN(lon)) {
            console.warn("Invalid coordinates:", location);
            return;
        }

      
        lat = lat.toFixed(roundingPrecision);
        lon = lon.toFixed(roundingPrecision);

       
        let key = lat + ',' + lon;
        if (!locationGroups[key]) {
            locationGroups[key] = [];
        }
        locationGroups[key].push(location);
    });

    let latLngs = []; 

    for (let key in locationGroups) {
        let group = locationGroups[key];
        let [baseLat, baseLng] = key.split(',').map(Number);
        latLngs.push([baseLat, baseLng]);

         
        let popupContent = `<b>${group.length} logins at this location:</b><br>`;
        
        
        group.forEach((loc, index) => {
            popupContent += `<hr><b>User ${index + 1}:</b> ${loc.user_name}<br>`;
            popupContent += `<b>Timestamp:</b> <span style="color:red">${loc.created_at}</span><br>`;
        });

     
        let html = `
          <div style="position: relative; display: inline-block;">
              <img src="https://cdn-icons-png.flaticon.com/128/684/684908.png" style="width:30px;height:30px;">
              <div style="
                  position: absolute;
                  top: -8px;
                  right: -8px;
                  background: red;
                  color: white;
                  border-radius: 50%;
                  width: 20px;
                  height: 20px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-size: 12px;
              ">${group.length}</div>
          </div>`;

        let customIcon = L.divIcon({
            html: html,
            className: "", 
            iconSize: [30, 30]
        });

        let marker = L.marker([baseLat, baseLng], { icon: customIcon })
            .bindPopup(popupContent);

        markersLayer.addLayer(marker);
    }

    if (latLngs.length === 1) {
        map.setView(latLngs[0], 15);
    } else {
        map.fitBounds(latLngs);
    }
}


document.addEventListener("DOMContentLoaded", function() {
    initializeMap();
});


    </script>

</body>
