<%- include('../../layouts/head.ejs') %>



<style>
  .strikethrough-red {
    color: red;
    text-decoration: line-through;
  }
</style>

<%- include('../../layouts/header.ejs') %>
<main class="dashboard-main bg-gray-50">
  <%- include('../../layouts/navbar.ejs') %>

  <div class="container mx-auto   py-6">

    <%- include('../../partials/utils/title.ejs', {title: "Trip Edit Manager"}) %>
    <% 
          const breadcrumbs = [
            { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
            { label: "Trip Manager", href: "/admin/trips" },
            { label: "Trip Edit Manager" }
          ];
        %>
    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>


    <!-- Main Form Card -->
    <div class="bg-white rounded-xl shadow-md overflow-hidden">
      <!-- Card Header -->
      <div class="bg-gradient-to-r from-blue-600 to-blue-800 px-6 py-4">
        <div class="flex items-center">
          <i class="fas fa-info-circle text-white mr-2 text-xl"></i>
          <h2 class="text-xl font-semibold text-white">Trip Information</h2>
        </div>
      </div>

      <!-- Form Content -->
      <div class="p-6">
        <form id="edittrip" class="space-y-6">
          <!-- Hidden Fields -->
          <input type="hidden" name="trip_id" value="<%= trip.trip_id %>">

          <!-- Two Column Layout -->
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Left Column -->
            <div class="space-y-6">
              <!-- Trip Settings -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- Trip Type -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Trip Type</label>
                  <select name="trip_type" class="block w-full pl-3 pr-10 h-12 form-select text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md" <%= status ? 'disabled' : '' %>>
                    <% 
                      const env = 0;
                      const options = env === 1 ? ["Normal", "Ride Later"] : ["Normal", "Outstation", "Rental"];
                      const selectedType = trip.trip_type || 'normal';
                      
                      options.forEach(function(option) {
                        const value = option?.toLowerCase()?.replace(" ", "_");
                    %>
                    <option value="<%= value %>" <%= selectedType === value ? 'selected' : '' %>><%= option %></option>
                    <% }) %>
                  </select>

                </div>

                <!-- Ride Mode -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Ride Mode</label>
                  <select name="is_ride_later" class="block w-full pl-3 pr-10 h-12 form-select text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md" <%= status ? 'disabled' : '' %>>
                    <option value="0" <%= trip.is_ride_later == 0 ? 'selected' : '' %>>Ride Now</option>
                    <option value="1" <%= trip.is_ride_later == 1 ? 'selected' : '' %>>Ride Later</option>
                  </select>
                </div>
              </div>

              <!-- Date Fields -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                  <input type="date" name="trip_date" value="<%= trip.trip_date ? new Date(trip.trip_date).toISOString().split('T')[0] : '' %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status && trip.trip_status !== "request" ? 'disabled' : '' %>>
                  <p class="mt-1 text-xs text-blue-600 text-right">**Change ride mode to modify trip date</p>
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">All Countries Date</label>
                  <input type="date" name="trip_all_date" value="<%= trip.trip_date ? new Date(trip.trip_date).toISOString().split('T')[0] : '' %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm bg-gray-100 sm:text-sm" disabled>
                </div>
              </div>

              <!-- Passenger Section -->
              <div class="bg-blue-50 rounded-lg p-4 border border-blue-100">
                <h3 class="text-sm font-medium text-blue-800 mb-3 flex items-center">
                  <i class="fas fa-user-circle mr-2"></i> Passenger Information
                </h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Name</label>
                    <input type="text" name="client_name" value="<%= trip.user.u_fname %> <%= trip.user.u_lname %>" class="block w-full px-3 py-2 bg-gray-100 border h-12 border-gray-300 rounded-md shadow-sm sm:text-sm" disabled>
                    <input type="hidden" name="user_id" value="<%= trip.user.user_id %>">
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Phone</label>
                    <input type="text" name="client_phone" value="<%= trip.user.c_code || '' %> <%= trip.user.u_phone || '' %>" class="block w-full px-3 py-2 bg-gray-100 h-12 border border-gray-300 rounded-md shadow-sm sm:text-sm" disabled>
                  </div>
                </div>

                <div class="mt-4">
                  <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                  <input type="text" name="client_email" value="<%= trip.user.u_email %>" class="block w-full px-3 py-2 bg-gray-100 h-12 border border-gray-300 rounded-md shadow-sm sm:text-sm" disabled>
                </div>
              </div>

              <!-- Trip Details -->
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                  <select id="categorySelect" name="category_id" <%= status && trip.trip_status !== "request" ? 'disabled' : '' %> class="block w-full pl-3 pr-10 h-12 form-select text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md" <%= status ? 'disabled' : '' %>>
                    <option value="">Select Category</option>

                  </select>
                </div>

                <!-- Location Inputs -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Pickup Location</label>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <i class="fas fa-map-marker-alt text-gray-400"></i>
                    </div>
                    <input type="text" id="trip_from_loc" name="trip_from_loc" value="<%= trip.trip_from_loc %>" class="block w-full pl-10 pr-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                  </div>
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Drop Location</label>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <i class="fas fa-map-marker-alt text-gray-400"></i>
                    </div>
                    <input type="text" id="trip_to_loc" name="trip_to_loc" value="<%= trip.trip_to_loc %>" class="block w-full pl-10 pr-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                  </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Distance (km)</label>
                    <input type="number" name="trip_distance" value="<%= trip.trip_distance %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Pickup Notes</label>
                    <textarea name="p_notes" rows="2" class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"><%= trip.p_notes %></textarea>
                  </div>
                </div>
              </div>

              <!-- Promo Code Section -->
              <div class="bg-purple-50 rounded-lg p-4 border border-purple-100">
                <h3 class="text-sm font-medium text-purple-800 mb-3 flex items-center">
                  <i class="fas fa-tag mr-2"></i> Promo Code
                </h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Promo Code</label>
                    <input type="text" name="promo_code" value="<%= trip.promo_code %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Promo Amount</label>
                    <input type="text" name="promo_amt" value="<%= trip.promo_amt %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                  </div>
                </div>

                <div class="mt-4">
                  <label class="block text-sm font-medium text-gray-700 mb-1">Trip Pay Amount</label>
                  <input type="number" name="trip_pay_amount" value="<%= trip.trip_pay_amount %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                </div>
              </div>
            </div>

            <!-- Right Column -->
            <div class="space-y-6">
              <!-- Driver Selection -->
              <div class="bg-green-50 rounded-lg p-4 border border-green-100">
                <h3 class="text-sm font-medium text-green-800 mb-3 flex items-center">
                  <i class="fas fa-id-card-alt mr-2"></i> Assign Driver
                </h3>

                <div>
                  <label class="block text-sm  font-medium text-gray-700 mb-1">Select Driver</label>
                  <select id="driverSelect" class="w-full" name="driver_id">
                    <option value="">Select a driver</option>
                  </select>
                </div>
              </div>

              <!-- Fare Summary -->
              <% if (trip.trip_pay_amount > 0) { %>
              <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                <h3 class="text-sm font-medium text-gray-800 mb-3 flex items-center">
                  <i class="fas fa-receipt mr-2"></i> Fare Breakdown
                </h3>

                <div class="space-y-3">
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Base Price:</span>
                    <span class="font-medium"><%= trip.category.cat_base_price %></span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Fare Per KM:</span>
                    <span class="font-medium"><%= trip.category.cat_fare_per_km %></span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Fare Per Min:</span>
                    <span class="font-medium"><%= trip.category.cat_fare_per_min %></span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Job Distance:</span>
                    <span class="font-medium"><%= trip.trip_distance %></span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Job Time:</span>
                    <span class="font-medium"><%= trip.trip_total_time %></span>
                  </div>

                  <div class="border-t border-gray-200 pt-2 mt-2 flex justify-between font-medium">
                    <span class="text-gray-700">Subtotal:</span>
                    <span><%= trip.trip_base_fare %></span>
                  </div>

                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Promo Discount:</span>
                    <span class="text-red-500">-<%= trip.promo_amt %></span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">GST (10%):</span>
                    <span class="text-blue-500">+<%= trip.tax_amt %></span>
                  </div>
                  <div class="flex justify-between text-sm">
                    <span class="text-gray-600">Adjustments:</span>
                    <span class="text-blue-500">+<%= trip.adjust_amt %></span>
                  </div>

                  <div class="border-t border-gray-200 pt-2 mt-2 flex justify-between font-semibold">
                    <span class="text-gray-800">Total Amount:</span>
                    <span class="text-lg text-green-600"><%= trip.trip_pay_amount %></span>
                  </div>
                </div>
              </div>
              <% } %>

              <!-- Trip Status Section -->
              <div class="bg-yellow-50 rounded-lg p-4 border border-yellow-100">
                <h3 class="text-sm font-medium text-yellow-800 mb-3 flex items-center">
                  <i class="fas fa-clipboard-check mr-2"></i> Trip Status
                </h3>

                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                  <select name="trip_status" class="block w-full pl-3 pr-10 h-12 form-select text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                    <% tripStatus.forEach(item => { 
                      let isDisabled = true;
                      
                      if (trip.trip_status == "arrive" && (item.slug === "begin" || item.slug === "arrive" || item.slug === "cancel")) {
                          isDisabled = false;
                      }

                      if (trip.trip_status == "request" && (item.slug === "cancel" || item.slug === "expired" || item.slug === "assigned")) {
                          isDisabled = false;
                      }
                    %>
                    <option value="<%= item.slug %>" <%= trip.trip_status === item.slug ? 'selected' : '' %> <%= isDisabled ? 'disabled' : '' %>>
                      <%= item.name %>
                    </option>
                    <% }); %>
                  </select>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Payment Status</label>
                    <select name="trip_pay_status" class="block w-full pl-3 pr-10 h-12 form-select text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md" <%= status ? 'disabled' : '' %>>
                      <option value="Paid" <%= trip.trip_pay_status === 'Paid' ? 'selected' : '' %>>Paid</option>
                      <option value="Unpaid" <%= trip.trip_pay_status === '' ? 'selected' : '' %>>Unpaid</option>
                    </select>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
                    <select name="trip_pay_mode" class="block w-full pl-3 pr-10 h-12 form-select text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md" <%= status ? 'disabled' : '' %>>
                      <option value="Cash" <%= trip.trip_pay_mode === 'Cash' ? 'selected' : '' %>>Cash</option>
                      <option value="Wallet" <%= trip?.trip_pay_mode?.toLowerCase() === 'wallet' ? 'selected' : '' %>>Wallet</option>
                      <option value="Card" <%= trip.trip_pay_mode === 'Card' ? 'selected' : '' %>>Online Payment</option>
                    </select>
                  </div>
                </div>

                <div class="mt-4">
                  <label class="block text-sm font-medium text-gray-700 mb-1">Tip Amount ($)</label>
                  <input type="number" name="tip" value="<%= trip.trip_tip %>" class="block w-full px-3 py-2 border h-12 border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm" <%= status ? 'disabled' : '' %>>
                </div>
              </div>
            </div>
          </div>


          <!-- Form Actions -->
          <div class="flex justify-end pt-6 border-t border-gray-200">

            <button type="submit" id="submitButton" class="inline-flex items-center px-6 py-[10px] border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
              Update Trip
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</main>

<!-- Optimized JavaScript -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const driverSelect = $('#driverSelect');
    const tripDriverId = "<%= trip?.driver_id || '' %>";
    const tripDriverName = "<%= maskName(trip.driver?.d_fname || '', trip.driver?.d_lname || '') %>";

    // Initialize Select2
    // Replace the driverSelect initialization with this:
    driverSelect.select2({
      placeholder: "Select a driver",
      allowClear: true,
      width: '100%',
      minimumInputLength: 2,
      ajax: {
        url: '/admin/active/driver/options?d_active=1&is_delete=0&d_is_available=1&d_is_verified=1',
        dataType: 'json',
        delay: 300,
        data: params => ({
          search: params.term,
          exclude: tripDriverId // Pass current driver ID to exclude
        }),
        processResults: data => ({
          results: data.map(driver => ({
            id: driver.driver_id,
            text: `${driver.d_name} (${driver.driver_id})`,
            d_name: driver.d_name
          }))
        }),
        cache: true
      }
    });

    // Better handling of preselected driver
    if (tripDriverId && tripDriverName) {
      const option = new Option(`${tripDriverName} (${tripDriverId})`, tripDriverId, true, true);
      driverSelect.append(option).trigger('change');

      // Make it non-removable if needed
      driverSelect.on('select2:unselect', function(e) {
        if (e.params.data.id === tripDriverId) {
          driverSelect.val(tripDriverId).trigger('change');
        }
      });
    }
    // Preselect and show in input (but not selectable in list)
    if (tripDriverId && tripDriverName) {
      const option = new Option(`${tripDriverName} (${tripDriverId})`, tripDriverId, true, true);
      driverSelect.append(option).trigger('change');
    }

    // Google Maps Autocomplete
    if (typeof google !== 'undefined') {
      const initAutocomplete = (element, latField, lngField) => {
        const autocomplete = new google.maps.places.Autocomplete(element, {
          types: ['geocode']
        });

        autocomplete.addListener('place_changed', () => {
          const place = autocomplete.getPlace();
          if (place.geometry) {
            $(latField).val(place.geometry.location.lat());
            $(lngField).val(place.geometry.location.lng());
          }
        });
      };

      initAutocomplete(document.getElementById('trip_from_loc'), '#pickupLat', '#pickupLng');
      initAutocomplete(document.getElementById('trip_to_loc'), '#dropLat', '#dropLng');
    }

  });
</script>


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





<script>
  document.addEventListener("DOMContentLoaded", function() {
    const form = document.getElementById("edittrip"); // Replace with actual form ID
    const submitButton = document.getElementById("submitButton"); // Replace with actual button ID
    const loader = document.getElementById("loader"); // Replace with actual loader ID

    form.addEventListener("submit", function(event) {
      event.preventDefault(); // Prevent default form submission

      submitButton.disabled = true;

      const formData = new FormData(form);
      let requestData = {};
      let allFieldNames = [];

      // Only include fields with non-empty values
      formData.forEach((value, key) => {
        if (value !== null && value !== "") {
          requestData[key] = value;
          allFieldNames.push(key);
        }
      });

      console.log("All Non-Empty Field Names:", allFieldNames);

      // API Call
      fetch("/admin/update-trip/<%= trip.trip_id %>", { // Replace with your actual API URL
          method: "PUT",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(requestData)
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            Swal.fire({
              icon: 'success',
              title: 'Success!',
              text: 'Form submitted successfully!',
            }).then(() => {
              form.reset();
window.location.reload(true);
            });
          } else {
            Swal.fire({
              icon: 'success',
              text: data.message || 'Error submitting form.',
            });
          }
        })
        .catch(error => {
          console.error("Error:", error);
          Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'An error occurred while submitting the form.',
          });
        })
        .finally(resetLoader);
    });

    function resetLoader() {
      submitButton.disabled = false;
    }

    function validateEmail(email) {
      const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    }

    function validatePhone(phone) {
      const re = /^\d{10}$/;
      return re.test(phone);
    }
  });
  // Add this to your existing JavaScript
  document.addEventListener('DOMContentLoaded', function() {
    // Define elements object if not already defined
    const elements = {
      categorySelect: $('#categorySelect')
    };

    // Load categories dropdown
    function loadCategories() {
      fetch('/admin/allCatData')
        .then(res => {
          if (!res.ok) throw new Error('Network response was not ok');
          return res.json();
        })
        .then(data => {
          if (data.success && data.data) {
            elements.categorySelect.empty().append('<option value="">Select Category</option>');

            data.data.forEach(cat => {
              const option = new Option(cat.cat_name, cat.category_id, false, false);
              $(option).attr({
                'data-base': cat.cat_base_price,
                'data-fare-per-km': cat.cat_fare_per_km,
                'data-fare-per-min': cat.cat_fare_per_min
              });
              elements.categorySelect.append(option);
            });

            // Set the selected category if editing an existing trip
            const currentCategoryId = "<%= trip.category_id %>";
            if (currentCategoryId) {
              elements.categorySelect.val(currentCategoryId).trigger('change');
            }
          } else {
            console.error('Failed to load categories:', data.message);
          }
        })
        .catch(error => {
          console.error('Error loading categories:', error);
          // Fallback to server-rendered options if available
          const currentCategoryId = "<%= trip.category_id %>";
          if (currentCategoryId) {
            elements.categorySelect.val(currentCategoryId).trigger('change');
          }
        });
    }

    // Initialize category dropdown
    loadCategories();

    // Category selection handler
    elements.categorySelect.on('change', function() {
      const selectedOption = this.options[this.selectedIndex];
      if (selectedOption.value) {
        // Update fare calculation based on selected category
        const basePrice = selectedOption.getAttribute('data-base');
        const farePerKm = selectedOption.getAttribute('data-fare-per-km');
        const farePerMin = selectedOption.getAttribute('data-fare-per-min');

        // Update your fare calculation here
        console.log('Selected category data:', {
          basePrice,
          farePerKm,
          farePerMin
        });

        // Example: Update fare calculation fields
        // You'll need to implement your actual fare calculation logic here
        updateFareCalculation(basePrice, farePerKm, farePerMin);
      }
    });

    // Example fare calculation function
    function updateFareCalculation(basePrice, farePerKm, farePerMin) {
      // Get distance and time values from your form
      const distance = parseFloat(document.querySelector('[name="trip_distance"]').value) || 0;
      const time = parseFloat("<%= trip.trip_total_time %>") || 0; // Or get from a form field

      // Calculate new fare
      const calculatedFare = parseFloat(basePrice) +
        (distance * parseFloat(farePerKm)) +
        (time * parseFloat(farePerMin));

      // Update the fare field (if needed)
      document.querySelector('[name="trip_pay_amount"]').value = calculatedFare.toFixed(2);
    }
  });
</script>



<%- footer %>