   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->

<style>
  #phone{
    width: 100% !important;
  }
</style>

 <script src="/js/demo-protection.js"></script>


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

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


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


    <%- include('../partials/utils/breadcrumb', { breadcrumbs }) %>
<div class="row gy-4" style="margin-bottom: 30px;">
  <div class="col-lg-12">
    <div class="user-grid-card position-relative border radius-16 overflow-hidden bg-base h-100 shadow-sm">
      <!-- Header with cover photo -->
      <div class="cover-photo-container" style="height: 180px; overflow: hidden;">
        <img src="/user-grid-bg1.png" alt="Cover photo" class="w-100 h-100 object-fit-cover" style="filter: brightness(0.95);">
      </div>
      
      <!-- Profile content -->
      <div class="profile-content px-4 pb-4 pt-5">
        <!-- Profile header with avatar -->
        <div class="profile-header text-center mb-4">
          <div class="avatar-container d-inline-block position-relative mb-3" style="margin-top: -100px;">
            <div class="avatar-frame" style="
              width: 120px;
              height: 120px;
              border-radius: 50%;
              border: 4px solid white;
              background: white;
              box-shadow: 0 4px 12px rgba(0,0,0,0.1);
              display: inline-flex;
              justify-content: center;
              align-items: center;
              overflow: hidden;
            ">
              <img src="<%= CATEGORY_BASE_URL %><%= user.image?.img_path %>" alt="Profile photo" 
                   class="h-100 w-100 object-fit-cover"
                   onerror="this.src='https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'">
            </div>
          </div>
          <h5 class="mb-1 fw-semibold" style="font-size: 1.4rem;"><%= user.u_name %></h5>
          <p class="text-muted mb-3"><%= user.u_email %></p>
          <div class="d-flex justify-content-center gap-2 mb-3">
            <span class="badge bg-primary-light bg-opacity-10 text-primary-light px-3 py-1 rounded-pill">
              Admin
            </span>
          </div>
        </div>

        <!-- Personal info section -->
        <div class="personal-info-section bg-light rounded-3 p-4">
          <h6 class="section-title mb-3 fw-semibold d-flex align-items-center">
            <i class="bi bi-person-lines-fill me-2 text-primary-light"></i>
            Personal Information
          </h6>
          
          <div class="info-grid">
            <div class="info-item py-2 border-bottom">
              <div class="d-flex">
                <span class="text-muted flex-shrink-0" style="width: 120px;">Full Name</span>
                <span class="fw-medium text-dark"><%= user.u_name %></span>
              </div>
            </div>
            <div class="info-item py-2 border-bottom">
              <div class="d-flex">
                <span class="text-muted flex-shrink-0" style="width: 120px;">Email</span>
                <span class="fw-medium text-dark"><%= user.u_email %></span>
              </div>
            </div>
            <div class="info-item py-2 border-bottom">
              <div class="d-flex">
                <span class="text-muted flex-shrink-0" style="width: 120px;">Phone</span>
                <span class="fw-medium text-dark"><%= user.u_phone %></span>
              </div>
            </div>
            <div class="info-item py-2">
              <div class="d-flex">
                <span class="text-muted flex-shrink-0" style="width: 120px;">Bio</span>
                <span class="fw-medium text-dark"><%= ADMIN_NAME %> Admin</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Optional action buttons -->
        <!-- <div class="d-flex justify-content-center gap-3 mt-4">
          <button class="btn btn-sm btn-outline-primary rounded-pill px-3">
            <i class="bi bi-pencil me-1"></i> Edit Profile
          </button>
          <button class="btn btn-sm btn-outline-secondary rounded-pill px-3">
            <i class="bi bi-envelope me-1"></i> Message
          </button>
        </div> -->
      </div>
    </div>
  </div>
</div>

<style>
  .user-grid-card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }
  
  .user-grid-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.1) !important;
  }
  
  .section-title {
    font-size: 1.1rem;
    color: #495057;
  }
  
  .info-grid {
    display: grid;
    gap: 0.5rem;
  }
  
  .avatar-frame {
    transition: transform 0.3s ease;
  }
  
  .avatar-frame:hover {
    transform: scale(1.05);
  }
</style>
    <div class="row gy-4">
   
      <div class="col-lg-12">
        <div class="card h-100">
          <div class="card-body p-24">


            <div class="tab-content" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-edit-profile" role="tabpanel" aria-labelledby="pills-edit-profile-tab" tabindex="0">
                <form id="editUserForm" enctype="multipart/form-data">
                  <input type="hidden" name="user_id" id="user_id" value="<%= user.user_id %>">

                  <div class="mb-3">
                    <label for="profilePic" class="form-label">Profile Picture</label>
                    <input type="file" class="form-control" id="profilePic" name="profilePic">
                    <img src="<%= CATEGORY_BASE_URL %><%= user.image?.img_path %>" class="img-thumbnail mt-2" width="100" alt="Profile Picture">
                  </div>

                  <div class="mb-3">
                    <label for="u_fname" class="form-label">First Name</label>
                    <input type="text" class="form-control" id="u_fname" name="u_fname" value="<%= user.u_fname %>" required>
                  </div>

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

                  <div class="mb-3">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email" name="email" value="<%= user.u_email %>" required>
                  </div>

                  <div class="mb-3">
                    <label for="phone" class="form-label">Phone</label>
                    <div class="input-group">
                      <select class="form-select" style="max-width: 180px;" id="countryCode" name="countryCode" required>
                        <option disabled selected>Choose Country</option>
                      </select>
                      <input type="number" class="form-control" id="phone" name="phone" oninput="this.value = this.value.replace(/^\s+/, '')" value="<%= user.u_phone %>" required>
                    </div>
                  </div>

                  <div class="mb-3">
                    <label class="block text-gray-700 font-medium ">Location</label>
                    <select name="is_ride_later" class="w-full px-4 py-2 border form-select rounded-md focus:ring focus:ring-blue-200" required>
                      <option value=0 disabled>Select Location</option>
                      <option value=1>All Countries</option>
                    </select>
                  </div>

                  <!-- <div class="mb-3">
              <label for="Password" class="form-label">Password</label>
              <div class="input-group">
                <input type="password" class="form-control" id="Password" name="Password" value="<%= pass %>" required>
                <button type="button" class="btn btn-outline-secondary" id="togglePassword">
                  Show
                 </button>
              </div>
            </div> -->

                  <script>
                    // Toggle password visibility
                    document.getElementById('togglePassword').addEventListener('click', function() {
                      const passwordField = document.getElementById('Password');
                      const passwordIcon = document.getElementById('passwordIcon');

                      if (passwordField.type === 'password') {
                        passwordField.type = 'text';
                        passwordIcon.classList.remove('bi-eye-slash');
                        passwordIcon.classList.add('bi-eye');
                      } else {
                        passwordField.type = 'password';
                        passwordIcon.classList.remove('bi-eye');
                        passwordIcon.classList.add('bi-eye-slash');
                      }
                    });
                  </script>


                  <div class="mb-3">
                    <label for="u_state" class="form-label">State</label>
                    <input type="text" class="form-control" id="u_state" name="u_state" value="<%= user.u_state %>" required>
                  </div>

                  <div class="mb-3">
                    <label for="u_zip" class="form-label">Zip Code</label>
                    <input type="number" class="form-control" id="u_zip" name="u_zip" value="<%= user.u_zip %>" oninput="this.value = this.value.replace(/^\s+/, '')" required>
                  </div>
                  
                  <% if (user.group_id !== 5 && user.group_id !== 6) { %>
                  <div class="mb-3">
                    <label for="title" class="form-label">Title</label>
                    <input type="text" class="form-control" id="title" name="title" value="<%= user.title %>" required>
                  </div>

                  <div class="mb-3">
                    <label for="logo" class="form-label">Logo</label>
                    <input type="file" class="form-control" id="logo" name="logo">
                    <!-- If a logo exists, display the current logo -->
                    <% if (user.login_logo) { %>
                    <img src="<%= CATEGORY_BASE_URL %><%= user.login_logo %>" class="img-thumbnail mt-2" width="100" alt="Logo">
                    <% } %>
                  </div>

                  <div class="mb-3">
                    <label for="headerLogo" class="form-label">Header Logo</label>
                    <input type="file" class="form-control" id="headerLogo" name="headerLogo">
                    <!-- If a header logo exists, display the current header logo -->
                    <% if (user.header_logo) { %>
                    <img src="<%= CATEGORY_BASE_URL %><%= user.header_logo %>" class="img-thumbnail mt-2" width="100" alt="Header Logo">
                    <% } %>
                  </div>

                  <div class="mb-3">
                    <label for="favicon" class="form-label">Favicon</label>
                    <input type="file" class="form-control" id="favicon" name="favicon">
                    <!-- If a favicon exists, display the current favicon -->
                    <% if (user.fav_icon) { %>
                    <img src="<%= CATEGORY_BASE_URL %><%= user.fav_icon %>" class="img-thumbnail mt-2" width="32" alt="Favicon">
                    <% } %>
                  </div>
                  <% } %>
                  
                  <div style="display: flex; justify-content:end ;">
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                  </div>

                </form>
              </div>


            </div>
          </div>
        </div>
      </div>
    </div>


  </div>

  </div>
  <script>
    // 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"
          }
        },
            {
          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: "u_state",
          type: "text",
          required: true,
          messages: {
            required: "State is required"
          }
        },
        {
          name: "u_zip",
          type: "number",
          required: true,
          messages: {
            required: "Zip Code is required"
          }
        }<% if (user.group_id !== 5 && user.group_id !== 6) { %>,
        {
          name: "title",
          type: "text",
          required: true,
          messages: {
            required: "Title is required"
          }
        },
        {
          name: "logo",
          type: "file",
          required: true,
          existingUrl: "<%= user.login_logo %>", // this is the ID of the img tag
          messages: {
            required: "Logo is required"
          }
        },
        {
          name: "headerLogo",
          type: "file",
          existingUrl: "<%= user.header_logo %>", // this is the ID of the img tag
          required: true,
          messages: {
            required: "Header Logo is required"
          }
        },
        {
          name: "favicon",
          type: "file",
          existingUrl: "<%= user.fav_icon %>", // this is the ID of the img tag
          required: true,
          messages: {
            required: "Favicon is required"
          }
        }<% } %>
      ]
    };
  </script>

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

  <!-- Select2 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

  <!-- jQuery (required by Select2) -->


  <!-- Select2 JS -->
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

  <script>
    // Utility: Get emoji flag from country code
    function getFlagEmoji(code) {
      return code.toUpperCase().replace(/./g, char =>
        String.fromCodePoint(127397 + char.charCodeAt())
      );
    }

    fetch("/countryCode.json")
      .then(res => res.json())
      .then(data => {
        const userCountryCode = "<%= user?.c_code || +91 %>";
        const $select = $('#countryCode');

        data.forEach(country => {
          const value = `+${country.id}`;
          const isSelected = userCountryCode && value === userCountryCode;

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

          $select.append(option);
        });

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

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

    const formValidator = setupFormValidation(
      formConfig.formId,
      formConfig.fields
    );

    document.getElementById('editUserForm').addEventListener('submit', async function(e) {
      e.preventDefault(); // Prevent the default form submission
      const isValid = formValidator.validateForm();

      // If any validation fails, stop
      // if (!isValid) {
      //   console.log('Form validation failed');
      //   return;
      // }
      document.getElementById("loaderOverlay").style.display = "flex";

      // Create a FormData object from the form
      let formData = new FormData(this);
      formData.append("u_name", document.getElementById("u_fname").value + " " + document.getElementById("u_lname").value);

      try {
        // Send the form data to the server via a POST request
        const response = await fetch('/admin/editAdmin', {
          method: 'POST',
          body: formData
        });

        // Parse the JSON response
        const result = await response.json();
        if (result.success) {
          // Display success message using SweetAlert2
          document.getElementById("loaderOverlay").style.display = "none";
          Swal.fire({
            icon: 'success',
            title: 'User updated successfully',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
          });
        } else {
          // Display error message
          document.getElementById("loaderOverlay").style.display = "none";
          Swal.fire({
            icon: 'error',
            title: 'Error updating user',
            text: result.message || 'Something went wrong.',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
          });
        }
      } catch (error) {
        // Handle any network or other errors
        document.getElementById("loaderOverlay").style.display = "none";
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Something went wrong. Please try again.',
          toast: true,
          position: 'top-end',
          showConfirmButton: false,
          timer: 3000,
          timerProgressBar: true,
        });
        console.error("Error during form submission:", error);
      }
    });
  </script>

  <%- footer %>