<!-- Trip Status Section -->
<div class="section-card bg-yellow-50 border-yellow-100">
  <h3 class="section-title text-yellow-800">
    <i class="fas fa-clipboard-check mr-2"></i> Trip Status
  </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">Status</label>
      <select name="trip_status" class="form-select h-12">
        <% tripStatus.forEach(item => { 
          let isDisabled = item.slug !== "request";
        %>
        <option value="<%= item.slug %>" <%= "request" === item.slug ? 'selected' : '' %> <%= isDisabled ? 'disabled' : '' %>>
          <%= item.name %>
        </option>
        <% }); %>
      </select>
    </div>

    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">Payment Status</label>
      <select name="trip_pay_status" class="form-select">
        <option value="Unpaid">Unpaid</option>
      </select>
    </div>
  </div>

  <div class="mt-4">
    <label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
    <select name="trip_pay_mode" class="form-select">
      <option value="" disabled selected>Select Payment Mode</option>
      <option value="Cash">Cash</option>
      <option value="Wallet">Wallet</option>
      <option value="Card">Online Payment</option>
    </select>
  </div>

  <div class="mt-4 flex items-center">
    <input type="checkbox" name="is_send_notification" value="1" id="notificationCheckbox" class="form-checkbox">
    <label for="notificationCheckbox" class="ml-2 block text-sm text-gray-700">
      Send notification to passenger
    </label>
  </div>
</div>

<!-- Optimized JavaScript -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const tripTypeSelect = document.getElementById('tripType');
    const normalOptions = document.getElementById('normalOptions');
    const outstationOptions = document.getElementById('outstationOptions');
    const returnDateContainer = document.getElementById('returnDateContainer');
    const rentalOptions = document.getElementById('rentalOptions');
    let curr = "<%= city_cur %>";

    // Initial setup
    updateTripOptions();

    // Handle trip type changes
    tripTypeSelect.addEventListener('change', updateTripOptions);

    // Handle outstation trip mode changes
    if (document.querySelector('[name="is_oneway"]')) {
      document.querySelector('[name="is_oneway"]').addEventListener('change', function() {
        if (this.value === '0') { // Round trip selected
          returnDateContainer.classList.remove('hidden');
          // Set default return date (start date + 1 day)
          const startDate = document.querySelector('[name="trip_datetime"]').value;
          if (startDate) {
            const date = new Date(startDate);
            date.setDate(date.getDate() + 1);
            document.querySelector('[name="trip_end_date"]').value = date.toISOString().slice(0, 16);
          }
        } else {
          returnDateContainer.classList.add('hidden');
        }
      });
    }

    // Add to your existing trip type change handler
    tripTypeSelect.addEventListener('change', function() {
      const tripType = this.value;

      // Show/hide elements based on trip type
      if (tripType === 'rental') {
        document.getElementById('rentalPackageContainer').classList.remove('hidden');
        document.getElementById('dropLocationContainer').classList.add('hidden');
      } else {
        document.getElementById('rentalPackageContainer').classList.add('hidden');
        document.getElementById('dropLocationContainer').classList.remove('hidden');
      }

    });


    // Handle package selection changes
    document.getElementById('rentalPackageSelect')?.addEventListener('change', function() {
      const selectedOption = this.options[this.selectedIndex];
      if (selectedOption.value) {
        // Update fare display with package details
        document.getElementById('basePrice').innerText = `${curr} ${selectedOption.dataset.price}`;
        document.getElementById('totalFare').innerText = `${curr} ${selectedOption.dataset.price}`;
        document.getElementById('grossFare').innerText = `${curr} ${selectedOption.dataset.price}`;
        document.getElementById('trip_pay_amount').value = selectedOption.dataset.price;

        // You may want to store the package details in your form data
        estData = {
          package_id: selectedOption.value,
          package_name: selectedOption.text,
          package_price: selectedOption.dataset.price,
          package_hours: selectedOption.dataset.hours
        };
      }
    });


    function updateTripOptions() {
      const tripType = tripTypeSelect.value;

      // Hide all options first
      normalOptions.classList.add('hidden');
      outstationOptions.classList.add('hidden');
      returnDateContainer.classList.add('hidden');
      rentalOptions.classList.add('hidden');

      // Show relevant options based on trip type
      if (tripType === 'normal') {
        normalOptions.classList.remove('hidden');
      } else if (tripType === 'outstation') {
        outstationOptions.classList.remove('hidden');
      } else if (tripType === 'rental') {
        // No specific options to show for rental in this case
        // (rentalOptions would be shown if you add rental-specific fields)
      }
    }
  });
  document.addEventListener('DOMContentLoaded', function() {

    const elements = {
      riderSelect: $('#riderSelect'),
      driverSelect: $('#driverSelect'),
      categorySelect: $('#categorySelect'),
      clientName: $('#clientName'),
      clientPhone: $('#clientPhone'),
      clientEmail: $('#clientEmail'),
      user_id: $('#user_id'),
      api_key: $('#api_key')
    };

    // Generalized Select2 initializer with working processResults
    const initSelect2 = (element, url, template, val) => {
      if (!element.length) {
        console.warn('Select2 init skipped: element not found:', element);
        return;
      }

      element.select2({
        placeholder: element.data('placeholder') || 'Search...',
        allowClear: true,
        width: '100%',
        minimumInputLength: val,
        ajax: {
          url: url,
          dataType: 'json',
          delay: 300,
          data: params => {
            console.log(`Fetching from ${url} with search:`, params.term);
            return {
              search: params.term,
              page: params.page || 1
            };
          },
          processResults: (data, params) => {
            console.log('API response from', url, data);
            params.page = params.page || 1;

            const results = (Array.isArray(data.data) ? data.data : data).map(item => ({
              id: item.user_id || item.driver_id || item.id,
              text: item.u_name || item.d_name || item.name || 'Unknown',
              ...item
            }));

            return {
              results: results,
              pagination: {
                more: false
              }
            };
          },
          cache: true
        },
        templateResult: template,
        templateSelection: item => item.text || item.u_name || item.d_name
      });
    };

    // Initialize rider select
    initSelect2(
      elements.riderSelect,
      '/admin/all/passengers/options?is_delete=0',
      user => {
        if (user.loading) return user.text;
        const div = document.createElement('div');
        div.innerHTML = `${user.u_name || user.text} <span class="text-muted">(ID: ${user.user_id || user.id})</span>`;
        return div;
      },
      1 // Minimum input length for search
    );

    // Initialize driver select
    initSelect2(
      elements.driverSelect,
      '/admin/active/driver/options?d_active=1&is_delete=0&d_is_available=1&d_is_verified=1',
      driver => {
        if (driver.loading) return driver.text;
        const div = document.createElement('div');
        div.innerHTML = `${driver.d_name || driver.text} <span class="text-muted">(ID: ${driver.driver_id || driver.id})</span>`;
        return div;
      },
      0 // Minimum input length for search
    );

    // Handle rider selection
    elements.riderSelect.on('select2:select', function(e) {
      const user = e.params.data;
      console.log('Rider selected:', user);
      elements.clientName.val(user.u_name || '');
      elements.clientPhone.val(`+${user.c_code || ''} ${user.u_phone || ''}`.trim());
      elements.clientEmail.val(user.u_email || '');
      elements.user_id.val(user.user_id || user.id || '');
      elements.api_key.val(user.api_key || '');
    });

    // Clear rider selection
    elements.riderSelect.on('select2:clear', function() {
      elements.clientName.val('');
      elements.clientPhone.val('');
      elements.clientEmail.val('');
      elements.user_id.val('');
      elements.api_key.val('');
    });

    // Load categories dropdown
    function loadCategories() {
      fetch('/admin/allCatData')
        .then(res => res.json())
        .then(data => {
          if (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);
            });
          }
        })
        .catch(console.error);
    }

    loadCategories();
  });
</script>

<script>
  const checkbox = document.getElementById("notificationCheckbox");
  const hiddenInput = document.getElementById("hiddenNotification");

  checkbox.addEventListener("change", function() {
    hiddenInput.value = this.checked ? "1" : "0";
  });
</script>
<script>
  // Validation rules in JSON format
  const validationRules = {
    trip_type: {
      required: true,
      message: "Please select a trip type"
    },
    is_ride_later: {
      required: true,
      message: "Please select ride mode"
    },
    is_oneway: {
      requiredWhen: {
        field: "trip_type",
        value: "outstation"
      },
      message: "Please select trip mode for outstation"
    },
    trip_end_date: {
      requiredWhen: {
        field: "trip_type",
        value: "outstation",
        andField: "is_oneway",
        andValue: "0"
      },
      message: "Return date is required for round trips",
      validate: (value) => {
        const startDate = new Date(document.querySelector('[name="trip_datetime"]').value);
        const endDate = new Date(value);
        return endDate > startDate;
      },
      invalidMessage: "Return date must be after start date"
    },
    trip_datetime: {
      required: true,
      message: "Start date is required",
      validate: (value) => {
        const now = new Date();
        const selectedDate = new Date(value);
        return selectedDate > now;
      },
      invalidMessage: "Start date must be in the future"
    },
    riderSelect: {
      required: true,
      message: "Please select a passenger",
      validate: (value) => {
        const select = document.getElementById('riderSelect');
        return select && $(select).val() !== null && $(select).val() !== '';
      },
      invalidMessage: "Please select a passenger"

    },
    category_id: {
      required: true,
      message: "Please select a category"
    },
    rental_package: {
      requiredWhen: {
        field: "trip_type",
        value: "rental"
      },
      message: "Please select a rental package"
    },
    trip_from_loc: {
      required: true,
      message: "Pickup location is required"
    },
    trip_to_loc: {
      requiredWhen: {
        field: "trip_type",
        notValue: "rental"
      },
      message: "Drop location is required"
    },
    trip_distance: {
      required: true,
      message: "Distance is required",
      validate: (value) => !isNaN(value) && parseFloat(value) > 0,
      invalidMessage: "Distance must be a valid number greater than 0"
    },

    // trip_pay_mode: {
    //   required: true,
    //   message: "Payment method is required"
    // }
  };

  // Function to validate a field
  function validateField(fieldName) {
    const field = document.querySelector(`[name="${fieldName}"]`) ||
      document.getElementById(fieldName);
    const rules = validationRules[fieldName];
    if (!rules) return true; // No validation rules for this field

    // Remove existing error message
    const existingError = field.parentElement.querySelector('.error-message');
    if (existingError) {
      existingError.remove();
    }

    // Check if field is required
    let value = field.value;
    if (field.type === 'select-one') {
      const select = $(field).data('select2');
      value = select ? select.$container.find('.select2-selection__rendered').attr('title') : field.value;
    }

    // Check conditional required
    if (rules.requiredWhen) {
      const conditionField = document.querySelector(`[name="${rules.requiredWhen.field}"]`);
      const conditionValue = conditionField ? conditionField.value : null;

      if (rules.requiredWhen.notValue) {
        if (conditionValue !== rules.requiredWhen.notValue) {
          if (!value) {
            showError(field, rules.message);
            return false;
          }
        }
      } else if (conditionValue === rules.requiredWhen.value) {
        if (rules.requiredWhen.andField) {
          const andField = document.querySelector(`[name="${rules.requiredWhen.andField}"]`);
          const andValue = andField ? andField.value : null;
          if (andValue === rules.requiredWhen.andValue && !value) {
            showError(field, rules.message);
            return false;
          }
        } else if (!value) {
          showError(field, rules.message);
          return false;
        }
      }
    } else if (rules.required && !value) {
      showError(field, rules.message);
      return false;
    }

    // Custom validation
    // Custom validation
    if (rules.validate && value && (typeof value !== 'string' || value.trim() !== '')) {
      if (!rules.validate(value)) {
        showError(field, rules.invalidMessage || "This field is required");
        return false;
      }
    }

    return true;
  }

  // Function to show error message
  function showError(field, message) {
    const errorElement = document.createElement('div');
    errorElement.className = 'error-message text-red-500 text-xs mt-1';
    errorElement.textContent = message;

    // Insert after the field
    if (field.type === 'select-one' && $(field).data('select2')) {
      // For Select2 fields
      $(field).next('.select2-container').after(errorElement);
    } else {
      field.parentNode.insertBefore(errorElement, field.nextSibling);
    }
  }

  // Function to validate the entire form
  function validateForm() {
    let isValid = true;

    // Validate all fields
    Object.keys(validationRules).forEach(fieldName => {
      if (!validateField(fieldName)) {
        isValid = false;
      }
    });

    return isValid;
  }

  // Add event listeners for real-time validation
  document.addEventListener('DOMContentLoaded', function() {
    // Add blur event listeners for all validated fields
    Object.keys(validationRules).forEach(fieldName => {
      const field = document.querySelector(`[name="${fieldName}"]`) ||
        document.getElementById(fieldName);
      if (field) {
        field.addEventListener('blur', () => validateField(fieldName));

        // For Select2 fields, listen to change events
        if ($(field).data('select2')) {
          $(field).on('select2:close', () => validateField(fieldName));
        }
      }
    });


  });
</script>


<script>
  let estData;
  let ADMIN_URL = "<%= ADMIN_URL %>";
  let api_key = document.querySelector('[name="api_key"]')?.value;
  let curr = "<%= city_cur %>";

  document.getElementById("edittrip").addEventListener("submit", function(e) {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    const form = e.target;
    const tripType = document.getElementById('tripType').value;
    const isRideLater = document.querySelector('[name="is_ride_later"]')?.value === '1';
    const selectTime = document.querySelector('[name="trip_datetime"]')?.value;

    // Temporarily enable disabled fields
    const disabledFields = form.querySelectorAll("[disabled]");
    disabledFields.forEach(el => el.removeAttribute("disabled"));

    let formattedGMTDate;

    if (selectTime) {
      const gmtDate = new Date(selectTime);

      // Convert to UTC

      // Format to 'YYYY-MM-DD HH:mm:ss'
      const yyyy = gmtDate.getUTCFullYear();
      const mm = String(gmtDate.getUTCMonth() + 1).padStart(2, '0'); // Months are 0-based
      const dd = String(gmtDate.getUTCDate()).padStart(2, '0');
      const hh = String(gmtDate.getUTCHours()).padStart(2, '0');
      const mi = String(gmtDate.getUTCMinutes()).padStart(2, '0');
      const ss = String(gmtDate.getUTCSeconds()).padStart(2, '0');

      formattedGMTDate = `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;

      // Send `gmtDateString` in your API payload
    } else {
      console.error("Trip date input is missing or empty.");
    }

    // Create FormData object
    const formData = new FormData();

    // Common parameters for all trip types
    const commonData = {
      trip_date: formattedGMTDate,
      city_id: "<%= city_id %>",
      user_id: document.querySelector('[name="user_id"]')?.value || '',
      trip_currency: "<%= city_cur %>",
      seats: "1",
      trip_status: document.querySelector('[name="trip_status"]')?.value || 'request',
      is_share: "0",
      is_delivery: "0",
      trip_pay_mode: document.querySelector('[name="trip_pay_mode"]')?.value || 'Cash',
      pay_card: document.querySelector('[name="trip_pay_mode"]')?.value === 'Card' ? localStorage.getItem("pm") : "",
      pickup_notes: document.getElementById("p_notes")?.value || '',
      trip_customer_details: JSON.stringify({
        name: document.querySelector('[name="client_name"]')?.value,
        phone: document.querySelector('[name="client_phone"]')?.value,
        email: document.querySelector('[name="client_email"]')?.value
      }),
      api_key: document.querySelector('[name="api_key"]')?.value || '',
      trip_dunit: "<%= dunit %>",
      is_ride_later: isRideLater ? "1" : "0"
    };

    // Add common data to formData
    Object.entries(commonData).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        formData.append(key, value);
      }
    });

    // Handle trip type specific parameters
    if (tripType === 'normal') {
      const selectedCategory = document.getElementById("categorySelect")?.selectedOptions[0];

      const normalData = {
        trip_type: "normal",
        cat_name: selectedCategory?.text || '',
        trip_from_loc: document.querySelector('[name="trip_from_loc"]')?.value || '',
        trip_to_loc: document.querySelector('[name="trip_to_loc"]')?.value || '',
        trip_scheduled_pick_lat: document.querySelector('[name="pickupLat"]')?.value || '',
        trip_scheduled_pick_lng: document.querySelector('[name="pickupLng"]')?.value || '',
        trip_scheduled_drop_lat: document.querySelector('[name="dropLat"]')?.value || '',
        trip_scheduled_drop_lng: document.querySelector('[name="dropLng"]')?.value || '',
        trip_distance: document.querySelector('[name="trip_distance"]')?.value || '',
        trip_total_time: document.querySelector('[name="tripTime"]')?.value || '',
        category_id: selectedCategory?.value || '',
        trip_pay_amount: estData?.trip_pay_amount || '',
        tax_amt: estData?.tax_amt || '',
        trip_base_fare: estData?.trip_base_fare || '',
        trip_driver_commision: estData?.trip_driver_commision || '',
        trip_comp_commision: estData?.trip_comp_commision || '',
        est_data: JSON.stringify(estData) || ''
      };

      Object.entries(normalData).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          formData.append(key, value);
        }
      });

    } else if (tripType === 'outstation') {
      const isRound = document.querySelector('[name="is_oneway"]')?.value === '0';

      const tripEndDateEl = document.querySelector('[name="trip_end_date"]');
      const tripEndDate = tripEndDateEl?.value?.trim();

      const outstationData = {
        trip_type: "outstation",
        is_oneway: isRound ? "0" : "1",
        ...(tripEndDate ? {
          trip_end_date: tripEndDate
        } : {}),
        cat_name: document.querySelector('[name="category_id"]')?.selectedOptions[0]?.text || '',
        trip_from_loc: document.querySelector('[name="trip_from_loc"]')?.value || '',
        trip_to_loc: document.querySelector('[name="trip_to_loc"]')?.value || '',
        trip_scheduled_pick_lat: document.querySelector('[name="pickupLat"]')?.value || '',
        trip_scheduled_pick_lng: document.querySelector('[name="pickupLng"]')?.value || '',
        trip_scheduled_drop_lat: document.querySelector('[name="dropLat"]')?.value || '',
        trip_scheduled_drop_lng: document.querySelector('[name="dropLng"]')?.value || '',
        trip_distance: document.querySelector('[name="trip_distance"]')?.value || '',
        trip_total_time: document.querySelector('[name="tripTime"]')?.value || '',
        category_id: document.querySelector('[name="category_id"]')?.value || '',
        trip_pay_amount: estData?.trip_pay_amount || '',
        tax_amt: estData?.tax_amt || '',
        trip_base_fare: estData?.trip_base_fare || '',
        trip_driver_commision: estData?.trip_driver_commision || '',
        trip_comp_commision: estData?.trip_comp_commision || '',
        est_data: JSON.stringify(estData) || ''
      };


      Object.entries(outstationData).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          formData.append(key, value);
        }
      });

    } else if (tripType === 'rental') {
      const packageSelect = document.getElementById('rentalPackageSelect');
      const selectedPackage = packageSelect?.options[packageSelect.selectedIndex];

      const rentalData = {
        trip_type: "rental",
        pkg_cat_id: selectedPackage?.value || '',
        pkg_cat_name: selectedPackage?.parentElement.label || '',
        cat_name: selectedPackage?.dataset.categoryName || '',
        trip_from_loc: document.querySelector('[name="trip_from_loc"]')?.value || '',
        trip_scheduled_pick_lat: document.querySelector('[name="pickupLat"]')?.value || '',
        trip_scheduled_pick_lng: document.querySelector('[name="pickupLng"]')?.value || '',
        trip_distance: selectedPackage?.dataset.distance || '',
        trip_total_time: selectedPackage?.dataset.duration || '',
        category_id: selectedPackage?.dataset.categoryId || '',
        trip_pay_amount: selectedPackage?.dataset.price || '',
        trip_base_fare: selectedPackage?.dataset.baseFare || '',
        tax_amt: selectedPackage?.dataset.tax || '',
        est_data: JSON.stringify({
          package_id: selectedPackage?.value,
          package_name: selectedPackage?.parentElement.label,
          package_price: selectedPackage?.dataset.price,
          package_hours: selectedPackage?.dataset.duration,
          package_distance: selectedPackage?.dataset.distance,
          extra_km_fare: selectedPackage?.dataset.extraKmFare,
          extra_hrs_fare: selectedPackage?.dataset.extraHrsFare,
          night_charges: selectedPackage?.dataset.nightCharges
        })
      };

      Object.entries(rentalData).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          formData.append(key, value);
        }
      });
    }

    document.getElementById("loaderOverlay").style.display = "flex";

    // Submit the form
    fetch(`${ADMIN_URL}api/v1/tripapi/save`, {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams(formData)
      })
      .then(res => res.json())
      .then(async data => {
        console.log("API Response:", data);
        document.getElementById("loaderOverlay").style.display = "none";

        if (data.resDecrypt?.response) {
          const {
            trip_id,
            user_id
          } = data.resDecrypt.response;

          await Swal.fire({
            title: 'Trip Saved!',
            text: 'The trip details have been successfully saved.',
            icon: 'success',
            confirmButtonText: 'OK'
          });

          const driver_id = document.querySelector('[name="driver"]')?.value;
          if (driver_id) {
            // Assign trip to driver
            await fetch(`${ADMIN_URL}api/v1/tripapi/tripassigned`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                u_name: document.querySelector('[name="client_name"]')?.value,
                driver_id: driver_id,
                trip_id: trip_id,
                trip_status: "assigned",
                api_key: document.querySelector('[name="api_key"]')?.value,
                user_id: user_id,
                u_email: document.querySelector('[name="client_email"]')?.value
              })
            });

            // Send notification if needed
            const is_send_notification = document.getElementById("notificationCheckbox")?.checked ? "1" : "0";
            if (is_send_notification == "1") {

              const select = document.querySelector("select[name='driver']");
              const selectedOption = select.options[select.selectedIndex];

              const notificationData = new FormData();
              notificationData.append('trip_id', trip_id);
              notificationData.append('is_share', '0');
              notificationData.append('trip_status', 'request');
              notificationData.append('api_key', document.querySelector('[name="api_key"]')?.value || '');
              notificationData.append((selectedOption.dataset.type?.toLowerCase() === "ios" ? "ios" : "android"),
                selectedOption.dataset.token || '');
              notificationData.append('content-available', '1');
              notificationData.append('message', 'Hey, You received a new Ride Request. Act Fast');
              notificationData.append('drivers', driver_id);

              await fetch(`${ADMIN_URL}api/v1/tripapi/sendnotificationontripsave`, {
                method: 'POST',
                body: notificationData
              });
            }
          } else {
            const is_send_notification = document.getElementById("notificationCheckbox")?.checked ? "1" : "0";
            console.log("No driver assigned, sending notifications to nearby drivers:", is_send_notification);

            if (is_send_notification == "1") {
              // No driver assigned - send notification to all nearby drivers
              try {
                // Get pickup location coordinates
                const pickupLat = document.querySelector('[name="pickupLat"]')?.value;
                const pickupLng = document.querySelector('[name="pickupLng"]')?.value;
                const category_id = document.querySelector('[name="category_id"]')?.value ||
                  document.getElementById("categorySelect")?.value;

                if (!pickupLat || !pickupLng || !category_id) {
                  throw new Error("Missing required location or category information");
                }

                // Get nearby drivers
                const driversResponse = await fetch(`${ADMIN_URL}api/v1/driverapi/getnearbydriverlistsVer2`, {
                  method: 'POST',
                  headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                  },
                  body: new URLSearchParams({
                    api_key: document.querySelector('[name="api_key"]')?.value || '',
                    category_id: category_id,
                    lat: pickupLat,
                    lng: pickupLng,
                    miles: "<%= driver_radius %>", // You can adjust this radius
                    city_id: "<%= city_id %>",
                    is_share: "0",
                    seats: "1"
                  })
                });

                const driversData = await driversResponse.json();

                if (driversData.resDecrypt?.response?.length > 0) {
                  const nearbyDrivers = driversData.resDecrypt.response;
                  const androidTokens = [];
                  const iosTokens = [];
                  const driverIds = [];

                  // Organize tokens by device type
                  nearbyDrivers.forEach(driver => {
                    if (driver.d_device_token) {
                      if (driver.d_device_type?.toLowerCase() === 'ios') {
                        iosTokens.push(driver.d_device_token);
                      } else {
                        androidTokens.push(driver.d_device_token);
                      }
                      driverIds.push(driver.driver_id);
                    }
                  });

                  if (androidTokens.length > 0 || iosTokens.length > 0) {
                    // Prepare notification data
                    const notificationData = new FormData();
                    notificationData.append('trip_id', trip_id);
                    notificationData.append('is_share', '0');
                    notificationData.append('trip_status', 'request');
                    notificationData.append('api_key', document.querySelector('[name="api_key"]')?.value || '');

                    if (androidTokens.length > 0) {
                      notificationData.append('android', androidTokens.join(','));
                    }
                    if (iosTokens.length > 0) {
                      notificationData.append('ios', iosTokens.join(','));
                    }

                    notificationData.append('content-available', '1');
                    notificationData.append('message', 'Hey, You received a new Ride Request. Act Fast');
                    notificationData.append('drivers', driverIds.join(','));

                    // Send notification to all nearby drivers
                    await fetch(`${ADMIN_URL}api/v1/tripapi/sendnotificationontripsave`, {
                      method: 'POST',
                      body: notificationData
                    });

                    // await Swal.fire({
                    //   title: 'Notification Sent!',
                    //   text: 'No driver was assigned, so notifications have been sent to nearby available drivers.',
                    //   icon: 'info',
                    //   confirmButtonText: 'OK'
                    // });
                  }
                }
              } catch (error) {
                console.error("Error sending notifications to nearby drivers:", error);
                await Swal.fire({
                  title: 'Warning',
                  text: 'Trip was saved but there was an issue notifying nearby drivers.',
                  icon: 'warning',
                  confirmButtonText: 'OK'
                });
              }
            }
          }


          window.location.href = `/admin/trips`;

        }
      })
      .catch(err => {
        document.getElementById("loaderOverlay").style.display = "none";

        Swal.fire({
          title: 'Error!',
          text: err.message || 'There was a problem saving the trip. Please try again.',
          icon: 'error',
          confirmButtonText: 'OK'
        });
      })
      .finally(() => {
        disabledFields.forEach(el => el.setAttribute("disabled", true));
      });
  });
</script>
<script>
  let map, directionsService, directionsRenderer;

  function initMap() {
    directionsService = new google.maps.DirectionsService();
    let curr = "<%= city_cur %>";

    let pickupInput = document.getElementById("trip_from_loc");
    let dropInput = document.getElementById("trip_to_loc");

    let pickupAutocomplete = new google.maps.places.Autocomplete(pickupInput);
    let dropAutocomplete = new google.maps.places.Autocomplete(dropInput);

    let pickupLat = document.getElementById("pickupLat");
    let pickupLng = document.getElementById("pickupLng");
    let dropLat = document.getElementById("dropLat");
    let dropLng = document.getElementById("dropLng");
    let tripDistance = document.getElementById("tripDistance");
    let tripTime = document.getElementById("tripTime");

    function extractLatLng(place, latElement, lngElement) {
      if (place.geometry && place.geometry.location) {
        latElement.value = place.geometry.location.lat();
        lngElement.value = place.geometry.location.lng();
      }
    }

    pickupAutocomplete.addListener("place_changed", function() {
      let place = pickupAutocomplete.getPlace();

      extractLatLng(place, pickupLat, pickupLng);
      calculateRoute();
    });

    dropAutocomplete.addListener("place_changed", function() {
      let place = dropAutocomplete.getPlace();
      extractLatLng(place, dropLat, dropLng);
      calculateRoute();
    });

    const promoButton = document.getElementById("submitPromo");


    let p = false
    promoButton.addEventListener("click", async function() {
      const promoCodeInput = document.getElementById("promo_code");
      const promoCode = promoCodeInput.value.trim();
      if (!promoCode) {
        Swal.fire({
          icon: "warning",
          title: "Missing Promo Code",
          text: "Please enter a promo code.",
        });
        return;
      }
      const categorySelect = document.getElementById("categorySelect");
      console.log("Selected Category ID:", categorySelect.value);
      p = true
            calculateFare(categorySelect.value);

    });

    function calculateRoute() {
      if (pickupLat.value && pickupLng.value && dropLat.value && dropLng.value) {
        let request = {
          origin: new google.maps.LatLng(parseFloat(pickupLat.value), parseFloat(pickupLng.value)),
          destination: new google.maps.LatLng(parseFloat(dropLat.value), parseFloat(dropLng.value)),
          travelMode: google.maps.TravelMode.DRIVING,
        };

        directionsService.route(request, function(result, status) {
          if (status === google.maps.DirectionsStatus.OK) {
            let route = result.routes[0].legs[0];
            let distance = route.distance.value / 1000; // Convert meters to km
            let time = Math.ceil(route.duration.value / 60); // Convert seconds to minutes

            tripDistance.value = distance;
            tripTime.value = time;

            document.getElementById("trip_distance").value = distance.toFixed(2);
            document.getElementById("jobDistance").innerText = distance.toFixed(2) + " <%=dunit%>";
            document.getElementById("jobDistanceInput").innerText = distance.toFixed(2)
            document.getElementById("jobTime").innerText = time + " min";

            // Get polyline from the route
            let polyline = result.routes[0].overview_polyline;
            document.getElementById("polyline").value = polyline;
            const categorySelect = document.getElementById("categorySelect");
            console.log("Selected Category ID:", categorySelect.value);
                               document.getElementById('promo_code').value=''

            calculateFare(categorySelect.value);
          } else {
            console.error("Directions request failed: " + status);
          }
        });
      }
    }

    async function calculateFare(cat_id) {
      // Get all required form values
      const tripType = document.getElementById('tripType').value;
      const isShare = document.getElementById("is_share")?.value || "0";
      const seats = document.getElementById("seats")?.value || "1";
      const distance = document.getElementById("trip_distance")?.value || "0";
      const duration = document.getElementById("tripTime")?.value || "0";
      const pickupLat = document.getElementById("pickupLat")?.value;
      const pickupLng = document.getElementById("pickupLng")?.value;
      const dropLat = document.getElementById("dropLat")?.value;
      const dropLng = document.getElementById("dropLng")?.value;
      const pickupAddress = document.getElementById("trip_from_loc")?.value;
      const dropAddress = document.getElementById("trip_to_loc")?.value;
      const polyline = document.getElementById("polyline")?.value;
      const apiKey = document.getElementById("api_key")?.value;
      const userId = document.getElementById("user_id")?.value;
      const tripDate = (() => {
        const raw = document.getElementById("trip_datetime")?.value;
        if (!raw) return "";
        const d = new Date(raw); // interprets as local time
        const yyyy = d.getUTCFullYear();
        const mm   = String(d.getUTCMonth() + 1).padStart(2, '0');
        const dd   = String(d.getUTCDate()).padStart(2, '0');
        const hh   = String(d.getUTCHours()).padStart(2, '0');
        const mi   = String(d.getUTCMinutes()).padStart(2, '0');
        const ss   = String(d.getUTCSeconds()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
      })();
      const cityId = "<%= city_id %>";
      const promoCodeInput = document.getElementById("promo_code");
      const promo_code = promoCodeInput.value.trim();
      const promoAmt = document.getElementById("promoAmtvalue");
      const isRound = tripType === 'outstation' ?
        (document.querySelector('[name="is_oneway"]')?.value === '0' ? 1 : 0) : 0;

      // Validate promo code first if it exists
      if (promo_code) {
        document.getElementById("loaderOverlay").style.display = "flex";
        p = false;
        try {
          const validationResponse = await fetch(`${ADMIN_URL}api/v1/promoapi/validatepromos`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              promo_code: promo_code,
              user_id: userId,
              city_id: cityId,
              api_key: apiKey,
              category_id: cat_id || ''
            })
          });

          if (!validationResponse.ok) {
            throw new Error('Promo code validation failed');
          }
          Swal.fire({
            icon: 'success',
            title: 'Promo code applied successfully',
          });
          const validationResult = await validationResponse.json();

          if (!validationResult.resDecrypt.code) {
            // Invalid promo code
            Swal.fire({
              icon: 'error',
              title: 'Invalid Promo Code',
              text: validationResult.resDecrypt.message || 'The promo code you entered is invalid or expired.'
            });
            promoCodeInput.value = ''; // Clear the invalid promo code
            return;
          }
        } catch (error) {
          console.error('Error validating promo code:', error);
          Swal.fire({
            icon: 'error',
            title: 'Invalid Promo Code',
            text: validationResult.resDecrypt.message || 'The promo code you entered is invalid or expired.'
          });
          return;
        }
      }

      // For rental trips, we don't need drop location or distance calculations
      // For rental trips, we don't need drop location or distance calculations
      if (tripType === 'rental') {
        try {
          const data = {
            city_id: cityId
          };

          const response = await fetch(`${ADMIN_URL}api/v1/tripapi/estimatepackagetripfare?api_key=${apiKey}&user_id=${userId}`, {
            method: "POST",
            headers: {
              "Accept": "application/json",
              "Content-Type": "application/json",
            },
            body: JSON.stringify(data)
          });

          const result = await response.json();
          const packages = result.resDecrypt.response;

          // Populate package dropdown grouped by duration
          const packageSelect = document.getElementById('rentalPackageSelect');
          packageSelect.innerHTML = '<option value="">Select Rental Package</option>';

          // Group packages by duration first
          const packagesByDuration = {};
          packages.forEach(pkg => {
            if (!packagesByDuration[pkg.name]) {
              packagesByDuration[pkg.name] = [];
            }
            packagesByDuration[pkg.name].push(...pkg.Category);
          });

          // Create optgroups for each duration
          for (const [durationName, categories] of Object.entries(packagesByDuration)) {
            const optgroup = document.createElement('optgroup');
            optgroup.label = durationName;

            categories.forEach(category => {
              const option = document.createElement('option');
              option.value = category.pkg_cat_id;
              option.textContent = `${category.cat_name} -  ${category.est.trip_pay_amount}`;
              option.dataset.price = category.est.trip_pay_amount;
              option.dataset.baseFare = category.est.trip_base_fare;
              option.dataset.tax = category.est.tax_amt;
              option.dataset.duration = durationName.match(/\d+/)[0];
              option.dataset.distance = durationName.match(/\d+/g)[1];
              option.dataset.categoryId = category.category_id;
              option.dataset.categoryName = category.cat_name;
              option.dataset.extraKmFare = category.est.pkg_category.extra_km_fare || 0;
              option.dataset.extraHrsFare = category.est.pkg_category.extra_hrs_fare || 0;
              option.dataset.nightCharges = category.est.pkg_category.night_charges || 0;

              optgroup.appendChild(option);
            });

            packageSelect.appendChild(optgroup);
          }
          document.getElementById("loaderOverlay").style.display = "none";

          return;
        } catch (error) {
          document.getElementById("loaderOverlay").style.display = "none";

          console.error('Error fetching rental packages:', error);
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Failed to load rental packages. Please try again.'
          });
          return;
        }
      }

      // For normal and outstation trips, proceed with normal validation
      if (tripType !== 'outstation' && tripType !== 'normal') {
        document.getElementById("loaderOverlay").style.display = "none";

        return;
      }

      if (!pickupLat || !pickupLng) {
        document.getElementById("loaderOverlay").style.display = "none";

        console.error("Missing required location data", pickupLat, pickupLng, dropLat, dropLng);
        return;
      }

      try {
        let response, data;

        if (tripType === 'outstation') {
          // Call outstation fare estimate API
          const outstationData = {
            trip_scheduled_pick_lat: pickupLat,
            trip_scheduled_pick_lng: pickupLng,
            trip_scheduled_drop_lat: dropLat,
            trip_scheduled_drop_lng: dropLng,
            trip_distance: distance,
            trip_hrs: duration,
            trip_from_loc: pickupAddress,
            trip_to_loc: dropAddress,
            trip_date: tripDate,
            api_key: apiKey,
            city_id: cityId,
            user_id: userId,
            is_round: isRound,
            polyline: polyline || "0",
            promo_code: promo_code || undefined
          };

          response = await fetch(`${ADMIN_URL}api/v1/tripapi/estimateoutstationtripfare`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(outstationData)
          });

          if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

          const result = await response.json();
          data = result.resDecrypt.response[cat_id];
        } else if (tripType === 'normal') {
          // Call normal fare estimate API
          const formData = new FormData();
          formData.append('is_share', isShare);
          formData.append('trip_scheduled_pick_lng', pickupLng);
          formData.append('trip_scheduled_pick_lat', pickupLat);
          formData.append('trip_from_loc', pickupAddress);
          formData.append('trip_to_loc', dropAddress);
          formData.append('trip_scheduled_drop_lat', dropLat);
          formData.append('trip_scheduled_drop_lng', dropLng);
          formData.append('polyline', polyline);
          formData.append('seats', seats);
          formData.append('trip_distance', distance);
          formData.append('api_key', apiKey);
          formData.append('user_id', userId);
          formData.append('trip_date', tripDate);
          formData.append('trip_hrs', duration);
          formData.append('city_id', cityId);
          if (promo_code) formData.append('promo_code', promo_code);

          response = await fetch(`${ADMIN_URL}api/v1/tripapi/estimatetripfare`, {
            method: 'POST',
            body: formData
          });

          if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

          const result = await response.json();
          data = result.resDecrypt.response[cat_id];
        }

        console.log("API Response:", data);

        if (data) {
          document.getElementById("loaderOverlay").style.display = "none";

          // Handle promo code display if applicable
          if (promo_code && data.trip_pay_amount_without_promo) {
            // promoAmt.innerText = ` ${data.trip_pay_amount_without_promo?.toFixed(2)}`;
          }

          estData = data;

          // Get category details (for normal trips)
          let selectedCategory = document.getElementById("categorySelect")?.selectedOptions[0];
          let base_price = tripType === 'outstation' ?
            (data.trip_base_fare || 0) :
            (parseFloat(selectedCategory?.getAttribute("data-base")) || 0);

          let fare_per_km = tripType === 'outstation' ?
            (data.trip_fare_per_km || 0) :
            (parseFloat(selectedCategory?.getAttribute("data-fare-per-km")) || 0);

          let fare_per_min = tripType === 'outstation' ?
            (data.trip_fare_per_min || 0) :
            (parseFloat(selectedCategory?.getAttribute("data-fare-per-min")) || 0);

          // Update the fare display with API response
          document.getElementById("basePrice").innerText = `<%= city_cur %>${Number(base_price).toFixed(2)}`;
          document.getElementById("basePriceInput").value = base_price;

          document.getElementById("farePerKM").innerText = `<%= city_cur %>${Number(fare_per_km).toFixed(2)}`;
          document.getElementById("farePerKMInput").value = fare_per_km;

          document.getElementById("farePerMin").innerText = `<%= city_cur %>${Number(fare_per_min).toFixed(2)}`;
          document.getElementById("farePerMinInput").value = fare_per_min;

          // document.getElementById("totalFare").innerText = ` ${Number(data.trip_pay_amount)?.toFixed(2) || '0.00'}`;

          document.getElementById("totalFareInput").innerText = data.trip_base_fare || '0.00';
          document.getElementById("promoAmount").innerText = `<%= city_cur %>${Number(data.trip_promo_amt)?.toFixed(2) || '0.00'}`;
          document.getElementById("promoAmountInput").value = data.trip_promo_amt || '0.00';
          document.getElementById("promo_amt").value = data.trip_promo_amt || '0.00';

          document.getElementById("gstAmount").innerText = `<%= city_cur %>${Number(data.tax_amt)?.toFixed(2) || '0.00'}`;
          document.getElementById("gstAmountInput").value = data.tax_amt || '0.00';

          document.getElementById("adjustAmount").innerText = `<%= city_cur %>${Number(data.adjust_amt)?.toFixed(2) || '0.00'}`;
          document.getElementById("adjustAmountInput").value = data.adjust_amt || '0.00';

          document.getElementById("grossFare").innerText = `<%= city_cur %>${Number(data.trip_pay_amount)?.toFixed(2) || '0.00'}`;
          document.getElementById("grossFareInput").value = data.trip_pay_amount || '0.00';
          document.getElementById("trip_pay_amount").value = data.trip_pay_amount || '0.00';
        } else {
          console.error("No fare data returned from API");
          Swal.fire({
            icon: 'warning',
            title: 'Category Not Available',
            text: 'This category is not available currently. Please choose another.',
            confirmButtonText: 'Okay'
          });
        }
      } catch (error) {
        console.error('Error calculating fare:', error);
        document.getElementById("loaderOverlay").style.display = "none";
      }
    }
    // Add this event listener for package selection changes
    document.getElementById('rentalPackageSelect')?.addEventListener('change', function() {
      const selectedOption = this.options[this.selectedIndex];

      if (selectedOption.value) {
        const packagePrice = parseFloat(selectedOption.dataset.price);
        const baseFare = parseFloat(selectedOption.dataset.baseFare);
        const taxAmount = parseFloat(selectedOption.dataset.tax);

        // Update fare display with package details
        document.getElementById('basePrice').innerText = `  ${curr}${Number(baseFare).toFixed(2)}`;
        document.getElementById('basePriceInput').value = baseFare;

        document.getElementById('farePerKM').innerText = '  ${curr}0.00';
        document.getElementById('farePerKMInput').value = 0;

        document.getElementById('farePerMin').innerText = '  ${curr}0.00';
        document.getElementById('farePerMinInput').value = 0;

        document.getElementById('totalFare').innerText = `  ${curr}${Number(baseFare).toFixed(2)}`;

        document.getElementById('gstAmount').innerText = `  ${curr}${Number(taxAmount).toFixed(2)}`;
        document.getElementById('gstAmountInput').value = taxAmount;

        document.getElementById('grossFare').innerText = `  ${curr}${Number(packagePrice).toFixed(2)}`;
        document.getElementById('grossFareInput').value = packagePrice;
        document.getElementById('trip_pay_amount').value = packagePrice;

        // Store package details in estData for form submission
        estData = {
          package_id: selectedOption.value,
          package_name: selectedOption.parentElement.label,
          category_id: selectedOption.dataset.categoryId,
          category_name: selectedOption.dataset.categoryName,
          package_price: packagePrice,
          trip_base_fare: baseFare,
          tax_amt: taxAmount,
          trip_pay_amount: packagePrice,
          duration_hours: selectedOption.dataset.duration,
          distance_km: selectedOption.dataset.distance,
          extra_km_fare: selectedOption.dataset.extraKmFare,
          extra_hrs_fare: selectedOption.dataset.extraHrsFare,
          night_charges: selectedOption.dataset.nightCharges
        };
      }
    });

    function manualFareCalculation() {
      // Fallback manual calculation if API fails
      let selectedCategory = document.getElementById("categorySelect")?.selectedOptions[0];
      if (!selectedCategory) return;

      let basePrice = parseFloat(selectedCategory.getAttribute("data-base")) || 0;
      let farePerKM = parseFloat(selectedCategory.getAttribute("data-fare-per-km")) || 0;
      let farePerMin = parseFloat(selectedCategory.getAttribute("data-fare-per-min")) || 0;
      let distance = parseFloat(tripDistance.value) || 0;
      let time = parseFloat(tripTime.value) || 0;

      let totalFare = basePrice + (distance * farePerKM) + (time * farePerMin);
      let promoAmount = 0;
      let gstAmount = totalFare * 0.10;
      let adjustAmount = 0;
      let grossFare = totalFare - promoAmount + gstAmount + adjustAmount;

      document.getElementById("basePrice").innerText = `${curr} ${Number(basePrice).toFixed(2)}`;
      document.getElementById("basePriceInput").value = `${Number(basePrice).toFixed(2)}`;
      document.getElementById("farePerKM").innerText = `${curr} ${Number(farePerKM).toFixed(2)}`;
      document.getElementById("farePerKMInput").value = `${Number(farePerKM).toFixed(2)}`;
      document.getElementById("farePerMin").innerText = `${curr} ${Number(farePerMin).toFixed(2)}`;
      document.getElementById("farePerMinInput").value = `${Number(farePerMin).toFixed(2)}`;

      document.getElementById("totalFare").innerText = `${curr} ${Number(totalFare).toFixed(2)}`;
      document.getElementById("promoAmount").innerText = `${curr} ${Number(promoAmount).toFixed(2)}`;
      document.getElementById("promoAmountInput").value = `${Number(promoAmount).toFixed(2)}`;
      document.getElementById("gstAmount").innerText = `${curr} ${Number(gstAmount).toFixed(2)}`;
      document.getElementById("gstAmountInput").value = `${Number(gstAmount).toFixed(2)}`;

      document.getElementById("adjustAmount").innerText = `${curr} ${Number(adjustAmount).toFixed(2)}`;
      document.getElementById("adjustAmountInput").value = `${Number(adjustAmount).toFixed(2)}`;

      document.getElementById("grossFare").innerText = `${Number(grossFare).toFixed(2)}`;
      document.getElementById("grossFareInput").value = `${Number(grossFare).toFixed(2)}`;
      document.getElementById("trip_pay_amount").value = `${Number(grossFare).toFixed(2)}`;
    }

    document.getElementById("categorySelect")?.addEventListener("change", function() {
      const categorySelect = document.getElementById("categorySelect");
      console.log("Selected Category ID:", categorySelect.value);
      calculateFare(categorySelect.value);
    });
  }
</script>
