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

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

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

    .select2-selection__rendered {
      width: 80px !important;
    }

    .select2-container .select2-selection--single {
      height: 47px !important;
      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: 100px !important;
    }

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

    .rl {
      --bs-gutter-x: -0.75rem !important;
    }

    .is-invalid {
      border-color: #dc3545 !important;
    }
    
    .text-danger {
      color: #dc3545;
      font-size: 0.875em;
    }
  </style>

  <div class="container flex-1 pt-20 w-full my-4">
    <%- include('../../partials/utils/title.ejs', {title: "Add Owner"}) %>

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

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

    <div class="mt-4">
      <div class="bg-white shadow-md rounded-lg" style="padding: 20px;">
        <form id="addOwnerForm" enctype="multipart/form-data">

          <!-- Two-column layout for form fields -->
          <div class="row">
            <!-- First Column -->
            <div class="col-md-6">
              <div class="mb-3">
                <label for="d_fname" class="form-label">First Name</label>
                <input type="text" class="form-control" id="d_fname" name="d_fname" oninput="this.value = this.value.replace(/^\s+/, '')">
                <div class="text-danger" id="d_fname-error"></div>
              </div>
              <div class="mb-3">
                <label for="d_lname" class="form-label">Last Name</label>
                <input type="text" class="form-control" id="d_lname" name="d_lname" oninput="this.value = this.value.replace(/^\s+/, '')">
                <div class="text-danger" id="d_lname-error"></div>
              </div>
              
              <div class="mb-3">
                <label for="d_email" class="form-label">Email ID</label>
                <input type="email" class="form-control" id="d_email" name="d_email" pattern="^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$">
                <div class="text-danger" id="d_email-error"></div>
              </div>
            </div>

            <!-- Second Column -->
            <div class="col-md-6">
              <div class="mb-1">
                <label for="d_phone" class="form-label">Contact Phone</label>
                <div class="row rl">
                  <div class="col-auto" style="padding-right: 0;">
                    <select class="form-select" id="c_code" name="c_code" style="min-width: 90px;"></select>
                  </div>
                  <div class="col">
                    <input type="text" class="form-control" id="d_phone" name="d_phone" oninput="this.value = this.value.replace(/[^0-9]/g, '')" placeholder="Enter phone number">
                  </div>
                </div>
                <div class="text-danger" id="d_phone-error"></div>
              </div>

              <div class="mb-3">
                <label for="d_gender" class="form-label">Gender</label>
                <select class="form-select" id="d_gender" name="d_gender">
                  <option value="" selected disabled>Please select gender</option>
                  <option value="male">Male</option>
                  <option value="female">Female</option>
                 </select>
                <div class="text-danger" id="d_gender-error"></div>
              </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 class="text-danger" id="city_id-error"></div>
              </div>

              <!-- Profile Photo -->
              <div class="mb-3">
                <label for="image_id" class="form-label">Profile Photo</label>
                <input type="file" class="form-control validate-image" id="image_id" name="image_id" accept=".jpg, .jpeg" data-preview="profilePreview" data-error="profilePicError">
                <img src="" class="img-thumbnail mt-2" width="100" style="display: none;" alt="Profile Photo" id="profilePreview">
                <small id="profilePicError" class="text-danger mt-1"></small>
                <div class="text-danger" id="image_id-error"></div>
              </div>
            </div>
          </div>

          <!-- Submit button (full width) -->
          <div style="display: flex; justify-content: end; gap: 10px;">
            <button type="button" class="btn btn-secondary" onclick="window.location.href='/admin/owner'">Cancel</button>
            <button type="submit" class="btn btn-primary">Add Owner</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</main>

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

<script>
  // Define form configuration
  const formConfig = {
    formId: "addOwnerForm",
    fields: [
      {
        name: "d_fname",
        type: "text",
        required: true,
        messages: {
          required: "First name is required"
        }
      },
      {
        name: "d_lname",
        type: "text",
        required: true,
        messages: {
          required: "Last name is required"
        }
      },
      {
        name: "d_email",
        type: "email",
        required: true,
        messages: {
          required: "Email is required",
          invalid: "Please enter a valid email address"
        }
      },
      {
        name: "c_code",
        type: "select",
        required: true,
        messages: {
          required: "Please select country code"
        }
      },
      {
        name: "d_phone",
        type: "phone",
        required: true,
        messages: {
          required: "Phone number is required",
          invalid: "Phone number must be 6-15 digits"
        }
      },
      {
        name: "city_id",
        type: "select",
        required: true,
        messages: {
          required: "Please select location"
        }
      },
      {
        name: "d_gender",
        type: "select",
        required: true,
        messages: {
          required: "Please select gender"
        }
      },
      {
        name: "image_id",
        type: "file",
        required: true,
        messages: {
          required: "Profile photo is required"
        }
      }
    ]
  };

  // Initialize when DOM is ready
  document.addEventListener('DOMContentLoaded', () => {
    // Initialize form validation
    const formValidator = setupFormValidation(formConfig.formId, formConfig.fields);

    // Profile picture validation
    const profilePicInput = document.getElementById('image_id');
    if (profilePicInput) {
      const profilePicError = document.getElementById('profilePicError');

      profilePicInput.addEventListener('change', function() {
        const file = this.files[0];
        const preview = document.getElementById('profilePreview');
        profilePicError.textContent = '';

        if (file) {
          const validTypes = ['image/jpeg', 'image/jpg'];
          if (!validTypes.includes(file.type)) {
            profilePicError.textContent = 'Only JPG/JPEG images are allowed';
            this.value = '';
            preview.style.display = 'none';
          } else if (file.size > 2 * 1024 * 1024) { // 2MB
            profilePicError.textContent = 'Image size must be less than 2MB';
            this.value = '';
            preview.style.display = 'none';
          } else {
            // Show preview
            const reader = new FileReader();
            reader.onload = function(e) {
              preview.src = e.target.result;
              preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
          }
        } else {
          preview.style.display = 'none';
        }
      });
    }

    // Helper function to convert file to base64
    function getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const base64 = reader.result.split(',')[1];
          const type = file.type.split('/')[1];
          resolve({ base64, type });
        };
        reader.onerror = error => reject(error);
      });
    }

    // Form submission handler
    const form = document.getElementById('addOwnerForm');
    if (form) {
      form.addEventListener('submit', async function(e) {
        e.preventDefault();

        // Validate form before proceeding
        if (!formValidator.validateForm()) {
          return; // Stop if validation fails
        }

        // Get form data
        const formData = new FormData(this);
        const ccode = document.getElementById("c_code").value.trim().replace(/\D/g, '');
        const phone = document.getElementById("d_phone").value.trim();

        try {
          // Show loading
          document.getElementById("loaderOverlay").style.display = "flex";

          // Handle profile image as base64 (like driver profile)
          const profilePicInput = document.getElementById('image_id');
          if (profilePicInput && profilePicInput.files[0]) {
            const { base64, type } = await getBase64(profilePicInput.files[0]);
            formData.append('driver_image', base64);
            formData.append('image_type', type);
            // Remove the file input from formData
            formData.delete('image_id');
          }

          // Submit the form data directly
          const submitResponse = await fetch('/admin/owner/add', {
            method: 'POST',
            body: formData
          });

          const result = await submitResponse.json();

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

          if (result.success) {
            await Swal.fire({
              icon: "success",
              title: "Success!",
              text: result.message || "Owner added successfully",
              timer: 1500,
              showConfirmButton: false
            });
            
            // Redirect based on owner status
            const redirectUrl = result.d_active === 1 ? '/admin/owner/active' : '/admin/owner/inactive';
            window.location.href = redirectUrl;
          } else {
            Swal.fire({
              icon: "error",
              title: "Failed!",
              text: result.message || "Error adding owner",
            });
          }
        } catch (error) {
          document.getElementById("loaderOverlay").style.display = "none";
          console.error("Error:", error);
          Swal.fire({
            icon: "error",
            title: "Request Failed",
            text: error.message || "Unknown error occurred",
          });
        }
      });
    }

    // Initialize cities dropdown
    fetch('/admin/getcities')
      .then(res => res.json())
      .then(cities => {
        window.citiesData = cities.data; // Store for country code lookup
        initCityDropdown(cities);
        
        // Trigger country code selection after city dropdown is ready
        setTimeout(() => {
          const $citySelect = $('#city_id');
          if ($citySelect.val()) {
            const selectedCityId = $citySelect.val();
            const selectedCity = window.citiesData.find(c => c.city_id == selectedCityId);
            
            if (selectedCity && selectedCity.country_code && window.countryCodes) {
              const matchingCountry = window.countryCodes.find(c => c.id == selectedCity.country_code);
              if (matchingCountry) {
                const $countrySelect = $('#c_code');
                const newValue = `+${matchingCountry.id}`;
                $countrySelect.val(newValue).trigger('change');
                console.log(`Initial country code set to: ${newValue} for phone code ${selectedCity.country_code}`);
              }
            }
          }
        }, 600);
      });

    function initCityDropdown(cities) {
      const cityDropdown = document.getElementById('city_id');
      cityDropdown.innerHTML = '<option value="">Select Location</option>';

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

      // If only one city, auto-select and lock it visually
      if (cities.data.length === 1) {
        const singleCity = cities.data[0];
        cityDropdown.value = singleCity.city_id;
        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";
      }
    }
  });

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

  // Country code select2 initialization
  document.addEventListener('DOMContentLoaded', () => {
    fetch("/countryCode.json")
      .then(res => res.json())
      .then(data => {
        window.countryCodes = data; // Store globally
        const $select = $('#c_code');

        data.forEach(country => {
          const isSelected = country.id === '<%= country_code %>';
          const option = new Option(
            `${getFlagEmoji(country.code)} +${country.id} (${country.name})`,
            `+${country.id}`,
            isSelected,
            isSelected
          );
          option.dataset.iso = country.code;
          $select.append(option);
        });

        // Initialize Select2
        $select.select2({
          placeholder: "Country",
          width: 'resolve',
          templateSelection: function (data) {
            return data.id;
          }
        });
        
        // Set country code from server
        $select.val('+<%= country_code %>').trigger('change');
      })
      .catch(err => {
        console.error("Failed to load country codes:", err);
      });
  });
</script>

<%- footer %>