<%- header %>
  <!-- pre-rendered navbar inserted -->
  <main class="dashboard-main">
    <%- navbar %>
      <!-- pre-rendered navbar inserted -->
      <% const isMasking=typeof enableMasking !=="undefined" ? enableMasking : true; function maskName(name) { if
        (!name) return "" ; if (!isMasking) return name; return name.substring(0, 3) + "***" ; } function
        maskEmail(email) { if (!email) return "" ; 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 "" ; if
        (!isMasking) return phone; const visible=phone.slice(0, 2); const masked="*" .repeat(phone.length - 2); return
        visible + masked; } %>

        <style>
          @media (max-width: 576px) {
            #countryCode {
              max-width: 100px !important;
            }
          }

          .select2,
          .select2-selection,
          .selection {
            width: auto !important;
          }

          .select2-selection__rendered {
            max-width: 160px !important;
            padding-left: 18px !important;
            padding-right: 28px !important;
          }

          .select2-container .select2-selection--single {
            border-bottom-right-radius: 0px !important;
            border-top-right-radius: 0px !important;
          }

          .select2-dropdown {
            min-width: 320px !important;
            width: 100% !important;
          }

          .select2-container {
            max-width: 160px !important;
          }

          #phone_masked {
            border-top-left-radius: 0px !important;
            border-bottom-left-radius: 0px !important;
          }

          #phone {
            /* width: 89% !important; */
            /* float: right !important; */
            border-top-left-radius: 0px !important;
            border-bottom-left-radius: 0px !important;
          }

          .rl {
            --bs-gutter-x: -0.75rem !important;
          }
        </style>

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

          <%- include('../../partials/utils/title.ejs', {title: "Edit Passenger" }) %>

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

                <!-- Black Transparent Loader Overlay -->
                <div id="loaderOverlay"
                  class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                  <div class="animate-spin rounded-full h-12 w-12 border-t-4 border-blue-500 border-solid"></div>
                </div>


                <div class="mt-4">
                  <div class="bg-white shadow-md rounded-lg" style="padding: 20px;">
                    <form id="editUserForm" enctype="multipart/form-data">
                      <input type="hidden" name="user_id" id="user_id" value="<%= user.user_id %>">
                      <input type="hidden" name="api_key" id="api_key" value="<%= user.api_key %>">
                      <!-- Two-column layout for form fields -->
                      <div class="row">
                        <!-- First Column -->
                        <div class="col-md-6">
                          <div class="mb-3">
                            <label for="u_fname_masked" class="form-label">First Name</label>
                            <!-- Masked visible field -->
                            <input type="text" class="form-control" id="u_fname_masked"
                              value="<%= maskName(user.u_fname) %>">
                            <!-- Hidden real-value field -->
                            <input type="hidden" name="u_fname" id="u_fname" value="<%= user.u_fname %>">
                          </div>

                          <div class="mb-3">
                            <label for="u_lname_masked" class="form-label">Last Name</label>
                            <input type="text" class="form-control" id="u_lname_masked"
                              value="<%= maskName(user.u_lname) %>">
                            <input type="hidden" name="u_lname" id="u_lname" value="<%= user.u_lname %>">
                          </div>


                        </div>
                        <div class="col-md-6">

                          <!-- Second Column -->
                          <div class="mb-3">
                            <label for="email_masked" class="form-label">Email <span
                                class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email_masked" value=""
                              placeholder="<%= maskEmail(user.u_email) %>">
                            <input type="hidden" name="email" id="email" value="<%= user.u_email %>">
                          </div>

                          <div class="mb-3">
                            <label for="phone_masked" class="form-label">Phone</label>
                            <div class="row gx-1">
                              <div class="col-auto" style="padding-right: 0;">
                                <select class="form-select" id="countryCode" name="countryCode"></select>
                              </div>
                              <div class="col ps-0">
                                <input type="text" class="form-control" id="phone_masked"
                                  value="<%= maskPhone(user.u_phone) %>">
                                <input type="hidden" name="phone" id="phone" value="<%= user.u_phone %>">
                              </div>
                            </div>
                          </div>
                        </div>

                        <div class="col-md-6">
                          <div class="mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status">
                              <option value="1" <%=user.active=='1' ? 'selected' : '' %>>Active</option>
                              <option value="0" <%=user.active=='0' ? 'selected' : '' %>>Inactive</option>
                            </select>
                          </div>
                          <div class="mb-3">
                            <label for="city_id" class="form-label">Location</label>
                            <select class="form-select" id="city_id" name="city_id">
                              <option value="">Loading cities...</option>
                            </select>
                          </div>

                        </div>
                        <div class="col-md-6">
                          <div class="mb-3 d-none">
                            <label for="text_password" class="form-label">Password</label>
                            <input type="text" class="form-control" id="text_password" name="text_password">
                          </div>
                          <!-- <div class="mb-3">
                   <label for="u_gender" class="form-label">Gender</label>
                   <select class="form-select" id="u_gender" name="u_gender">
                    <option value="" selected disabled>Please select gender</option>
                     <option value="Male" <%= user.u_gender.toLowerCase() === 'male' ? 'selected' : '' %>>Male</option>
                     <option value="Female" <%= user.u_gender.toLowerCase() === 'female' ? 'selected' : '' %>>Female</option>
                    </select>
                 </div> -->
                          <!-- Profile Picture (full width) -->
                          <div class="mb-3">
                            <label for="profilePic" class="form-label">Profile Picture</label>
                            <input type="file" class="form-control" id="profilePic" name="profilePic"
                              accept=".jpg, .jpeg, .png">
                            <% if (user?.image?.img_path) { %>
                              <img src="<%= IMAGE_FOLDER_PATH %><%= user?.image?.img_path %>" class="img-thumbnail mt-2"
                                width="100" alt="Profile Picture">
                              <% } else { %>
                                <img src="/placeholder.jpg" class="img-thumbnail mt-2" width="100"
                                  alt="Default Profile Picture">
                                <% } %>
                          </div>
                        </div>
                        <div id="testDriverContainer" style="  display: none;">
                          <div class="form-check"
                            style="display: flex; justify-content: start; align-items: center; gap: 10px; margin-bottom: 20px;">
                            <input type="checkbox" id="is_test" name="is_test" <%=user.is_test==1 ? "checked" : "" %>
                            class="form-check-input" />
                            <label for="is_test" class="form-check-label">Test Passenger</label>
                          </div>
                        </div>
                      </div>

                      <!-- Trip Permissions Section -->
                      <!-- <div class="row mb-3">
               <div class="col-md-6">
                 <label class="form-label" style="font-weight: 600; font-size: 1rem; margin-bottom: 0.75rem;">Trip Permissions</label>
                 <div class="card" style="border: 2px solid #0d6efd; border-radius: 8px; box-shadow: 0 2px 4px rgba(13, 110, 253, 0.1); margin-top: 10px;">
                   <div class="card-body" style="padding: 1rem;">
                     <% 
                       let tripPerm = {};
                       try {
                         tripPerm = user.trip_perm ? (typeof user.trip_perm === 'string' ? JSON.parse(user.trip_perm) : user.trip_perm) : {};
                       } catch(e) {
                         tripPerm = {};
                       }
                     %>
                     <div class="d-flex align-items-center justify-content-between">
                       <label class="form-label mb-0" style="font-weight: 500; font-size: 0.95rem; margin-top: 0px !important;" for="create_trip">Create Trip</label>
                       <div class="form-check form-switch">
                         <input class="form-check-input" type="checkbox" role="switch" id="create_trip" name="trip_perm[create_trip]" value="1" <%= tripPerm.create_trip == "1" ? "checked" : "" %> style="width: 3rem; height: 1.5rem; cursor: pointer;">
                       </div>
                     </div>
                   </div>
                 </div>
               </div>
             </div> -->

                      <!-- Submit button (full width) -->
                      <div style="display: flex; justify-content: end; align-items: center;">
                        <button type="submit" class="btn btn-primary">Update Passenger</button>
                      </div>
                    </form>
                  </div>
                </div>
        </div>
  </main>


  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.has('is_test')) {
        document.getElementById('testDriverContainer').style.display = 'block';
      }
    });
  </script>


  <script>
    let initialValues

    document.getElementById("profilePic").addEventListener("change", function (event) {
      let reader = new FileReader();
      reader.onload = function (e) {
        document.querySelector("img.img-thumbnail").src = e.target.result;
      };
      reader.readAsDataURL(event.target.files[0]);
    });

    // Utility: Get emoji flag from country code
    document.addEventListener("DOMContentLoaded", function () {
      const $select = $('#countryCode');

      function getFlagEmoji(code) {
        return code.toUpperCase().replace(/./g, char =>
          String.fromCodePoint(127397 + char.charCodeAt())
        );
      }

      fetch("/countryCode.json")
        .then(res => res.json())
        .then(data => {
          const rawCode = "<%= user?.c_code || '+91' %>";
          const userCountryCode = rawCode.startsWith('+') ? rawCode : `+${rawCode}`;
          const normalizedUserCode = userCountryCode.replace('+', '');

          data.forEach(country => {
            const value = `+${country.id}`;
            const isSelected = String(country.id) === normalizedUserCode;

            const option = new Option(
              `${getFlagEmoji(country.code)} ${value} (${country.name})`,
              value,
              false,
              isSelected
            );

            $select.append(option);
          });

          $select.select2({
            placeholder: "Select country code",
            width: 'resolve',

            // Show only the code in the selected field
            templateSelection: function (data) {
              return data.id || '';
            }
          });


          initialValues = {
            u_fname: document.getElementById("u_fname").value,
            u_lname: document.getElementById("u_lname").value,
            u_email: document.getElementById("email").value,
            //  u_gender: document.getElementById("u_gender").value,

            u_password: document.getElementById("text_password").value,
            u_phone: document.getElementById("phone").value,
            city_id: "<%= user.city_id %>",
            c_code: $('#countryCode').val(),
            active: document.getElementById("status").value,
            profilePic: document.getElementById("profilePic").files.length > 0 ?
              document.getElementById("profilePic").files[0].name : "",
          };

          if (userCountryCode) {
            $select.val(userCountryCode).trigger('change');
          }
        })
        .catch(err => {
          console.error("Failed to load country codes:", err);
        });
    });
  </script>


  <script>
    function syncMaskedField(maskedId, hiddenId) {
      const masked = document.getElementById(maskedId);
      const hidden = document.getElementById(hiddenId);

      masked.addEventListener('input', function () {
        hidden.value = masked.value; // real value updated in hidden input
      });
    }

    // Apply to all fields
    syncMaskedField('u_fname_masked', 'u_fname');
    syncMaskedField('u_lname_masked', 'u_lname');
    syncMaskedField('email_masked', 'email');
    syncMaskedField('phone_masked', 'phone');

    // Define form configuration
    const formConfig = {
      formId: "editUserForm",
      fields: [{
        name: "u_fname",
        type: "text",
        required: true,
        messages: {
          required: "First name is required"
        }
      },
      {
        name: "u_lname",
        type: "text",
        required: true,
        messages: {
          required: "Last name is required"
        }
      },
      {
        name: "email",
        type: "email",
        required: true,
        messages: {
          required: "Email is required",
          invalid: "Please enter a valid email address"
        }
      },

      {
        name: "countryCode",
        type: "select",
        required: true,
        messages: {
          required: "Please select country code"
        }
      },
      {
        name: "phone",
        type: "phone",
        required: true,
        messages: {
          required: "Phone number is required",
          invalid: "Phone number must be 6-15 digits"
        }
      },
      {
        name: "status",
        type: "select",
        required: true,
        messages: {
          required: "Please select status"
        }
      },
      // {
      //   name: "u_gender",
      //   type: "select",
      //   required: true,
      //   messages: {
      //     required: "Please select gender"
      //   }
      // },
      ]
    };

    // Sync 'is-invalid' class from hidden email to visible email_masked
    document.addEventListener('DOMContentLoaded', function () {
      const hiddenEmail = document.getElementById("email");
      const maskedEmail = document.getElementById("email_masked");
      if (hiddenEmail && maskedEmail) {
        const observer = new MutationObserver(function (mutations) {
          mutations.forEach(function (mutation) {
            if (mutation.attributeName === "class") {
              if (hiddenEmail.classList.contains("is-invalid")) {
                maskedEmail.classList.add("is-invalid");
              } else {
                maskedEmail.classList.remove("is-invalid");
              }
            }
          });
        });
        observer.observe(hiddenEmail, { attributes: true });

        // Also clear error when typing
        maskedEmail.addEventListener('input', function () {
          maskedEmail.classList.remove("is-invalid");
          const errContainer = document.getElementById("email-error");
          if (errContainer) errContainer.textContent = "";
        });
      }
    });
  </script>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const savedCityId = "<%= user.city_id %>"; // user's assigned city

      fetch('/admin/getcities')
        .then(res => res.json())
        .then(cities => {
          initDropdowns(cities, savedCityId);
        });

      function initDropdowns(cities, selectedId) {
        const cityDropdown = document.getElementById('city_id');
        const userGroupId = <%= user.group_id %>;
        const userCityId = <%= user.city_id %>;

        cityDropdown.innerHTML = '<option value="">Select City</option>';

        // Populate dropdown options
        cities.data.forEach(city => {
          const option = document.createElement('option');
          option.value = city.city_id;
          option.textContent = city.city_name;

          // Preselect if matching user's city
          if (String(city.city_id) === String(selectedId)) {
            option.selected = true;
          }

          cityDropdown.appendChild(option);
        });

        // For Corporate (group_id=6) or Company Manager (group_id=5), lock to their city
        if (userGroupId === 5 || userGroupId === 6) {
          cityDropdown.value = userCityId;
          cityDropdown.setAttribute("readonly", true);
          cityDropdown.style.pointerEvents = "none";
          cityDropdown.style.opacity = "0.7";
          cityDropdown.style.background = "#f3f4f6";
        }
        // If only one city, auto-select and disable
        else if (cities.data.length === 1) {
          const singleCity = cities.data[0];
          cityDropdown.value = singleCity.city_id;

          // 🔥 Do NOT disable — instead lock it visually
          cityDropdown.setAttribute("readonly", true);
          cityDropdown.style.pointerEvents = "none";
          cityDropdown.style.opacity = "0.7";
          cityDropdown.style.background = "#f3f4f6";
        } else {
          cityDropdown.removeAttribute("readonly");
          cityDropdown.style.pointerEvents = "auto";
          cityDropdown.style.opacity = "1";
        }

      }
    });
  </script>


  <script src="/js/validator/validation.js"></script>

  <script src="/js/update-user-form-script.js"></script>


  <%- footer %>