   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->
  <%- include('../../partials/utils/mask.ejs') %>

<script src="/js/pagination.js"></script>

 

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

    <%- include('../../partials/utils/title.ejs', {title: "Courier Trips Manager"}) %>

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

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <%- include('../../partials/utils/export-buttons.ejs') %>
      <!-- Offcanvas for Search Filter Panel -->
      <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
        <button data-tooltip="Delete selected trips" id="deleteSelected" class="btn shadow btn-danger" style="padding-block: 6px;">
          <i class="fas fa-trash"></i>
        </button>
        <div style="display: flex; justify-content: end;">
          <%- include('../../partials/utils/searchFilter-withpreselect.ejs') %>
        </div>
      </div>
    </div>


    <div class="card basic-data-table" style="margin-top: 20px;">
      <div class="card-header">
        <h5 class="card-title mb-0">Total Courier Trips: <span id="totalRows"></span> </h5>
      </div>

      <%- include('../../partials/globalSearch.ejs') %>


      <!-- Responsive Table -->
      <div style="padding-inline: 20px; overflow-x: auto;">
        <div class="table-responsive bordered-table">
          <table id="tripsTable" class="table table-striped table-bordered">
            <thead>
              <tr>
                <th scope="col">
                  <div class="form-check style-check d-flex align-items-center">
                    <input id="selectAll" class="form-check-input" type="checkbox">
                  </div>
                </th>
                <th data-sort="trip_id">
                  ID
                  <span class="sort-icons">
                    <i class="fa fa-sort sort-neutral"></i>
                    <i class="fa fa-sort-up sort-asc"></i>
                    <i class="fa fa-sort-down sort-desc"></i>
                  </span>
                </th>

                <th>Trip Type</th>
                <th>Options</th>

                <th data-sort="user_id" onclick="pagination.setSort('user_id')">Passenger <span class="sort-icons">
                    <i class="fa fa-sort sort-neutral"></i>
                    <i class="fa fa-sort-up sort-asc"></i>
                    <i class="fa fa-sort-down sort-desc"></i>
                  </span></th>
                <th data-sort="driver_id" onclick="pagination.setSort('driver_id')">Driver <span class="sort-icons">
                    <i class="fa fa-sort sort-neutral"></i>
                    <i class="fa fa-sort-up sort-asc"></i>
                    <i class="fa fa-sort-down sort-desc"></i>
                  </span></th>
                <th data-sort="trip_date" onclick="pagination.setSort('trip_date')">Trip Date <span class="sort-icons">
                    <i class="fa fa-sort sort-neutral"></i>
                    <i class="fa fa-sort-up sort-asc"></i>
                    <i class="fa fa-sort-down sort-desc"></i>
                  </span></th>
                <th style="width: 300 !important">From Location</th>
                <th style="width: 300 !important">To Location</th>
                <th data-sort="trip_distance" onclick="pagination.setSort('trip_distance')">Distance <span class="sort-icons">
                    <i class="fa fa-sort sort-neutral"></i>
                    <i class="fa fa-sort-up sort-asc"></i>
                    <i class="fa fa-sort-down sort-desc"></i>
                  </span></th>
                <th data-sort="trip_pay_amount" onclick="pagination.setSort('trip_pay_amount')">Amount <span class="sort-icons">
                    <i class="fa fa-sort sort-neutral"></i>
                    <i class="fa fa-sort-up sort-asc"></i>
                    <i class="fa fa-sort-down sort-desc"></i>
                  </span></th>
                <th>Status</th>
                <th>Edit</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>


      <div class="pagination">
        <div id="pagination"></div>
      </div>

    </div>

</main>





<!-- Driver Assignment Modal -->
<div id="driverPopup" class="fixed flex inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-50">
  <div class="bg-white rounded-xl shadow-lg w-full max-w-md p-6 relative animate-fadeIn">
    <!-- Close Button -->
    <button type="button" class="absolute top-0 right-0 text-gray-500 hover:text-red-500 text-xl close">
      &times;
    </button>

    <h3 class="text-xl font-semibold mb-4 text-center">Assign Driver</h3>

    <form id="assignDriverForm" class="space-y-4">
      <input type="hidden" name="trip_id" id="popupTripId">

      <!-- Custom Searchable Dropdown -->
      <div>
        <label for="driverSearch" class="block text-sm font-medium text-gray-700 mb-1">Search Driver:</label>
        <input type="text" id="driverSearch" placeholder="Type to search driver..." class="w-full px-4 py-2 mb-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">

        <div id="driverDropdown" class="max-h-40 overflow-y-auto border border-gray-200 rounded-md shadow-sm bg-white">
          <!-- Drivers will be loaded here via JS -->
        </div>

      </div>

      <div class="text-center">
        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-medium  py-2 rounded-lg transition duration-200">
          Assign
        </button>
      </div>
    </form>
  </div>
</div>

<script>
   window.exportConfig = {
    csv: {
      headers: [
        "Trip ID", "Trip Type", "User Name", "Driver Name",
        "Trip Date", "From Location", "To Location",
        "Distance (km)", "Amount ($)", "Cancelled By", "Status"
      ],
      dataMapper: (trip) => [
        trip.trip_id,
        trip.trip_type === "delivery" ? "courier" : trip.trip_type,
        maskName(trip.user?.u_name || "N/A"),
        trip.driver ? maskName(trip.driver.d_name || "N/A") : "N/A",
        new Date(trip.trip_date).toLocaleString(),
        `"${trip.trip_from_loc}"`,
        `"${trip.trip_to_loc}"`,
        trip.trip_distance,
        trip.trip_pay_amount,
        trip.cancelled_by,
        trip.trip_status_name
      ],
      filename: 'trips.csv'
    },
    pdf: {
      headers: [
        "Trip ID", "Trip Type", "User Name", "Driver Name",
        "Trip Date", "From Location", "To Location",
        "Distance (km)", "Amount ($)", "Cancelled By", "Status"
      ],
      dataMapper: (trip) => [
        trip.trip_id,
        trip.trip_type === "delivery" ? "courier" : trip.trip_type,
        maskName(trip.user?.u_name || "N/A"),
        trip.driver ? maskName(trip.driver.d_name || "N/A") : "N/A",
        new Date(trip.trip_date).toLocaleString(),
        trip.trip_from_loc,
        trip.trip_to_loc,
        trip.trip_distance,
        trip.trip_pay_amount,
        trip.cancelled_by,
        trip.trip_status_name
      ],
      title: 'Trips Report',
      filename: 'trips.pdf'
    },
    fetchAllUrl: '/admin/getDevliveryTrips?limit=99999',
    currentData: []
  };

  window.globalSearchInput = '#globalSearch';

  const pagination = new Pagination({
    fetchUrl: '/admin/getDevliveryTrips',
    defaultSort: { column: 'trip_id', order: 'DESC' },
    dataMapper: (trip) => `
        <tr>
        <td>
          <div class="form-check style-check d-flex align-items-center">
            <input class="select-driver form-check-input selectRow" type="checkbox" value="${trip.trip_id}">
          </div>
        </td>
        <td>${trip.trip_id}</td>
        <td>${trip.trip_type == "normal" && trip.is_ride_later == 1 ? "scheduled ride" : trip.trip_type === "delivery"
        ? "courier" : trip.trip_type}</td>
        <td>
     <a  data-tooltip="Track trip" href="/admin/tracking/url/trips?trip_id=${trip.trip_id}"  target="_blank" class="text-blue-600 mr-3">
            <i class="fas fa-map-marker-alt"></i>
          </a>
          <a  data-tooltip="View trip chat" href="/admin/trips/chat/${trip.trip_id}" target="_blank" class="text-blue-600 mr-3">
            <i class="fas fa-comment-dots"></i>
          </a>
          ${
            trip.trip_status == "completed"
              ? `<a  data-tooltip="View invoice" href="/admin/invoice?trip_id=${trip.trip_id}" target="_blank" class="text-green-600">
                  <i class="fas fa-file-invoice"></i>
                 </a>`
              : ""
          }
        </td>
        <td>${maskName(trip.user?.u_name || "N/A")}</td>
        <td>
          ${
            !trip.driver || !trip.driver.d_name
              ? `<button class="add-driver-btn bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded-md shadow-md transition duration-200"
                  data-trip-id="${trip.trip_id}">Add Driver</button>`
              : maskName(trip.driver.d_name || "N/A")
          }
        </td>
        <td>${formatDate(trip.trip_date)}</td>
        <td style="width: 300px" class="textleft">${trip.trip_from_loc || trip.actual_from_loc}</td>
        <td style="width: 300px" class="textleft">${trip.trip_to_loc || trip.actual_to_loc}</td>
        <td>${trip.trip_distance} ${trip.trip_dunit}</td>
        <td>${trip.trip_currency}${trip.trip_pay_amount}</td>
        <td>${trip.trip_status == "completed" && trip.trip_pay_status == null ? "payment awaited" : trip.trip_status_name}</td>
        <td>
             <a href="/admin/trips/edit/${trip.trip_id}"  data-tooltip="Edit trip" class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
              <iconify-icon icon="lucide:edit"></iconify-icon>
            </a>
         </td>
      </tr>
    `
  });

 
  function showToast(message, type = 'success') {
    Swal.fire({
      toast: true,
      position: 'top-end',
      icon: type, // 'success', 'error', 'warning', etc.
      title: message,
      showConfirmButton: false,
      timer: 3000,
      timerProgressBar: true
    });
  }

  $(document).ready(function() {
    // Get reference to Bootstrap Offcanvas instance
    const filterOffcanvasEl = document.getElementById('filterOffcanvas');
    const filterOffcanvas = bootstrap.Offcanvas.getOrCreateInstance(filterOffcanvasEl);

    $(document).on('shown.bs.offcanvas hidden.bs.offcanvas', function() {
      const backdrops = $('.offcanvas-backdrop');
      if (backdrops.length > 1) {
        backdrops.slice(1).remove(); // Keep only one
      }
    });

    // When applying filters
    $("#applyFilters").click(function() {
      let filters = {};
      $("#searchForm").find("input, select").each(function() {
        const key = $(this).attr("name");
        const value = $(this).val().trim();
        if (value) filters[key] = value;
      });

      // Clear global search input
      $(window.globalSearchInput).val('');
      pagination.searchTerm = ''; // Clear global search term

      pagination.loadData(1, filters); // Apply filters
      filterOffcanvas.hide();
    });

    // Reset button
    $("#resetForm").click(function() {
      $("#searchForm")[0].reset();

      // Clear global search input
      $(window.globalSearchInput).val('');
      pagination.searchTerm = ''; // Clear global search term

      pagination.loadData(1, {}); // Reload with no filters
      filterOffcanvas.hide();
    });

    // Driver assignment functionality
    let selectedDriverId = null;

    document.getElementById('driverSearch').addEventListener('input', function() {
      const search = this.value.toLowerCase();
      document.querySelectorAll('.driver-option').forEach(opt => {
        const name = opt.textContent.toLowerCase();
        opt.style.display = name.includes(search) ? '' : 'none';
      });
    });

    document.querySelectorAll('.driver-option').forEach(opt => {
      opt.addEventListener('click', function() {
        const name = this.textContent;
        selectedDriverId = this.getAttribute('data-id');
        document.getElementById('driverSearch').value = name;
        document.getElementById('driverDropdown').classList.add('hidden');
      });
    });

    document.getElementById('driverSearch').addEventListener('focus', function() {
      document.getElementById('driverDropdown').classList.remove('hidden');
    });

    // Close modal
    document.querySelector('#driverPopup .close').addEventListener('click', () => {
      document.getElementById('driverPopup').classList.add('hidden');
    });

    // Fill trip_id and show modal
    $(document).on('click', '.add-driver-btn', function() {
      const tripId = $(this).attr('data-trip-id');
      document.getElementById('popupTripId').value = tripId;
      document.getElementById('driverPopup').classList.remove('hidden');
    });

    // Submit form
    document.getElementById('assignDriverForm').addEventListener('submit', function(e) {
      e.preventDefault();

      if (!selectedDriverId) {
        Swal.fire({
          icon: 'warning',
          title: 'No driver selected',
          text: 'Please choose a driver before submitting.'
        });
        return;
      }

      const tripId = document.getElementById('popupTripId').value;

      fetch('/admin/assign-driver', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            trip_id: tripId,
            driver_id: selectedDriverId
          })
        })
        .then(res => res.json())
        .then(data => {
          Swal.fire({
            icon: 'success',
            title: 'Driver Assigned',
            text: data.message,
            confirmButtonText: 'OK'
          }).then(() => location.reload());
        })
        .catch(err => {
          console.error(err);
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Something went wrong while assigning the driver.'
          });
        });
    });

    // Select/Deselect all checkboxes
    $("#selectAll").on("click", function() {
      $(".selectRow").prop("checked", this.checked);
    });

    // Delete single trip
    $(document).on('click', '.deleteSingle', function() {
      const tripId = $(this).data('id');

      Swal.fire({
        title: 'Delete Trip?',
        text: 'Are you sure you want to delete this trip?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: '/api/trips/' + tripId,
            type: 'POST',
            success: function() {
              showToast('Trip deleted successfully', "success");
              pagination.loadData(1);
            },
            error: function(xhr) {
              let errorMsg = 'Something went wrong!';
              if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMsg = xhr.responseJSON.message;
              } else if (xhr.responseText) {
                try {
                  const parsed = JSON.parse(xhr.responseText);
                  if (parsed.message) errorMsg = parsed.message;
                } catch (e) {
                  errorMsg = xhr.responseText;
                }
              }
              Swal.fire('Error!', errorMsg, 'error');
            }
          });
        }
      });
    });

    // Bulk delete selected trips
    $('#deleteSelected').on('click', function() {
      const selected = $('.selectRow:checked').map(function() {
        return $(this).val();
      }).get();

      if (selected.length === 0) {
        showToast('No trips selected', "error");
        return;
      }

      Swal.fire({
        title: 'Delete Selected Trips?',
        text: `You are about to delete ${selected.length} trip(s). This action cannot be undone.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete all'
      }).then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: '/admin/trips',
            method: 'POST',
            data: JSON.stringify({
              ids: selected
            }),
            contentType: 'application/json',
            success: function() {
              showToast('Selected trips deleted successfully', "success");
              pagination.loadData(1);
            },
            error: function(xhr) {
              let errorMsg = 'Something went wrong!';
              if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMsg = xhr.responseJSON.message;
              } else if (xhr.responseText) {
                try {
                  const parsed = JSON.parse(xhr.responseText);
                  if (parsed.message) errorMsg = parsed.message;
                } catch (e) {
                  errorMsg = xhr.responseText;
                }
              }
              Swal.fire('Error!', errorMsg, 'error');
            }
          });
        }
      });
    });

    function fetchDriverList() {
      fetch('/admin/active/driver/options?d_active=1&is_delete=0&d_is_available=1&d_is_verified=1') // Adjust the API path as per your backend
        .then(res => res.json())
        .then(drivers => {
          const dropdown = document.getElementById('driverDropdown');
          dropdown.innerHTML = ''; // Clear old content

          drivers.data.forEach(driver => {
            const div = document.createElement('div');
            div.className = 'driver-option px-4 py-2 hover:bg-blue-100 cursor-pointer';
            div.setAttribute('data-id', driver.driver_id);
            div.textContent = `(${driver.driver_id}) ${driver.d_name}`;
            dropdown.appendChild(div);
          });

          // Attach click listeners again after rendering
          document.querySelectorAll('.driver-option').forEach(opt => {
            opt.addEventListener('click', function() {
              const name = this.textContent;
              selectedDriverId = this.getAttribute('data-id');
              document.getElementById('driverSearch').value = name;
              dropdown.classList.add('hidden');
            });
          });
        })
        .catch(err => {
          console.error('Failed to fetch drivers:', err);
        });
    }

    $(document).on('click', '.add-driver-btn', function() {
      const tripId = $(this).attr('data-trip-id');
      document.getElementById('popupTripId').value = tripId;
      document.getElementById('driverPopup').classList.remove('hidden');
      fetchDriverList(); // Fetch drivers when opening modal
    });

    // Initial load
    pagination.loadData(1);
  });
</script>

<%- footer %>