   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->
 
<script src="/js/pagination.js"></script>

<style>
  tr,
  td,
  th {
    border: 1px solid #dcdcdc !important
  }
</style>
<% 
  const isMasking = typeof enableMasking !== "undefined" ? enableMasking : true;

  function maskName(name) {
    if (!name) return "N/A";
    if (!isMasking) return name;
    return name.substring(0, 3) + "***";
  }

  function maskEmail(email) {
    if (!email) return "N/A";
    if (!isMasking) return email;

    const parts = email.split("@");
    if (parts.length < 2) return email;

    const user = parts[0].slice(0, 2) + "***";
    const domain = "******." + parts[1].split(".").pop();
    return user + "@" + domain;
  }

  function maskPhone(phone) {
    if (!phone) return "N/A";
    if (!isMasking) return phone;

    const visible = phone.slice(0, 2);
    const masked = "*".repeat(phone.length - 2);
    return visible + masked;
  }
%>
 

  <div class="container flex-1 pt-20 w-full my-4">

    <%- include('../../partials/utils/title.ejs', {title: "Driver Detailed Report"}) %>

    <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: "Driver Detailed Report" }
    ];
  %>

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

    <div class="mt-4">

      <div class="p-4 bg-white shadow-md rounded-lg">


        <div class="overflow-x-auto ">
          <div class="card  ">
            <div class="card-header">
              <h4 class="text-lg font-semibold" class="text-lg font-semibold" class="mb-0">Driver Overview</h4>
            </div>
            <div class="card-body">

              <!-- Profile & Car Info -->
              <table class="table table-bordered">
                <tbody>
                  <tr>
                    <th>Full Name</th>
                    <td><%= driver?.driver_id %> - <%= maskName(driver?.d_name) %>                    
                    </td>
                    <th>Profile Image</th>

                    <td>
                      <div class="d-flex align-items-center">
                        <img src="<%= IMAGE_FOLDER_PATH%><%= driver?.image?.img_path %>" alt="Profile Image" class="pi-css rounded-circle me-2" width="40" height="40" onerror="this.onerror=null; this.src='/placeholder.jpg';">
                        <div>
                    </td>
                  </tr>
                  <tr>
                    <th>Vehicle Name</th>
                    <td><%= car?.car_name || "N/A" %></td>
                    <th>Vehicle Reg. No</th>
                    <td><%= car?.car_reg_no || "N/A" %></td>
                  </tr>
                  <tr>
                    <th>Vehicle Model</th>
                    <td><%= car?.car_model || "N/A" %></td>
                    <th>Vehicle Make</th>
                    <td><%= car?.car_make || "N/A" %></td>
                  </tr>

                  <tr>
                    <th>Wallet Amount</th>
                    <td colspan="3" style="color:<%= driver?.d_wallet < 0 ? 'red' : 'green' %>"><%=city_cur %><%= (driver?.d_wallet || 0)?.toFixed(2) %></td>
                  </tr>
                </tbody>
              </table>
            </div>

              <!-- Ride Summary -->
              <h4 class="text-lg font-semibold" class="mt-4" style="padding-left: 25px;">Ride Summary</h4>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table basic-border-table mb-0">
                    <tbody>
                      <tr>
                        <th>Total Number of Rides</th>
                        <td><%= totalRides %></td>
                        <th>Last Time Connected</th>
                        <td><%= lastRide %></td>
                      </tr>
                      <tr>
                        <th>Total Amount of All Rides</th>
                        <td colspan="3"><%=city_cur %><%= totalAmount?.toFixed(2) %></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <!-- Payment Breakdown -->
              <h4 class="text-lg font-semibold" class="mt-4" style="padding-left: 25px;">Ride Payment Mode Breakdown</h4>

              <div class="card-body">
                <div class="table-responsive">
                  <table class="table basic-border-table mb-0">
                    <thead class="table-light">
                      <tr>
                        <th>Mode</th>
                        <th>#Rides</th>
                        <th>Amount</th>
                      </tr>
                    </thead>
                    <tbody>
                      <% ['CASH', 'WALLET', 'CARD'].forEach(mode => { %>
                      <tr>
                        <td><%= mode %></td>
                        <td><%= paymentStats[mode]?.rides %></td>
                        <td><%=city_cur %><%= paymentStats[mode]?.amount.toFixed(2) %></td>
                      </tr>
                      <% }) %>
                      <tr class="table-light fw-bold">
                        <td>Total of rides PROMO code applied on the rides fees</td>
                        <td><%= promoStats?.rides %></td>
                        <td><%=city_cur %><%= promoStats.amount?.toFixed(2) %></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <!-- Cancellation Info -->
              <h4 class="text-lg font-semibold" class="mt-4" style="padding-left: 25px;">Cancellation Stats</h4>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table basic-border-table mb-0">
                    <tbody>
                      <tr>
                        <th>Cancelled Rides (by Driver)</th>
                        <td><%= cancelledByDriver %></td>
                      </tr>
                      <tr>
                        <th>Cancelled at Pickup (by User)</th>
                        <td><%= cancelledByUser %></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <!-- Other Insights -->
              <h4 class="text-lg font-semibold" class="mt-4" style="padding-left: 25px;">Insights</h4>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table basic-border-table mb-0">
                    <tbody>
                      <tr>
                        <th>Most Frequent Rider</th>
                        <td><%= mostFrequentRider %></td>
                      </tr>
                      <tr>
                        <th>Total Rides</th>
                        <td><%= totalRides %></td>
                      </tr>
                      <tr>
                        <th>Avg. Waiting Time at Pickup</th>
                        <td><%= avgWaitingTime %></td>
                      </tr>
                      <tr>
                        <th>Average Rating</th>
                        <td><%= avgRating %></td>
                      </tr>
                      <tr>
                        <th>Total Rating</th>
                        <td>
                          <% 
                            const rating = parseFloat(driver?.d_rating || 0); 
                            const fullStars = Math.floor(rating);
                            const halfStar = rating % 1 >= 0.5;
                            const emptyStars = 5 - fullStars - (halfStar ? 1 : 0);
                          %>

                          <% for(let i = 0; i < fullStars; i++) { %>
                          <i class="fa fa-star text-warning"></i>
                          <% } %>

                          <% if(halfStar) { %>
                          <i class="fa fa-star-half-alt text-warning"></i>
                          <% } %>

                          <% for(let i = 0; i < emptyStars; i++) { %>
                          <i class="fa fa-star text-secondary"></i>
                          <% } %>

                          <br />
                          <span><%= rating?.toFixed(2) %> / 5</span><br />
                          <span>Total Ratings: <%= driver?.d_rating_count || 0 %></span>
                        </td>
                      </tr>

                      <tr>
                        <th>Least & Most Expensive Rides</th>
                        <td>MinAmt: <%=city_cur %><%= minAmount?.toFixed(2) %> | MaxAmt: <%=city_cur %><%= maxAmount?.toFixed(2) %></td>
                      </tr>
                      <tr>
                        <th>Best Location (by Distance)</th>
                        <td><%= bestLocation %></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
          </div>

        </div>

      </div>

      <div class="  bg-white shadow-md rounded-lg mt-6" style="padding: 20px;">
        <h4 class="text-lg font-semibold" class="text-lg font-semibold">Total of distance by km done by this drivers will drop a rider: </h4>

        <div class="overflow-x-auto mt-6">

          <form method="get" class="row g-2 mb-3">
            <input type="hidden" name="driver_id" value="<%= driver.driver_id %>">
            <div class="col-md-3">
              <label>Search By From:</label>
              <input type="date" name="from_date" class="form-control" value="<%= from_date || '' %>">
            </div>
            <div class="col-md-3">
              <label>Search By To:</label>
              <input type="date" name="to_date" class="form-control" value="<%= to_date || '' %>">
            </div>
            <div class="col-md-2 align-self-end">
              <button type="submit" class="btn btn-primary w-100">Search</button>
            </div>
          </form>

          <div class="card-body">
            <div class="table-responsive">
              <table class="table basic-border-table mb-0">
                <thead class="table-light text-center">
                  <tr>
                    <th>No. of Trips</th>
                    <th>Total Distance (km)</th>
                    <th>Total Fare</th>
                    <th>Driver Earning</th>
                  </tr>
                </thead>
                <tbody class="text-center">
                  <tr>
                    <td><%= tripCount %></td>
                    <td><%= totalDistance?.toFixed(2) %></td>
                    <td><%=city_cur %><%= totalFare?.toFixed(2) %></td>
                    <td><%=city_cur %><%= driverEarnings %></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>


      </div>
      <div class="bg-white shadow-md rounded-lg mt-6" style="padding: 20px;">
        <h4 class="text-lg font-semibold">Best Location (Avg. Based on Distance)</h4>

        <div class="overflow-x-auto mt-6">
          <div id="map" style="height: 400px; width: 100%;" class="mb-4"></div>
        </div>


      </div>
    </div>
  </div>
</main>

 
<script>
  function initMap() {
    let avgLat = <%= avgLat %>;
    let avgLng = <%= avgLng %>;

    // If lat/lng are zero or invalid, fallback to browser geolocation
    if (!avgLat || !avgLng || (avgLat === 0 && avgLng === 0)) {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const userLocation = {
              lat: position.coords.latitude,
              lng: position.coords.longitude,
            };

            const map = new google.maps.Map(document.getElementById("map"), {
              center: userLocation,
              zoom: 12,
            });

            // No marker in this case
          },
          (error) => {
            console.error("Geolocation failed:", error);
            // Fallback to default coordinates
            const defaultLocation = { lat: 0, lng: 0 };
            const map = new google.maps.Map(document.getElementById("map"), {
              center: defaultLocation,
              zoom: 2,
            });
          }
        );
      } else {
        console.warn("Geolocation not supported by browser.");
        const defaultLocation = { lat: 0, lng: 0 };
        const map = new google.maps.Map(document.getElementById("map"), {
          center: defaultLocation,
          zoom: 2,
        });
      }
    } else {
      const avgLocation = { lat: avgLat, lng: avgLng };

      const map = new google.maps.Map(document.getElementById("map"), {
        center: avgLocation,
        zoom: 12,
      });

      const marker = new google.maps.Marker({
        position: avgLocation,
        map,
        title: "Average Best Location",
      });

      // Create info window for address display
      const infoWindow = new google.maps.InfoWindow({
        content: '<div style="padding: 10px;"><strong>Loading address...</strong></div>',
      });

      // Add click listener to marker
      marker.addListener("click", () => {
        // Show loading state
        infoWindow.setContent('<div style="padding: 10px;"><strong>Loading address...</strong></div>');
        infoWindow.open(map, marker);

        // Reverse geocode to get address
        const geocoder = new google.maps.Geocoder();
        geocoder.geocode({ location: avgLocation }, (results, status) => {
          if (status === "OK" && results[0]) {
            const address = results[0].formatted_address;
            infoWindow.setContent(`
              <div style="padding: 10px; max-width: 300px;">
                <h6 style="margin: 0 0 8px 0; font-weight: 600; color: #1f2937;">Average Best Location</h6>
                <p style="margin: 0; font-size: 14px; color: #4b5563;">
                  <i class="fas fa-map-marker-alt" style="color: #ef4444; margin-right: 5px;"></i>
                  ${address}
                </p>
                <p style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;">
                  <strong>Coordinates:</strong> ${avgLat.toFixed(6)}, ${avgLng.toFixed(6)}
                </p>
              </div>
            `);
          } else {
            infoWindow.setContent(`
              <div style="padding: 10px; max-width: 300px;">
                <h6 style="margin: 0 0 8px 0; font-weight: 600; color: #1f2937;">Average Best Location</h6>
                <p style="margin: 0; font-size: 14px; color: #4b5563;">
                  <i class="fas fa-map-marker-alt" style="color: #ef4444; margin-right: 5px;"></i>
                  Address not available
                </p>
                <p style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;">
                  <strong>Coordinates:</strong> ${avgLat.toFixed(6)}, ${avgLng.toFixed(6)}
                </p>
              </div>
            `);
          }
        });
      });
    }
  }
</script>

<!-- Load Google Maps JS API -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<%= GoogleMapsAPIKey %>&callback=initMap">
</script>


<%- footer %>