<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GPS Tracking</title>
  <style>
   /* ✅ General Styles */
body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
    background: #f4f4f4;
    color: #333;
    text-align: center;
}

/* ✅ Main Container */
.container {
    display: flex;
    max-width:100%;
    margin: 5px auto;
    padding: 2px;
    background: white;
    border-radius: 10px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}

/* ✅ Title */
h1 {
    font-size: 24px;
    margin-bottom: 2px;
    color: #444;
}

/* ✅ Tracking Sessions */
#sessionList {
    display: grid;
    grid-template-columns: 1fr; /* Only one column */
    gap: 15px;
    max-width: 300px;
    margin: 10px auto;
    padding: 10px;
    height: 500px;
    overflow-y: scroll;
}

.delete-button {
            background-color: #dc3545; /* Red */
            color: #fff;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 11px;
            cursor: pointer;
            width: 60px;
        }


/* ✅ Session Item Card */
.session-item {
    background: #fff;
    padding: 5px;
    border-radius: 10px;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
    cursor: pointer;
    border-left: 5px solid #007bff;
}

/* ✅ Hover Effect */
.session-item:hover {
    transform: translateY(-3px);
    box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.15);
}

/* ✅ Session Text */
.session-item span {
    display: block;
    font-size: 14px;
    color: #666;
}

/* ✅ User Name */
.session-item strong {
    font-size: 16px;
    color: #333;
}

/* ✅ Map Display */
#map {
    width: 100%;
    height: 500px;
    border-radius: 10px;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}


.container2 {
    display: grid;
    grid-template-columns: 300px 1fr; /* First column is 150px, second column takes the rest */
    gap: 15px;
  width: 100%;
    margin: 2px auto;
    padding: 10px;
}

.mapcard{
width: 100%;
    background: #fff;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
    cursor: pointer;
    
}
   
  </style>
</head>
<body>

    <div class="container">
        <div>
            <h1>📍 GPS Tracking System</h1>
        </div>
     
        
       <div class="container2">

        <div id="sessionList" class="session-grid"></div> <!-- ✅ Updated to grid layout -->
    <div class="mapcard">

       
        <div id="map"></div>
    </div>
       
</div>
    </div>
    

  <script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCauv80CxhP1ZUvXkbQcbstbdQDChQxLqU&callback=initMap" async defer></script>
 
  <script>
      let map;
      let markers = { start: null, end: null, current: null };
      let trackingPolyline = null;

      function initMap() {
          map = new google.maps.Map(document.getElementById("map"), {
              zoom: 13,
              center: { lat: 9.045, lng: 38.744 } // Default center
          });

          fetchTrackingSessions(); // Fetch list of user tracking sessions
      }

   
      function fetchTrackingSessions() {
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 1); // Get yesterday's date
    const endDate = new Date(); // Get today's date

    const startDateString = startDate.toISOString().split('T')[0];
    const endDateString = endDate.toISOString().split('T')[0];

    fetch(`/api/gps/ss?startDate=${startDateString}&endDate=${endDateString}`)
        .then(response => response.json())
        .then(data => {
            if (data.sessions && data.sessions.length > 0) {
                displaySessions(data.sessions);
            } else {
                document.getElementById("sessionList").innerHTML = "<p>No tracking sessions found.</p>";
            }
        })
        .catch(error => console.error("❌ Error fetching sessions:", error));
}




      function displaySessions(sessions) {
    const sessionListDiv = document.getElementById("sessionList");
    sessionListDiv.innerHTML = ""; // Clear existing list

    sessions.forEach(session => {
        const startTimeFormatted = new Date(session.startTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        const endTimeFormatted = new Date(session.endTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

        const sessionDiv = document.createElement("div");
sessionDiv.classList.add("session-item");

sessionDiv.innerHTML = `
    <strong>👤 ${session.userName}</strong>
    <span>📅 From: ${startTimeFormatted} ⏩ To: ${endTimeFormatted}</span>
    <button class="delete-button" data-session-id="${session.trackingSessionId}">🗑️ Delete</button>
`;

sessionDiv.onclick = () => fetchTrackingHistory(session.userId, session.trackingSessionId);
sessionListDiv.appendChild(sessionDiv);

// Add event listener for delete button separately
const deleteButton = sessionDiv.querySelector('.delete-button');
deleteButton.addEventListener('click', (event) => {
    event.stopPropagation(); // Prevent the click from triggering the sessionDiv onclick
    const sessionId = event.target.getAttribute('data-session-id');
    deleteSession(sessionId);
});

   
   
    });
}
async function deleteSession(trackingSessionId) {
    if (confirm('Are you sure you want to delete this tracking session?')) {
        try {
            const response = await fetch(`/api/gps/delete/${trackingSessionId}`, { method: 'DELETE' });
            const data = await response.json();
            if (data.message) {
                await fetchTrackingSessions(); // Refresh the session list
                alert(`✅ ${data.message}`);
            } else {
                alert('❌ Error deleting session');
            }
        } catch (error) {
            console.error('❌ Error deleting session:', error);
            alert('❌ Error deleting session');
        }
    }
}




      function fetchTrackingHistory(userId, trackingSessionId) {
          fetch(`/api/gps/location/history/${userId}/${trackingSessionId}`)
              .then(response => response.json())
              .then(data => {
                  if (data.path && data.path.length > 1) {
                      plotTrackingPath(data);
                  } else {
                      console.error("❌ Not enough data points to plot a path.");
                  }
              })
              .catch(error => console.error("❌ Error fetching tracking history:", error));
      }

      function plotTrackingPath(session) {
          const startPoint = { lat: session.startPoint.latitude, lng: session.startPoint.longitude };
          const endPoint = { lat: session.endPoint.latitude, lng: session.endPoint.longitude };
          const pathCoordinates = session.path.map(point => ({ lat: point.latitude, lng: point.longitude }));

          // Remove existing markers and polylines if any
          if (markers.start) markers.start.setMap(null);
          if (markers.end) markers.end.setMap(null);
          if (trackingPolyline) trackingPolyline.setMap(null);

          // Start Marker (Green)
          markers.start = new google.maps.Marker({
              position: startPoint,
              map: map,
              title: "Start Point",
              icon: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
          });

          // End Marker (Red)
          markers.end = new google.maps.Marker({
              position: endPoint,
              map: map,
              title: "End Point",
              icon: "http://maps.google.com/mapfiles/ms/icons/red-dot.png",
          });

          // Draw the full tracking path (Blue)
          trackingPolyline = new google.maps.Polyline({
              path: pathCoordinates,
              geodesic: true,
              strokeColor: "#0000FF", // Blue path
              strokeOpacity: 1.0,
              strokeWeight: 3,
          });

          trackingPolyline.setMap(map);
          map.setCenter(startPoint);
      }
  </script>

</body>
</html>
