    <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->
  <script>let NODE_API_BASE_URL = "<%= NODE_API_BASE_URL %>";</script>


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

     <% 
  const isMasking = typeof enableMasking !== "undefined" ? enableMasking : true;

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

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

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

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

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

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

     <div class="container mx-auto  pt-20">
       <!-- Header Section -->

       <%- include('../../partials/utils/title.ejs', {title: "Trip Edit Manager"}) %>
       <% 
          const breadcrumbs = [
            { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
            { label: "Trips 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">
             <h2 class="text-xl font-semibold">Trip Information</h2>
           </div>
         </div>
         <hr />

         <!-- Form Content -->
         <div class="p-6">
           <form id="edittrip" class="space-y-6">

             <!-- Hidden Fields -->
             <input type="hidden" id="pickupLat" name="pickupLat" value="<%= trip.trip_scheduled_pick_lat %>">
             <input type="hidden" id="pickupLng" name="pickupLng" value="<%= trip.trip_scheduled_pick_lng %>">
             <input type="hidden" id="dropLat" name="dropLat" value="<%= trip.trip_scheduled_drop_lat%>">
             <input type="hidden" id="dropLng" name="dropLng" value="<%= trip.trip_scheduled_drop_lng %>">
             <input type="hidden" id="tripDistance" name="tripDistance" value="<%= trip.trip_distance %>">
             <input type="hidden" id="tripTime" name="tripTime" value="<%= trip.trip_total_time %>">
             <input type="hidden" id="polyline" name="polyline">
             <input type="hidden" id="api_key" name="api_key" value="<%= api_key %>">
             <input type="hidden" id="user_id" name="user_id" value="<%= trip.user_id %>">

             <!-- Two Column Layout -->
             <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
               <!-- Left Column -->
               <div class="space-y-6" style="padding-inline: 10px;">
                 <!-- 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>
                     <div class="relative">
                       <select name="trip_type" <%=   trip.trip_status !== "request" ? 'disabled' : '' %> id="tripType" class="block form-select w-full pl-3 pr-10 text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">

                         <% 
                      const env = 0;
                      const options = env === 1 ? ["Normal", "Ride Later"] : ["Normal","Rental", "Outstation", "Delivery"];
                      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>
                   </div>

                   <!-- Normal Trip Options (Ride Now/Later) -->
                   <div id="normalOptions">
                     <label class="block text-sm font-medium text-gray-700 mb-1">Ride Mode</label>
                     <div class="relative">
                       <select <%=   trip.trip_status !== "request" ? 'disabled' : '' %> name="is_ride_later" class="block form-select w-full pl-3 pr-10 text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                         <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>

                   <!-- Outstation Trip Options (Single/Round Trip) -->
                   <div id="outstationOptions" class="hidden">
                     <label class="block text-sm font-medium text-gray-700 mb-1">Trip Mode</label>
                     <div class="relative">
                       <select name="is_oneway" class="block form-select w-full pl-3 pr-10 text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                         <option <%= trip.is_oneway == 0 ? 'selected' : '' %> value="1">Single Trip</option>
                         <option <%= trip.is_oneway == 0 ? 'selected' : '' %> value="0">Round Trip</option>
                       </select>
                     </div>
                   </div>

                   <!-- Return Date (for Outstation Round Trip) -->
                   <div id="returnDateContainer" class="hidden">
                     <label class="block text-sm font-medium text-gray-700 mb-1">Return Date</label>
                     <input <%=   trip.trip_status !== "request" ? 'disabled' : '' %> type="datetime-local" name="trip_end_date" value="<%= trip?.trip_end_date ? new Date(trip?.trip_end_date)?.toISOString().slice(0,16) : '' %>" class="block w-full px-3 py-2 h-12 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                   </div>

                   <!-- Rental Trip Options (hidden by default) -->
                   <div id="rentalOptions" class="hidden">
                     <!-- Rental specific fields would go here -->
                   </div>
                 </div>

                 <!-- Start Date -->
                 <div>
                   <label class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                   <input type="datetime-local" id="trip_datetime" <%=   trip.trip_status !== "request" ? 'disabled' : '' %> name="trip_datetime" value="<%= trip.trip_date ? new Date(trip.trip_date).toISOString().slice(0,16) : '' %>" class="block w-full px-3 py-2 h-12 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                   <p class="mt-1 text-xs text-blue-600 text-right">**Change ride mode to modify trip date</p>
                 </div>

                 <!-- Passenger Section -->
                 <div class="bg-blue-50 rounded-lg border border-blue-100" style="padding: 20px;">
                   <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="<%= maskName(trip.user.u_fname) %> <%= maskName(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 || '' %> <%=maskPhone(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" style="padding-top: 10px;">
                     <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                     <input type="text" name="client_email" value="<%= maskEmail(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 class="grid grid-cols-1 md:grid-cols-1 gap-4">
                     <div>
                       <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                       <select <%=   trip.trip_status !== "request" ? 'disabled' : '' %> name="category_id" id="categorySelect" class="block form-select w-full pl-3 pr-10 text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                         <option value="">Select Category</option>
                       </select>
                     </div>
                   </div>

                   <!-- Add this below your category select -->
                   <div id="rentalPackageContainer" class="hidden mt-4">
                     <label class="block text-sm font-medium text-gray-700 mb-1">Rental Package</label>
                     <div class="relative">
                       <select name="rental_package" <%=   trip.trip_status !== "request" ? 'disabled' : '' %> id="rentalPackageSelect" class="block form-select w-full pl-3 pr-10 text-base border border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md">
                         <option value="">Select Rental Package</option>
                         <!-- Packages will be loaded dynamically -->
                       </select>
                     </div>
                   </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" style="height: 46px; margin-left: 15px;">
                         <i class="fas fa-map-marker-alt text-gray-400"></i>
                       </div>
                       <input style="padding-left: 35px;" type="text" id="trip_from_loc" name="trip_from_loc" value="<%= trip.trip_from_loc %>" class="block w-full pl-14 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" <%=   trip.trip_status !== "request" ? '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" style="height: 46px; margin-left: 15px;">
                         <i class="fas fa-map-marker-alt text-gray-400"></i>
                       </div>
                       <input style="padding-left: 35px;" type="text" id="trip_to_loc" name="trip_to_loc" value="<%= trip.trip_to_loc %>" class="block w-full pl-14 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" <%=   trip.trip_status !== "request" ? 'disabled' : '' %>>
                     </div>
                   </div>

                   <%- include('../../partials/TripManager/edit-trip-multistops.ejs') %>

                   <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 (<%=dunit%>)</label>
                       <input type="text" name="trip_distance" id="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" <%= trip.trip_status !== "request" ? 'disabled' : '' %>>
                     </div>

                     <div>
                       <label class="block text-sm font-medium text-gray-700 mb-1">Pickup Notes</label>
                       <input name="p_notes" id="p_notes" value="<%= trip.p_notes %>" 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" />
                     </div>
                   </div>

                   <!-- Promo Code Section -->
                   <div class="bg-purple-50 rounded-lg border border-purple-100" style="padding: 20px;">
                     <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="flex gap-2" style="padding-bottom: 10px;">
                       <div class="flex-1">
                         <label class="block text-sm font-medium text-gray-700 mb-1">Enter Promo Code</label>
                         <input type="text" <%=   trip.trip_status !== "request" ? 'disabled' : '' %> name="promo_code" id="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">
                       </div>
                       <div class="flex items-end">
                         <button <%=   trip.trip_status !== "request" ? 'disabled' : '' %> type="button" id="submitPromo" class="h-12 px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500">
                           Apply
                         </button>
                       </div>
                     </div>

                     <div class="grid grid-cols-1 md:grid-cols-1 gap-4 mt-4" style="padding-bottom: 10px;">
                       <div>
                         <label class="block text-sm font-medium text-gray-700 mb-1">Promo Amount</label>

                         <input type="text" name="promo_amt" 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" disabled>
                       </div>
                     </div>

                     <div>
                       <label class="block text-sm font-medium text-gray-700 mb-1">Trip Pay Amount</label>
                       <input type="text" id="trip_pay_amount" 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" disabled>
                     </div>
                   </div>
                 </div>
               </div>
               <div class="space-y-6" style="padding-inline: 10px;">
                 <!-- Driver Selection -->
                 <div class="bg-green-50 rounded-lg  border border-green-100" style="padding: 20px;">
                   <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" <%= trip.trip_status !== "request" ? 'disabled' : '' %> name="driver_id" class="w-full" data-placeholder="<%= trip?.driver?.d_name ? `${trip.driver.d_name} (ID: ${trip.driver_id})` : 'Select Driver' %>">
                     </select>

                   </div>
                 </div>

                 <!-- Right Column -->

                 <!-- Fare Summary -->
                 <div class="bg-gray-50 rounded-lg  border border-gray-200" style="padding: 30px;">
                   <div style="display: flex; justify-content: space-between; align-items: center;">
                     <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>
                   <br />

                   <div class="space-y-3">
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Base Price:</span>
                       <span class="font-medium" id="basePrice"><%= city_cur %><%= trip.category.cat_base_price %></span>
                       <input type="hidden" name="base_price" id="basePriceInput">
                     </div>
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Fare Per KM:</span>
                       <span class="font-medium" id="farePerKM"><%= city_cur %><%= trip.category.cat_fare_per_km %></span>
                       <input type="hidden" name="fare_per_km" id="farePerKMInput">
                     </div>
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Fare Per Min:</span>
                       <span class="font-medium" id="farePerMin"><%= city_cur %><%= trip.category.cat_fare_per_min %></span>
                       <input type="hidden" name="fare_per_min" id="farePerMinInput">
                     </div>
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Job Distance:</span>
                       <span class="font-medium" id="jobDistance"><%= trip.trip_distance %></span>
                       <input type="hidden" name="job_distance" id="jobDistanceInput">
                     </div>
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Job Time:</span>
                       <span class="font-medium" id="jobTime"><%= trip.trip_total_time %></span>
                       <input type="hidden" name="job_time" id="jobTimeInput">
                     </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 id="totalFareInput"><%= city_cur %><%= trip.trip_base_fare %></span>
                    <input type="hidden" name="total_fare" id="">
                  </div> -->

                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Promo Discount:</span>
                       <span class="text-red-500" id="promoAmount">-<%= city_cur %><%= trip.promo_amt || 0 %> </span>
                       <input type="hidden" name="promo_amount" id="promoAmountInput">
                     </div>
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">GST (<%= city_tax %>%):</span>
                       <span class="text-blue-500" id="gstAmount">+<%= city_cur %><%= trip.tax_amt %></span>
                       <input type="hidden" name="gst_amount" id="gstAmountInput">
                     </div>
                     <div class="flex justify-between text-sm">
                       <span class="text-gray-600">Adjustments:</span>
                       <span class="text-blue-500" id="adjustAmount">+<%= city_cur %><%= trip.adjust_amt %></span>
                       <input type="hidden" name="adjust_amount" id="adjustAmountInput">
                     </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" id="grossFare"><span class="text-lg text-red-600 none" id="promoAmtvalue"></span><%= trip.trip_pay_amount %></span>
                       <input type="hidden" name="gross_fare" id="grossFareInput">
                     </div>
                   </div>
                 </div>

                 <!-- Trip Status Section -->



                 <div class="bg-yellow-50 rounded-lg  border border-yellow-100" style="padding: 20px;">
                   <h3 class="text-sm font-medium text-yellow-800 mb-3 flex items-center">
                     <i class="fas fa-clipboard-check mr-2"></i>Status
                   </h3>

                   <div>
                     <label class="block text-sm font-medium text-gray-700 mb-1">Trip 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">
                       <% 
    const isPaidCancel = trip.trip_status === "paid_cancel";
  
    tripStatus.forEach(item => { 
      let isDisabled = true;
      
      // only apply transition rules when NOT paid_cancel
      if (!isPaidCancel) {
        if (trip.trip_status == "arrive" && (item.slug === "begin" || item.slug === "cancel")) {
          isDisabled = false;
        }

        if (trip.trip_status == "request" && (item.slug === "cancel" || item.slug === "expired" || item.slug === "assigned")) {
          isDisabled = false;
        }

        if (trip.trip_status == "begin" && item.slug === "completed") {
          isDisabled = false;
        }

        if (trip.trip_status == "assigned" && (item.slug === "cancel" || item.slug === "accept")) {
          isDisabled = false;
        }

        if (trip.trip_status == "accept" && (item.slug === "cancel" || item.slug === "arrive")) {
          isDisabled = false;
        }
      }

      // ✅ selection logic
      let isSelected = false;
      if (isPaidCancel) {
        // when trip_status is paid_cancel, select "completed"
        isSelected = item.slug === "paid_cancel";
      } else {
        isSelected = trip.trip_status === item.slug;
      }
  %>

                       <option value="<%= item.slug %>" <%= isSelected ? "selected" : "" %> <%= isDisabled ? "disabled" : "" %>>
                         <%= (isPaidCancel && item.slug === "paid_cancel") 
            ? "Payment Awaited" 
            : item.name %>
                       </option>

                       <% }); %>
                     </select>



                   </div>

                   <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                     <div style="padding-bottom: 10px;">
                       <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" <%= trip.trip_status === "completed" && trip.trip_pay_status?.toLowerCase() === "paid" ? "disabled" : "" %>>

  <option value="Paid" <%= trip.trip_pay_status?.toLowerCase() === "paid" ? "selected" : "" %> <%= (trip.trip_status !== "completed" && trip.trip_status !== "paid_cancel") ? "disabled" : "" %>>
    Paid
  </option>

  <option value="" <%= trip.trip_pay_status?.toLowerCase() !== "paid" ? "selected" : '' %>>
    Unpaid
  </option>

</select>

                     </div>

                     <div>
                       <label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
                       <select <%=   trip.trip_status == "completed" && trip.trip_pay_status?.toLowerCase() == "paid"  ? 'disabled' : '' %> 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">
                         <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' : '' %>>Card</option>
                       </select>
                     </div>
                   </div>

                   <div class="mt-4" style="padding-top: 10px;">
                     <label class="block text-sm font-medium text-gray-700 mb-1">Tip Amount (<%= city_cur %>)</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 id="deliverySections" style="display:none;">
                   <div class="bg-yellow-50 rounded-lg  border border-yellow-100" style="padding: 20px;">

                     <!-- Receiver Details -->
                     <div class="mb-4">
                       <h3 class="text-sm font-medium text-purple-800 mb-0 flex items-center" style="padding-bottom: 10px;">
                         <i class="bi bi-pencil-square me-2"></i>Receiver Details
                       </h3>

                       <label>Full Name</label>
                       <input class="form-control" id="receiverName" value="<%= trip?.receiver?.u_name %>" <%=   trip.trip_type == "delivery" ? 'disabled' : '' %>>

                       <div class="row mt-3">
                         <div class="col-md-6">
                           <label>Country Code</label>
                           <select <%=   trip.trip_type == "delivery" ? 'disabled' : '' %> class="form-control" id="receiverCountryCode"></select >

                         </div>

                         <div class="col-md-6">
                           <label>Phone Number</label>
                           <input class="form-control" id="receiverPhone" value="<%= trip?.receiver?.u_phone %>" oninput="this.value = this.value.replace(/[^0-9]/g, '')" <%=   trip.trip_type == "delivery" ? 'disabled' : '' %>>
                         </div>
                       </div>
                     </div>

                     <!-- Delivery Images -->
                     <div class="mb-4" style="padding-top: 20px;">

                       <h3 class="text-sm font-medium text-purple-800 mb-0 flex items-center" style="padding-bottom: 10px;">
                         <i class="bi bi-pencil-square me-2"></i>Delivery Image
                       </h3>


                       <input type="file" class="form-control" id="deliveryImage" accept="image/*" <%=   trip.trip_type == "delivery" ? 'disabled' : '' %>>
                       <% if (trip.images && trip.images.length > 0) { %>
                       <div style="margin-top: 10px;">
                         <label>Existing Delivery Image</label><br>
                         <img src="<%= IMAGE_FOLDER_PATH %><%= trip.images[0].img_path %>" alt="Delivery Image" style="width: 150px; border-radius: 8px; margin-top: 5px;">
                       </div>
                       <% } %>

                     </div>

                     <!-- Delivery Notes -->
                     <div class="mb-4" style="padding-top: 20px;">
                       <h3 class="text-sm font-medium text-purple-800 mb-0 flex items-center" style="padding-bottom: 10px;">
                         <i class="bi bi-pencil-square me-2"></i>Delivery Notes
                       </h3>

                       <textarea <%=   trip.trip_type == "delivery" ? 'disabled' : '' %> class="form-control" id="deliveryNotes" rows="4"><%= trip.delivery_notes || '' %></textarea>
                     </div>
                   </div>

                 </div>
                 <%- include('../../partials/TripManager/trip-co-pass-info.ejs') %>
                 <%- include('../../partials/TripManager/trip-extra-options.ejs') %>


               </div>
             </div>


             <!-- Form Actions -->
             <div class="flex justify-end border-t border-gray-200 " style="padding-bottom: 15px; padding-top: 20px; padding-right: 10px; gap: 10px ;">
               <button id="button" onclick="window.location.href='/admin/trips'" style="background-color: rgb(162, 162, 162);  padding-inline: 20px; color: white;"> Cancel
               </button>



               <button type="submit" id="submitButton" class="inline-flex items-center py-2 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>
   <!-- ============================
     Fare Calculation Popup
============================== -->
   <div class="modal fade" id="fareCalcModal" tabindex="-1" aria-labelledby="fareCalcModalLabel" aria-hidden="true">
     <div class="modal-dialog modal-xl modal-dialog-scrollable">
       <div class="modal-content">

         <div class="modal-header">

           <h4 class="modal-title" id="fareCalcModalLabel">Fare Calculation</h4>
           <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
         </div>

         <div class="modal-body">

           <!-- TOP SUMMARY -->
           <table class="table table-bordered text-center">
             <thead class="table-light">
               <tr>
                 <th>Base Price (BP)</th>
                 <th>Fare Per KM/MI (FPMK)</th>
                 <th>Distance (DIKM)</th>
                 <th>Fare Per Minute (FPM)</th>
                 <th>Job Time (JTIM)</th>
                 <th>GST Rate % (STRIP)</th>
               </tr>
             </thead>
             <tbody>


               <td id="calcBaseFare"></td>
               <td id="calcFarePerKM"></td>
               <td id="calcDistanceKM"></td>
               <td id="calcFarePerMin"></td>
               <td id="calcJobTime"></td>
               <td id="calcGstRate"></td>
               </tr>
             </tbody>
           </table>

           <!-- TOTAL JOB FARE (TJF) -->
           <table class="table table-bordered text-center mt-4">
             <thead class="table-light">
               <tr>
                 <th colspan="3">Total Job Fare (TJF)</th>
               </tr>
             </thead>
             <tbody>
               <tr>
                 <td id="calcTjfFormula"></td>
                 <td></td>
                 <td id="calcTjfValue"></td>
               </tr>
             </tbody>
           </table>



           <!-- GST -->
           <table class="table table-bordered text-center mt-4">
             <thead class="table-light">
               <tr>
                 <th colspan="3">GST Amount (STA)</th>
               </tr>
             </thead>
             <tbody>
               <tr>
                 <td id="calcGstFormula"></td>
                 <td></td>
                 <td id="calcGstValue"></td>
               </tr>
             </tbody>
           </table>


           <table class="table table-bordered text-center mt-4">
             <thead class="table-light">
               <tr>
                 <th colspan="3">Promo Amount (PDA)</th>
               </tr>
             </thead>
             <tbody>
               <tr>
                 <td id="calcPromo"></td>
               </tr>
             </tbody>
           </table>

           <!-- TOTAL AFTER PROMO -->
           <table class="table table-bordered text-center mt-4">
             <thead class="table-light">
               <tr>
                 <th colspan="3">Total Job Fare After Promo</th>
               </tr>
             </thead>
             <tbody>
               <tr>
                 <td id="calcTjfAfterPromoFormula"></td>
                 <td></td>
                 <td id="calcTjfAfterPromoValue"></td>
               </tr>
             </tbody>
           </table>
           <!-- GROSS FARE -->
           <table class="table table-bordered text-center mt-4">
             <thead class="table-light">
               <tr>
                 <th colspan="3">Gross Job Fare</th>
               </tr>
             </thead>
             <tbody>
               <tr>
                 <td id="calcGrossFareFormula"></td>
                 <td></td>
                 <td id="calcGrossFareValue"></td>
               </tr>
             </tbody>
           </table>

         </div>

         <div class="modal-footer">
           <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
         </div>

       </div>
     </div>
   </div>
   <script>
 
document.addEventListener('DOMContentLoaded', function() {

  console.log("apisdsd", NODE_API_BASE_URL)

    // Helper to convert UTC date to local datetime string
    function utcToLocalDatetime(utcDateString) {
        if (!utcDateString) return '';
        
        const date = new Date(utcDateString + 'Z'); // Force UTC parsing
        
        // Get timezone offset in minutes
        const tzOffset = date.getTimezoneOffset() * 60000;
        
        // Adjust date to local time
        const localDate = new Date(date.getTime() - tzOffset);
        
        // Return in datetime-local format
        return localDate.toISOString().slice(0, 16);
    }
    
    // Set dates
    const tripDateInput = document.getElementById('trip_datetime');
    const tripEndDateInput = document.querySelector('[name="trip_end_date"]');
    
    // Trip start date
    if ("<%= trip.trip_date %>" && tripDateInput) {
        tripDateInput.value = utcToLocalDatetime("<%= trip.trip_date %>");
    }
    
    // Trip end date (if exists)
    if ("<%= trip?.trip_end_date %>" && tripEndDateInput) {
        tripEndDateInput.value = utcToLocalDatetime("<%= trip?.trip_end_date %>");
    }
    
    // Optional: Display the timezone being used
    console.log('Browser timezone:', Intl.DateTimeFormat().resolvedOptions().timeZone);
});
</script>
     <script>
     document.addEventListener("DOMContentLoaded", function() {
       $('#receiverCountryCode').select2({
         placeholder: "Select Country Code",
         width: "100%"
       });

       function toggleDeliveryFields(tripType) {
         const section = document.getElementById("deliverySections");

         if (tripType === "delivery") {
           section.style.display = "block";

    

         } else {
           section.style.display = "none";

        
         }
       }

       function updateDeliveryValidationRules(tripType) {
  if (tripType === "delivery") {
    validationRules.receiverName = {
      required: true,
      message: "Receiver name is required"
    };

    validationRules.receiverCountryCode = {
      required: true,
      message: "Country code is required"
    };

    validationRules.receiverPhone = {
      required: true,
      message: "Receiver phone number is required",
      validate: (value) => /^\d{5,15}$/.test(value),
      invalidMessage: "Please enter a valid phone number"
    };

    validationRules.deliveryImage = {
      required: true,
      message: "Delivery proof image is required"
    };

    validationRules.deliveryNotes = {
      required: true,
      message: "Delivery notes are required"
    };
  } else {
    // Remove delivery rules when NOT delivery
    delete validationRules.receiverName;
    delete validationRules.receiverCountryCode;
    delete validationRules.receiverPhone;
    delete validationRules.deliveryImage;
    delete validationRules.deliveryNotes;
  }
}

 document.getElementById("tripType").addEventListener("change", function() {
  toggleDeliveryFields(this.value);
  updateDeliveryValidationRules(this.value);
});

       const rideModeSelect =
         document.getElementById("ride_mode") ||
         document.querySelector('select[name="is_ride_later"]');
       const tripDateInput = document.getElementById("trip_datetime");

       function toggleTripDate() {
         if (rideModeSelect.value === "0") {
           // disable editing but keep value visible
           tripDateInput.disabled = true;
           tripDateInput.classList.add("bg-gray-100", "cursor-not-allowed");
         } else {
           tripDateInput.disabled = false;
           tripDateInput.classList.remove("bg-gray-100", "cursor-not-allowed");
         }
       }

       // Run once on load
       toggleTripDate();

       // Listen for changes
       rideModeSelect.addEventListener("change", toggleTripDate);
     });
   </script>
   <script>
     document.addEventListener("DOMContentLoaded", function() {
       const tripType = "<%= trip.trip_type %>";

       if (tripType === "delivery") {
         document.getElementById("deliverySections").style.display = "block";

         // Pre-fill (already done above in EJS)
       } else {
         document.getElementById("deliverySections").style.display = "none";
       }
     });
     const receiverCCode = "<%= trip?.receiver?.c_code || '' %>";

     fetch("/countryCode.json")
       .then(res => res.json())
       .then(data => {
         const $select = $('#receiverCountryCode');
         const savedCode = "<%= trip?.receiver?.c_code || '' %>"; // e.g. "91"

         data.forEach(country => {
           const flag = [...country.code.toUpperCase()]
             .map(char => 127397 + char.charCodeAt())
             .map(code => String.fromCodePoint(code))
             .join('');

           const value = `+${country.id}`;

           const option = new Option(
             `${flag} +${country.id} (${country.name})`,
             value,
             false,
             false
           );

           $select.append(option);

           // Auto-select receiver's country code
           if (savedCode && savedCode == country.id) {
             option.selected = true;
           }
         });

         // Initialize Select2 AFTER options added
         $select.trigger('change');
       });
   </script>

   <script>
     document.addEventListener("DOMContentLoaded", function() {
       $('#receiverCountryCode').select2({
         placeholder: "Select Country Code",
         width: "100%"
       });


       const cur = "<%= city_cur %>";

       document.getElementById("calcBaseFare").innerText = `<%= city_cur %><%= trip.category.cat_base_price %>`;

       document.getElementById("calcFarePerKM").innerText = `<%= city_cur %><%= trip.category.fare_per_km %>`

       document.getElementById("calcDistanceKM").innerText = `<%= trip.trip_distance %>`

       document.getElementById("calcFarePerMin").innerText = `<%= city_cur %><%= trip.category.fare_per_min %>`

       document.getElementById("calcJobTime").innerText =
         Number(`<%= trip.trip_total_time %>`).toFixed(0);

       document.getElementById("calcGstRate").innerText =
         Number(<%= city_tax%> || 0).toFixed(0);

       // TJF
       document.getElementById("calcTjfFormula").innerText =
         `(${Number(`<%= trip.category.cat_base_price %>`)} + (${Number(`<%= trip.category.fare_per_km %>`)} × ${`<%= trip.trip_distance %>`}) + (${Number(`<%= trip.category.fare_per_min %>`)} × ${` <%= trip.trip_total_time %>`}))`;

       document.getElementById("calcTjfValue").innerText =
         `${cur}${Number(`<%= trip.trip_base_fare %>`).toFixed(2)}`;

       // Promo
       document.getElementById("calcPromo").innerText =
         `${cur}${Number(`<%= trip.trip_promo_amt %>` || 0).toFixed(2)}`;

       // TJF After Promo
       document.getElementById("calcTjfAfterPromoFormula").innerText =
         `(${Number(`<%= trip.trip_pay_amount_without_promo %>`).toFixed(2)} - ${Number(`<%= trip.trip_promo_amt %>`).toFixed(2)})`;

       document.getElementById("calcTjfAfterPromoValue").innerText =
         `${cur}${Number(`<%= trip.trip_pay_amount %>`).toFixed(2)}`;

       // GST
       document.getElementById("calcGstFormula").innerText =
         `((${Number(`<%= trip.trip_base_fare %>`).toFixed(2)} × ${Number(<%= city_tax%> || 0)}) / 100)`;

       document.getElementById("calcGstValue").innerText =
         `${cur}${Number( <%= trip.tax_amt %> || 0).toFixed(2)}`;


       // Gross Fare
       document.getElementById("calcGrossFareFormula").innerText =
         `(${Number(`<%= trip.trip_base_fare %>`).toFixed(2)} + ${Number(<%= trip.tax_amt %> ).toFixed(2)})`;

       document.getElementById("calcGrossFareValue").innerText =
         `${cur}${Number(`<%= trip.trip_pay_amount %>`).toFixed(2)}`;

       function toggleDeliveryFields(tripType) {
         const section = document.getElementById("deliverySections");

         if (tripType === "delivery") {
           section.style.display = "block";

           // Make required
           document.getElementById("receiverName").required = true;
           document.getElementById("receiverCountryCode").required = true;
           document.getElementById("receiverPhone").required = true;
           document.getElementById("deliveryImage").required = true;
           document.getElementById("deliveryNotes").required = true;

         } else {
           section.style.display = "none";

           // Remove required
           document.getElementById("receiverName").required = false;
           document.getElementById("receiverCountryCode").required = false;
           document.getElementById("receiverPhone").required = false;
           document.getElementById("deliveryImage").required = false;
           document.getElementById("deliveryNotes").required = false;
         }
       }


       const rideModeSelect =
         document.getElementById("ride_mode") ||
         document.querySelector('select[name="is_ride_later"]');
       const tripDateInput = document.getElementById("trip_datetime");

       function toggleTripDate() {
         if (rideModeSelect.value === "0") {
           // disable editing but keep value visible
           tripDateInput.disabled = true;
           tripDateInput.classList.add("bg-gray-100", "cursor-not-allowed");
         } else {
           tripDateInput.disabled = false;
           tripDateInput.classList.remove("bg-gray-100", "cursor-not-allowed");
         }
       }

       // Run once on load
       toggleTripDate();

       // Listen for changes
       rideModeSelect.addEventListener("change", toggleTripDate);
     });
   </script>

   <!-- 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);
       document.getElementById("tripType").addEventListener("change", function() {
         toggleDeliveryFields(this.value);
       });
       // 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 || "<%= trip.trip_date %>";
             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');
         }

       });

       // Helper functions to safely update DOM elements
       function setText(id, value) {
         const el = document.getElementById(id);
         if (el) el.innerText = value;
       }

       function setValue(id, value) {
         const el = document.getElementById(id);
         if (el) el.value = value;
       }

       function setHtml(id, value) {
         const el = document.getElementById(id);
         if (el) el.innerHTML = value;
       }

       // 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
           setText("basePrice", `${curr} ${selectedOption.dataset.price}`);
           setText("grossFare", `${curr} ${selectedOption.dataset.price}`);
           setValue("trip_pay_amount", 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 rider 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 driver 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 || "<%= trip.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('');
       });
       const selectedCategoryId = "<%= trip?.category_id || '' %>";

       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 isSelected = cat.category_id.toString() === selectedCategoryId.toString();
                 const option = new Option(cat.cat_name, cat.category_id, isSelected, isSelected);

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

               // Trigger change event if needed (e.g., to update UI based on category)
               elements.categorySelect.trigger('change');
             }
           })
           .catch(console.error);
       }

       loadCategories();
     });
   </script>





<script>
document.getElementById("edittrip").addEventListener("submit", async function(e) {
    e.preventDefault();
    if (typeof window.syncStopsInputEdit === "function") window.syncStopsInputEdit(true);

    const form = document.getElementById("edittrip");

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

    // Collect non-empty fields
    formData.forEach((value, key) => {
        if (value !== null && value !== "") {
            requestData[key] = value;
        }
    });

          // 🔁 Auto update trip status when payment is marked as paid
         if (requestData.trip_pay_status?.toLowerCase() === "paid" && "<%= trip.trip_status %>" == "paid_cancel") {
           requestData.trip_status = "completed";
         }

    // Receiver fields
    const receiverName = document.getElementById("receiverName")?.value?.trim();
    const receiverCode = document.getElementById("receiverCountryCode")?.value?.trim();
    const receiverPhone = document.getElementById("receiverPhone")?.value?.trim();
    const deliveryNotes = document.getElementById("deliveryNotes")?.value?.trim();
    const deliveryImageInput = document.getElementById("deliveryImage")?.files;

    if (receiverName || receiverCode || receiverPhone || deliveryNotes || deliveryImageInput.length > 0) {
        requestData.receiver_name = receiverName || '';
        requestData.receiver_country_code = receiverCode || '';
        requestData.receiver_phone = receiverPhone || '';
        requestData.delivery_notes = deliveryNotes || '';

        // Convert file → Base64
        if (deliveryImageInput.length > 0) {
            const file = deliveryImageInput[0];
            requestData.delivery_image = await new Promise((resolve) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result.split(",")[1]);
                reader.readAsDataURL(file);
            });
        }
    }

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

    fetch("/admin/update-trip/<%= trip.trip_id %>", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(requestData)
    })
    .then(res => res.json())
    .then(data => {
        document.getElementById("loaderOverlay").style.display = "none";

        if (data.trip) {
            Swal.fire({
                icon: "success",
                title: "Updated!",
                text: "Trip updated successfully."
            }).then(() => window.location.reload());
        } else {
            Swal.fire({ icon: "error", text: data.message });
        }
    })
    .catch(err => {
        document.getElementById("loaderOverlay").style.display = "none";
        Swal.fire({ icon: "error", text: "API error" });
        console.error(err);
    });

});
</script>



<script>
     let map, directionsService, directionsRenderer;

     function initMap() {
       directionsService = new google.maps.DirectionsService();

       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();
         } else {
           // Clear lat/lng when place is cleared
           latElement.value = '';
           lngElement.value = '';
         }
       }

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

       // Also listen for manual input clearing
       pickupInput.addEventListener('input', function() {
         if (!this.value.trim()) {
           pickupLat.value = '';
           pickupLng.value = '';
           calculateRoute(); // Recalculate when cleared
         }
       });

       dropInput.addEventListener('input', function() {
         if (!this.value.trim()) {
           dropLat.value = '';
           dropLng.value = '';
           calculateRoute(); // Recalculate when cleared
         }
       });

       var cfg = window.EDIT_TRIP_MULTISTOPS || {};
       var isRequestMode = !!cfg.isRequest;
       var MAX_STOPS = Math.max(1, parseInt(cfg.maxStops, 10) || 3);
       var stopsData = [];
       if (Array.isArray(cfg.initialStops)) {
         for (var i = 0; i < cfg.initialStops.length; i++) {
           var s = cfg.initialStops[i];
           stopsData.push({ status: s.status || "active", lat: String(s.lat || ""), lng: String(s.lng || ""), id: s.id || "Stop_" + (i + 1), zoneId: String(s.zoneId || "0"), address: s.address || "" });
         }
       }

       function syncStopsInputEdit(skipRoute) {
         var el = document.getElementById("stopsInput");
         var complete = (stopsData || []).filter(function(s) { return s.lat && s.lng && s.address; });
         if (el) el.value = JSON.stringify(complete);
         if (!skipRoute) calculateRoute(); // Always calculate when stops change
       }
       window.syncStopsInputEdit = syncStopsInputEdit;

       function addStopRowEdit(stop, index) {
         var list = document.getElementById("stopsList");
         if (!list) return;
         var wrap = document.createElement("div");
         wrap.className = "flex gap-2 items-center stop-row";
         wrap.dataset.stopIndex = index;
         var isEdit = isRequestMode;
         if (isEdit) {
           wrap.innerHTML = '<div class="flex-1 relative"><div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none h-[42px]"><i class="fas fa-map-pin text-amber-500 text-sm"></i></div><input type="text" class="stop-address block w-full pl-9 pr-10 py-2 border border-gray-300 rounded-md text-sm" placeholder="Stop address" data-idx="' + index + '" value="' + (stop.address || "").replace(/"/g, "&quot;") + '"></div><input type="hidden" class="stop-lat" data-idx="' + index + '" value="' + (stop.lat || "") + '"><input type="hidden" class="stop-lng" data-idx="' + index + '" value="' + (stop.lng || "") + '"><button type="button" class="remove-stop text-red-600 hover:text-red-800 p-2" data-idx="' + index + '" title="Remove stop"><i class="fas fa-trash-alt text-sm"></i></button>';
           list.appendChild(wrap);
           var inp = wrap.querySelector(".stop-address");
           var ac = new google.maps.places.Autocomplete(inp);
           ac.addListener("place_changed", function() {
             var p = ac.getPlace();
             if (p.geometry && p.geometry.location) {
               var idx = parseInt(inp.dataset.idx, 10);
               stopsData[idx] = stopsData[idx] || {};
               stopsData[idx].lat = String(p.geometry.location.lat());
               stopsData[idx].lng = String(p.geometry.location.lng());
               stopsData[idx].address = p.formatted_address || inp.value;
               stopsData[idx].status = "active";
               stopsData[idx].id = "Stop_" + (idx + 1);
               stopsData[idx].zoneId = stopsData[idx].zoneId || "0";
               wrap.querySelector(".stop-lat").value = stopsData[idx].lat;
               wrap.querySelector(".stop-lng").value = stopsData[idx].lng;
               syncStopsInputEdit();
             } else {
               // Clear lat/lng when address is cleared
               var idx = parseInt(inp.dataset.idx, 10);
               stopsData[idx] = stopsData[idx] || {};
               stopsData[idx].lat = "";
               stopsData[idx].lng = "";
               wrap.querySelector(".stop-lat").value = "";
               wrap.querySelector(".stop-lng").value = "";
               syncStopsInputEdit();
             }
           });
           
           // Also listen for manual clearing of stop address
           inp.addEventListener('input', function() {
             if (!this.value.trim()) {
               var idx = parseInt(inp.dataset.idx, 10);
               stopsData[idx] = stopsData[idx] || {};
               stopsData[idx].lat = "";
               stopsData[idx].lng = "";
               wrap.querySelector(".stop-lat").value = "";
               wrap.querySelector(".stop-lng").value = "";
               syncStopsInputEdit();
             }
           });
           
           wrap.querySelector(".remove-stop").addEventListener("click", function() {
             wrap.remove();
             var rows = list.querySelectorAll(".stop-row");
             stopsData = [];
             for (var r = 0; r < rows.length; r++) {
               var row = rows[r];
               var addr = row.querySelector(".stop-address");
               var lat = row.querySelector(".stop-lat");
               var lng = row.querySelector(".stop-lng");
               if (addr && lat && lng) { 
                 stopsData.push({ 
                   status: "active", 
                   lat: lat.value, 
                   lng: lng.value, 
                   id: "Stop_" + (stopsData.length + 1), 
                   zoneId: "0", 
                   address: addr.value 
                 }); 
               }
               row.dataset.stopIndex = r;
               if (addr) addr.dataset.idx = r;
               if (lat) lat.dataset.idx = r;
               if (lng) lng.dataset.idx = r;
               var rb = row.querySelector(".remove-stop");
               if (rb) rb.dataset.idx = r;
             }
             syncStopsInputEdit();
           });
         } else {
           var addr = (stop.address || "—").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
           wrap.innerHTML = '<div class="flex-1 py-2 px-3 bg-gray-50 rounded border text-sm"><i class="fas fa-map-pin text-amber-500 mr-2"></i>' + addr + '</div>';
           list.appendChild(wrap);
         }
       }

       var addBtn = document.getElementById("addStopBtn");
       if (addBtn && isRequestMode) {
         addBtn.addEventListener("click", function() {
           if (stopsData.length >= MAX_STOPS) { Swal.fire({ icon: "warning", title: "Max stops", text: "You can add at most " + MAX_STOPS + " stops." }); return; }
           var stop = { status: "active", lat: "", lng: "", id: "Stop_" + (stopsData.length + 1), zoneId: "0", address: "" };
           stopsData.push(stop);
           addStopRowEdit(stop, stopsData.length - 1);
           syncStopsInputEdit();
         });
       }

       for (var i = 0; i < stopsData.length; i++) addStopRowEdit(stopsData[i], i);
       syncStopsInputEdit();

       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
         
         // Check if we have pickup location but no drop location (distance 0)
         calculateRoute();
       });

       function calculateRoute() {
         // Check if we have at least pickup location
         if (!pickupLat.value || !pickupLng.value) {
           console.log("No pickup location, cannot calculate fare");
           return;
         }
         
         // If no drop location, calculate fare with 0 distance
         if (!dropLat.value || !dropLng.value) {
           console.log("No drop location, calculating fare with 0 distance");
           calculateFareWithZeroDistance();
           return;
         }
         
         var waypoints = [];
         var validStops = (typeof stopsData !== "undefined" ? stopsData : []).filter(function(s) { return s.lat && s.lng; });
         for (var i = 0; i < validStops.length; i++) {
           waypoints.push({ location: new google.maps.LatLng(parseFloat(validStops[i].lat), parseFloat(validStops[i].lng)), stopover: true });
         }
         var 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,
         };
         if (waypoints.length) request.waypoints = waypoints;

         directionsService.route(request, function(result, status) {
           if (status !== google.maps.DirectionsStatus.OK) {
             console.error("Directions request failed: " + status);
             // Even if route fails, calculate fare with 0 distance
             calculateFareWithZeroDistance();
             return;
           }
           var legs = (result.routes[0] && result.routes[0].legs) || [];
           var distance = 0, time = 0;
           for (var i = 0; i < legs.length; i++) {
             distance += (legs[i].distance && legs[i].distance.value) ? legs[i].distance.value : 0;
             time += (legs[i].duration && legs[i].duration.value) ? legs[i].duration.value : 0;
           }
           distance = distance / 1000;
           time = Math.ceil(time / 60);

           tripDistance.value = distance;
           tripTime.value = time;
           
           // Safely update distance elements
           const td = document.getElementById("trip_distance");
           if (td) td.value = distance.toFixed(2);
           
           const jd = document.getElementById("jobDistance");
           if (jd) jd.innerText = distance.toFixed(2) + " <%=dunit%>";
           
           const jdi = document.getElementById("jobDistanceInput");
           if (jdi) jdi.value = distance.toFixed(2);
           
           const jt = document.getElementById("jobTime");
           if (jt) jt.innerText = time + " min";
           
           const jti = document.getElementById("jobTimeInput");
           if (jti) jti.value = time;
           
           var ov = result.routes[0] && result.routes[0].overview_polyline;
           var polyStr = (ov && ov.points) ? ov.points : (typeof ov === "string" ? ov : "");
           var polyEl = document.getElementById("polyline");
           if (polyEl) polyEl.value = polyStr;
           
           const categorySelect = document.getElementById("categorySelect");
           if (categorySelect && categorySelect.value) calculateFare(categorySelect.value);
         });
       }

       // New function to calculate fare when distance is 0
       function calculateFareWithZeroDistance(cat_id = null) {
         const categorySelect = document.getElementById("categorySelect");
         const catId = cat_id || categorySelect?.value;
         
         if (!catId) {
           console.log("No category selected");
           // If no category selected yet, use the first available one
           if (categorySelect && categorySelect.options.length > 1) {
             const firstCategoryId = categorySelect.options[1].value;
             calculateFare(firstCategoryId, true);
           }
           return;
         }
         
         // Set distance and time to 0
         if (tripDistance) tripDistance.value = 0;
         if (tripTime) tripTime.value = 0;
         
         const td = document.getElementById("trip_distance");
         if (td) td.value = "0";
         
         const jd = document.getElementById("jobDistance");
         if (jd) jd.innerText = "0 <%=dunit%>";
         
         const jdi = document.getElementById("jobDistanceInput");
         if (jdi) jdi.value = "0";
         
         const jt = document.getElementById("jobTime");
         if (jt) jt.innerText = "0 min";
         
         const jti = document.getElementById("jobTimeInput");
         if (jti) jti.value = "0";
         
         // Calculate fare with 0 distance
         calculateFare(catId, true);
       }

       async function calculateFare(cat_id, zeroDistance = false) {
         // 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 = zeroDistance ? "0" : (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 = "<%= trip.user_id %>" || document.getElementById("user_id")?.value;
         const tripDate = document.getElementById("trip_datetime")?.value;
         const cityId = "<%= city_id %>";
         const promoCodeInput = document.getElementById("promo_code");
         const promo_code = p ? promoCodeInput.value.trim() : '';
         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(`${NODE_API_BASE_URL}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');
             }
             
             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
               document.getElementById("loaderOverlay").style.display = "none";
               return;
             } else {
               Swal.fire({
                 icon: 'success',
                 title: 'Promo code applied successfully',
               });
             }
           } catch (error) {
             console.error('Error validating promo code:', error);
             Swal.fire({
               icon: 'error',
               title: 'Invalid Promo Code',
               text: 'Failed to validate promo code. Please try again.'
             });
             document.getElementById("loaderOverlay").style.display = "none";
             return;
           }
         }

         // 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(`${NODE_API_BASE_URL}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');
             if (packageSelect) {
               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;
         }

         // Allow fare calculation even if drop location is missing (distance will be 0)
         if (!pickupLat || !pickupLng) {
           document.getElementById("loaderOverlay").style.display = "none";
           console.error("Missing required pickup location data");
           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 || pickupLat, // Use pickup as drop if missing
               trip_scheduled_drop_lng: dropLng || pickupLng, // Use pickup as drop if missing
               trip_distance: distance,
               trip_hrs: duration,
               trip_from_loc: pickupAddress,
               trip_to_loc: dropAddress || pickupAddress, // Use pickup as drop if missing
               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(`${NODE_API_BASE_URL}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 || pickupAddress); // Use pickup as drop if missing
             formData.append('trip_scheduled_drop_lat', dropLat || pickupLat); // Use pickup as drop if missing
             formData.append('trip_scheduled_drop_lng', dropLng || pickupLng); // Use pickup as drop if missing
             formData.append('polyline', polyline || "0");
             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(`${NODE_API_BASE_URL}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";

             // Helper function to safely update text/content
             function safeUpdate(id, value, isValue = false) {
               const element = document.getElementById(id);
               if (element) {
                 if (isValue) {
                   element.value = value;
                 } else {
                   element.innerText = value;
                 }
               } else {
                 console.warn(`Element with id "${id}" not found`);
               }
             }

             // 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
             safeUpdate("basePrice", `<%= city_cur %>${Number(base_price).toFixed(2)}`);
             safeUpdate("basePriceInput", base_price, true);

             safeUpdate("farePerKM", `<%= city_cur %>${Number(fare_per_km).toFixed(2)}`);
             safeUpdate("farePerKMInput", fare_per_km, true);

             safeUpdate("farePerMin", `<%= city_cur %>${Number(fare_per_min).toFixed(2)}`);
             safeUpdate("farePerMinInput", fare_per_min, true);

             safeUpdate("promoAmount", `<%= city_cur %>${Number(data.trip_promo_amt)?.toFixed(2) || '0.00'}`);
             safeUpdate("promoAmountInput", data.trip_promo_amt || '0.00', true);
             
             // Check if promo_amt element exists before updating
             const promoAmtElement = document.getElementById("promo_amt");
             if (promoAmtElement) {
               promoAmtElement.value = data.trip_promo_amt || '0.00';
             }
             
             safeUpdate("gstAmount", `<%= city_cur %>${Number(data.tax_amt)?.toFixed(2) || '0.00'}`);
             safeUpdate("gstAmountInput", data.tax_amt || '0.00', true);
             
             safeUpdate("adjustAmount", `<%= city_cur %>${Number(data.adjust_amt)?.toFixed(2) || '0.00'}`);
             safeUpdate("adjustAmountInput", data.adjust_amt || '0.00', true);
             
             safeUpdate("grossFare", `<%= city_cur %>${Number(data.trip_pay_amount)?.toFixed(2) || '0.00'}`);
             safeUpdate("grossFareInput", data.trip_pay_amount || '0.00', true);
             
             // Check if trip_pay_amount element exists
             const tripPayAmountElement = document.getElementById("trip_pay_amount");
             if (tripPayAmountElement) {
               tripPayAmountElement.value = data.trip_pay_amount || '0.00';
             }
             
             // Also update the trip distance display if it's showing old value
             safeUpdate("trip_distance", distance);
             safeUpdate("jobDistance", distance + " <%=dunit%>");
             
             console.log("Fare updated with distance:", distance);
           } else {
             console.error("No fare data returned from API");
             document.getElementById("loaderOverlay").style.display = "none";
             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
           function safeUpdate(id, value, isValue = false) {
             const element = document.getElementById(id);
             if (element) {
               if (isValue) {
                 element.value = value;
               } else {
                 element.innerText = value;
               }
             }
           }

           safeUpdate('basePrice', ` ${Number(baseFare).toFixed(2)}`);
           safeUpdate('basePriceInput', baseFare, true);
           
           safeUpdate('farePerKM', ' 0.00');
           safeUpdate('farePerKMInput', 0, true);
           
           safeUpdate('farePerMin', ' 0.00');
           safeUpdate('farePerMinInput', 0, true);
           
           safeUpdate('gstAmount', ` ${Number(taxAmount).toFixed(2)}`);
           safeUpdate('gstAmountInput', taxAmount, true);
           
           safeUpdate('grossFare', ` ${Number(packagePrice).toFixed(2)}`);
           safeUpdate('grossFareInput', packagePrice, true);
           
           const tripPayAmountElement = document.getElementById('trip_pay_amount');
           if (tripPayAmountElement) {
             tripPayAmountElement.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
           };
         }
       });

       document.getElementById("categorySelect")?.addEventListener("change", function() {
         const categorySelect = document.getElementById("categorySelect");
         console.log("Selected Category ID:", categorySelect.value);
         
         // Always calculate fare when category changes
         calculateRoute();
       });

       // Trigger initial fare calculation if category is already selected
       document.addEventListener('DOMContentLoaded', function() {
         const categorySelect = document.getElementById("categorySelect");
         if (categorySelect && categorySelect.value) {
           setTimeout(() => {
             calculateRoute();
           }, 1000); // Wait a bit for everything to load
         }
       });
     }
   </script>

   <%- footer %>





   <script src="https://maps.googleapis.com/maps/api/js?key=<%= GoogleMapsAPIKey%>&libraries=places&callback=initMap" async defer></script>