<%- header %>
  <!-- pre-rendered navbar inserted -->
  <main class="dashboard-main">
    <%- navbar %>
      <!-- pre-rendered navbar inserted -->

      <style>
        .select2-container {
          min-width: 100px !important;
          width: auto !important;
        }

        .select2-selection {
          height: 100% !important;
          padding: 6px 8px !important;
        }

        .select2-selection__rendered {
          line-height: 18px !important;
          padding-left: 6px !important;
        }

        #u_phone {
          width: 70% !important;
        }

        @media (max-width: 576px) {
          #countryCode {
            min-width: 90px !important;
          }
        }

        /* 
       .select2-selection__rendered {
         padding: 0px !important;
       } */
      </style>

      <div class="container flex-1 pt-20 w-full ">
        <%- include('../../partials/utils/title.ejs', {title: "Create Company" }) %>

          <% const breadcrumbs=[ { label: "Dashboard" , href: "/admin/dashboard" , icon: "bi bi-house-door" }, {
            label: "Create Company" } ]; %>

            <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

              <div class="card">
                <div class="card-header">
                  <h6 class="mb-0">Add Company</h6>
                </div>
                <div class="card-body">
                  <form id="subAdminForm" enctype="multipart/form-data">
                    <div class="row mb-3">
                      <div class="col-md-6">
                        <label>First Name</label>
                        <input type="text" name="u_fname" class="form-control" />
                      </div>
                      <div class="col-md-6">
                        <label>Last Name</label>
                        <input type="text" name="u_lname" class="form-control" />
                      </div>
                    </div>

                    <div class="row mb-3">
                      <div class="col-md-6">
                        <label>Email</label>
                        <input type="email" name="u_email" class="form-control" />
                      </div>
                      <div class="col-md-6">
                        <label>Phone</label>
                        <div class="input-group">
                          <div class="input-group-prepend">
                            <select name="countryCode" id="countryCode" class="form-select"
                              style="min-width: 130px;"></select>
                          </div>
                          <input type="text" name="u_phone" id="u_phone" class="form-control"
                            placeholder="Phone Number" />
                        </div>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <div class="col-md-6">
                        <label>Password</label>
                        <input type="password" name="password" class="form-control" />
                      </div>
                      <div class="col-md-6">
                        <label>Commission Type</label>
                        <select name="city_comm_type" class="form-select">
                          <option value="P">Percentage (%)</option>
                          <option value="F">Fixed</option>
                        </select>
                      </div>
                    </div>

                    <div class="row mb-3">
                      <div class="col-md-6">
                        <label>Commission</label>
                        <input type="number" name="city_comm" class="form-control" step="0.01" min="0"
                          placeholder="Enter commission amount" />
                      </div>
                      <div class="col-md-6">
                        <label>Street</label>
                        <input type="text" name="street" class="form-control" placeholder="Enter street address" />
                      </div>
                    </div>

                    <div class="row mb-3">

                      <div class="col-md-6">
                        <label>Address</label>
                        <input type="text" name="address" class="form-control" placeholder="Enter address" />
                      </div>
                      <div class="col-md-6">
                        <label>State</label>
                        <input type="text" name="state" class="form-control" placeholder="Enter state" />
                      </div>
                    </div>

                    <div class="row mb-3">

                      <div class="col-md-6">
                        <label>Postal Code</label>
                        <input type="text" name="pin_code" class="form-control" placeholder="Enter Postal Code" />
                      </div>
                      <div class="col-md-6">
                        <label>City</label>
                        <select name="city_id" class="form-control">
                          <option value="14">All Countries</option>
                        </select>
                      </div>
                    </div>

                    <div class="row mb-3">

                      <div class="col-md-6">
                        <label>Status</label>
                        <select name="status" class="form-control">
                          <option value="1">Active</option>
                          <option value="0">Inactive</option>
                        </select>
                      </div>
                      <div class="col-md-6">
                        <label for="profilePic" class="form-label">Profile Picture</label>
                        <input type="file" class="form-control" id="profilePic" name="profilePic"
                          accept=".jpg, .jpeg, .png">
                        <small class="text-muted">Allowed: JPG, JPEG, PNG (Max 2MB)</small>
                        <img src="" class="img-thumbnail mt-2" width="100" style="display: none;" alt="Profile Preview"
                          id="profilePreview">
                        <small id="profilePicError" class="text-danger mt-1"></small>
                      </div>
                      <div class="col-md-6" style="display: none;">
                        <label>Role</label>
                        <select name="group_id" class="form-control">
                          <% roles.forEach(role=> { %>
                            <option value="<%= role.id %>">
                              <%= role.name %>
                            </option>
                            <% }) %>
                        </select>
                      </div>
                    </div>

                    <div class="text-end">
                      <button type="submit" class="btn btn-success">Create Company</button>
                    </div>
                  </form>
                </div>
              </div>
      </div>
  </main>

  <script>
    // Define form configuration
    const formConfig = {
      formId: "subAdminForm",
      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: "u_email",
        type: "email",
        required: true,
        messages: {
          invalid: "Please enter a valid email address"
        }
      },

      {
        name: "countryCode",
        type: "select",
        required: true,
        messages: {
          required: "Please select country code"
        }
      },
      {
        name: "u_phone",
        type: "phone",
        required: true,
        messages: {
          required: "Phone number is required",
          invalid: "Phone number must be 6-15 digits"
        }
      },
      {
        name: "password",
        type: "text",
        required: true,
        messages: {
          required: "Password is required"
        }
      },
      {
        name: "city_id",
        type: "select",
        required: true,
        messages: {
          required: "Please select city"
        }
      },
      {
        name: "city_comm",
        type: "number",
        required: true,
        messages: {
          required: "Commission is required",
          invalid: "Commission must be between 0 and 100"
        }
      },
      ]
    };
  </script>

  <script src="/js/validator/validation.js"></script>
  <script>
    const form = document.getElementById("subAdminForm");
    const formValidator = setupFormValidation(
      formConfig.formId,
      formConfig.fields
    );

    // Profile picture validation
    const profilePicInput = document.getElementById('profilePic');
    if (profilePicInput) {
      const profilePicError = document.getElementById('profilePicError');
      const preview = document.getElementById('profilePreview');

      profilePicInput.addEventListener('change', function () {
        const file = this.files[0];
        profilePicError.textContent = '';

        if (file) {
          const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
          if (!validTypes.includes(file.type)) {
            profilePicError.textContent = 'Only JPG, JPEG, PNG 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';
        }
      });
    }

    form.addEventListener("submit", async (e) => {
      e.preventDefault();
      // Validate form
      if (!formValidator.validateForm()) {
        console.log('Form validation failed');
        return;
      }

      const formData = new FormData(form);

      try {
        const res = await fetch("/admin/create-sub-admin", {
          method: "POST",
          body: formData, // Send FormData directly for file upload
        });

        const result = await res.json();

        if (result.success) {
          Swal.fire({
            icon: "success",
            title: "Company created successfully!",
            toast: true,
            position: "top-end",
            showConfirmButton: false,
            timer: 2000,
          }).then(() => {
            // Get the status value to determine redirect
            const status = document.querySelector('select[name="status"]').value;
            if (status === "1") {
              window.location.href = "/admin/active-companies";
            } else {
              window.location.href = "/admin/inactive-companies";
            }
          });
        } else {
          throw new Error(result.message || "Something went wrong");
        }

      } catch (err) {
        Swal.fire({
          icon: "error",
          title: "Error",
          text: err.message || "Failed to create company.",
        });
      }
    });
  </script>

  <script>
    $(document).ready(function () {
      function getFlagEmoji(code) {
        return code.toUpperCase().replace(/./g, char =>
          String.fromCodePoint(127397 + char.charCodeAt())
        );
      }

      fetch("/countryCode.json")
        .then(res => res.json())
        .then(data => {
          window.countryCodes = data; // Store globally
          const $select = $('#countryCode');
          if (!$select.length) {
            console.error("Dropdown element #countryCode not found.");
            return;
          }

          data.forEach(country => {
            const option = new Option(
              `${getFlagEmoji(country.code)} +${country.id} (${country.name})`,
              `+${country.id}`,
              false,
              false
            );
            $select.append(option);
          });

          $select.select2({
            placeholder: "Country Code",
            width: 'resolve',
            templateSelection: function (data) {
              return data.id || 'Country Code';
            }
          });

          // Set initial country code from server
          const serverCountryCode = '<%= country_code %>';
          if (serverCountryCode) {
            $select.val(`+${serverCountryCode}`).trigger('change');
            console.log(`Initial country code set from server: +${serverCountryCode}`);
          }
        })
        .catch(err => {
          console.error("Failed to load country codes:", err);
        });
    });
  </script>

  <%- footer %>
