<%- 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: "Recurring Trips Manager"}) %>

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

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>
    
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <%- include('../../partials/utils/export-buttons.ejs') %>
      <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 Recurring 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>Recurring ID</th>
                <th>Weekdays</th>
                <th>Members</th>
                <th>Category</th>
                <th data-sort="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">
                  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">
                  Trip Date & Time
                  <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: 300px !important">From Location</th>
                <th style="width: 300px !important">To Location</th>
                <th>Actions</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: [
        "Recurring ID", "Category", "Weekdays", "User Name", "User Email", "User Phone",
        "Driver Name", "Driver Email", "Driver Phone", "Trip Date & Time", "From Location", 
        "To Location"
      ],
      dataMapper: (trip) => [
        trip.recurring_trip_id,
        trip.cat_name || "N/A",
        trip.weekdays || "N/A",
        maskName(trip.user?.u_name || "N/A"),
        trip.user?.u_email || "N/A",
        trip.user?.c_code ? `${trip.user.c_code} ${maskPhone(trip.user.u_phone || "N/A")}` : maskPhone(trip.user?.u_phone || "N/A"),
        trip.driver ? maskName(trip.driver.d_name || "N/A") : "N/A",
        trip.driver?.d_email || "N/A",
        trip.driver?.c_code ? `${trip.driver.c_code} ${maskPhone(trip.driver.d_phone || "N/A")}` : maskPhone(trip.driver?.d_phone || "N/A"),
        trip.formatted_trip_date || new Date(trip.trip_date).toLocaleString(),
        `"${trip.trip_from_loc}"`,
        `"${trip.trip_to_loc}"`
      ],
      filename: 'recurring_trips.csv'
    },
    pdf: {
      headers: [
        "Recurring ID", "Category", "Weekdays", "User Name", "User Email", "User Phone",
        "Driver Name", "Driver Email", "Driver Phone", "Trip Date & Time", "From Location", 
        "To Location"
      ],
      dataMapper: (trip) => [
        trip.recurring_trip_id,
        trip.cat_name || "N/A",
        trip.weekdays || "N/A",
        maskName(trip.user?.u_name || "N/A"),
        trip.user?.u_email || "N/A",
        trip.user?.c_code ? `${trip.user.c_code} ${maskPhone(trip.user.u_phone || "N/A")}` : maskPhone(trip.user?.u_phone || "N/A"),
        trip.driver ? maskName(trip.driver.d_name || "N/A") : "N/A",
        trip.driver?.d_email || "N/A",
        trip.driver?.c_code ? `${trip.driver.c_code} ${maskPhone(trip.driver.d_phone || "N/A")}` : maskPhone(trip.driver?.d_phone || "N/A"),
        trip.formatted_trip_date || new Date(trip.trip_date).toLocaleString(),
        trip.trip_from_loc,
        trip.trip_to_loc
      ],
      title: 'Recurring Trips Report',
      filename: 'recurring_trips.pdf'
    },
    fetchAllUrl: '/admin/getRecurringTrips?limit=99999',
    currentData: []
  };

  window.globalSearchInput = '#globalSearch';

  const pagination = new Pagination({
    fetchUrl: '/admin/getRecurringTrips',
    defaultSort: { column: 'recurring_trip_id', order: 'DESC' },
    dataMapper: (trip) => {
      const userPhone = trip.user?.c_code 
        ? `${trip.user.c_code} ${maskPhone(trip.user.u_phone || "N/A")}` 
        : maskPhone(trip.user?.u_phone || "N/A");
      
      const driverPhone = trip.driver?.c_code 
        ? `${trip.driver.c_code} ${maskPhone(trip.driver.d_phone || "N/A")}` 
        : maskPhone(trip.driver?.d_phone || "N/A");

      // Check if recurring trip is active
      const isRecurringActive = trip.recurringTrip?.is_active === 1;

      // Generate weekday badges
      const weekDays = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
      const weekDaysFull = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
      const activeIndices = trip.weekday_indices || [];
      
      const weekdayBadges = weekDays.map((day, index) => {
        const isActive = activeIndices.includes(index);
        const badgeClass = isActive ? 'bg-primary text-white' : 'bg-secondary text-white';
        const opacity = isActive ? '1' : '0.3';
        return `<span class="badge ${badgeClass}" style="opacity: ${opacity}; margin: 2px; min-width: 28px;" title="${weekDaysFull[index]}">${day}</span>`;
      }).join('');

      return `
        <tr>
    
          <td>
            <span class="badge bg-info">${trip.recurring_trip_id}</span>
            ${isRecurringActive 
              ? '<span class="badge bg-success ms-1" style="font-size: 0.7rem;">Active</span>' 
              : '<span class="badge bg-secondary ms-1" style="font-size: 0.7rem;">Inactive</span>'}
          </td>
          <td>
            <div style="display: flex; flex-wrap: wrap; gap: 2px;">
              ${weekdayBadges}
            </div>
          </td>
          <td>
            <a href="/admin/trip-members?trip_id=${trip.trip_id}" class="btn btn-sm btn-primary">
              <i class="fas fa-users"></i> View Members
            </a>
          </td>
          <td>
            <div style="display: flex; flex-wrap: wrap; gap: 2px;">
              ${trip.cat_name || "N/A"}
            </div>
          </td>
          <td>
            <div>
              <strong>${maskName(trip.user?.u_name || "N/A")}</strong><br>
              <small class="text-muted">${trip.user?.u_email || "N/A"}</small><br>
              <small class="text-muted">${userPhone}</small>
            </div>
          </td>
          <td>
           
                    <strong>${trip.driver ? maskName(trip.driver.d_name || "N/A") : "N/A"}</strong><br>
                    <small class="text-muted">${trip.driver?.d_email || "N/A"}</small><br>
                    <small class="text-muted">${trip.driver ? driverPhone : "N/A"}</small>
                   </div>
          </td>
          <td>${trip.formatted_trip_date || formatDate(trip.trip_date)}</td>
          <td style="width: 300px" class="textleft">${trip.trip_from_loc || trip.actual_from_loc || "N/A"}</td>
          <td style="width: 300px" class="textleft">${trip.trip_to_loc || trip.actual_to_loc || "N/A"}</td>
          <td>
            ${
              isRecurringActive
                ? `<button class="cancel-recurring-btn btn btn-sm btn-danger" 
                    data-recurring-id="${trip.recurring_trip_id}"
                    data-trip-id="${trip.trip_id}">
                    Cancel
                   </button>`
                : `<span class="badge bg-secondary">Cancelled</span>`
            }
          </td>
        </tr>
      `;
    }
  });

  function formatDate(dateString) {
    if (!dateString) return "N/A";
    const date = new Date(dateString);
    return date.toLocaleString();
  }

  $(document).ready(function() {
    pagination.loadData(1);

    // Filter functionality
    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();
      }
    });

    $("#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;
      });

      $(window.globalSearchInput).val('');
      pagination.searchTerm = '';

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

    $("#resetForm").click(function() {
      $("#searchForm")[0].reset();
      $(window.globalSearchInput).val('');
      pagination.searchTerm = '';
      pagination.loadData(1, {});
      filterOffcanvas.hide();
    });

    // Cancel recurring trip handler
    $(document).on('click', '.cancel-recurring-btn', function() {
      const recurringId = $(this).data('recurring-id');
      const tripId = $(this).data('trip-id');
      
      Swal.fire({
        title: 'Cancel Recurring Trip?',
        text: 'This will make the recurring trip inactive and cancel all future trips.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, cancel it!',
        cancelButtonText: 'No, keep it'
      }).then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: '/admin/cancel-recurring-trip',
            method: 'POST',
            data: { recurring_trip_id: recurringId },
            success: function(response) {
              if (response.success) {
                pagination.loadData(pagination.currentPage);
                Swal.fire('Cancelled!', response.message || 'Recurring trip has been cancelled.', 'success');
              } else {
                Swal.fire('Error!', response.message || 'Failed to cancel recurring trip.', 'error');
              }
            },
            error: function(xhr) {
              const errorMessage = xhr.responseJSON?.message || 'An error occurred while cancelling the recurring trip.';
              Swal.fire('Error!', errorMessage, 'error');
            }
          });
        }
      });
    });

    // 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');
    });

    // Submit driver assignment 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(() => {
            document.getElementById('driverPopup').classList.add('hidden');
            pagination.loadData(pagination.currentPage);
          });
        })
        .catch(err => {
          console.error(err);
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Something went wrong while assigning the driver.'
          });
        });
    });

    function fetchDriverList() {
      fetch('/admin/active/driver/options?d_active=1&is_delete=0&d_is_available=1&d_is_verified=1')
        .then(res => res.json())
        .then(drivers => {
          const dropdown = document.getElementById('driverDropdown');
          dropdown.innerHTML = '';

          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 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();
    });

    // Delete selected trips
    $('#deleteSelected').click(function() {
      const selectedTrips = $('.select-trip:checked').map(function() {
        return $(this).val();
      }).get();
      
      if (selectedTrips.length === 0) {
        Swal.fire('Warning!', 'Please select trips to delete.', 'warning');
        return;
      }
      
      Swal.fire({
        title: 'Are you sure?',
        text: `You are about to delete ${selectedTrips.length} trip(s). This action cannot be undone!`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete them!',
        cancelButtonText: 'Cancel'
      }).then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: '/admin/trips',
            method: 'POST',
            data: { trip_id: selectedTrips },
            success: function(response) {
              if (response.success) {
                pagination.loadData(pagination.currentPage);
                Swal.fire('Deleted!', response.message || 'Trips have been deleted.', 'success');
                $('#selectAll').prop('checked', false);
              } else {
                Swal.fire('Error!', response.message || 'Failed to delete trips.', 'error');
              }
            },
            error: function(xhr) {
              const errorMessage = xhr.responseJSON?.message || 'An error occurred while deleting trips.';
              Swal.fire('Error!', errorMessage, 'error');
            }
          });
        }
      });
    });

    // Select all checkbox
    $('#selectAll').change(function() {
      $('.select-trip').prop('checked', $(this).is(':checked'));
    });
  });
</script>

<%- footer %>
