<%- include('../../includes/map.ejs',{googleKey,language : lang}) %>

  <div
    data-providers-contract
    data-providers-csrf-token="<%= csrfToken %>"
    hidden
  ></div>
  <script src="/admin/app-assets/js/core/libraries/jquery.min.js"></script>
  <script src="/admin/assets/js/pages/providers-contract.js"></script>
  <script src="/admin/app-assets/vendors/js/forms/select/select2.full.min.js"></script>
  <script src="/admin/app-assets/js/scripts/forms/select/form-select2.js"></script>
  <script>

    $(document).ready(function () {
      $('.select2').select2({
        closeOnSelect: true
      });
    });


    function validateInput(input) {

      const i18n = {
        common: {
          emptyField: "<%= i18n.__('common.emptyField') %>",
          minLength: "<%= i18n.__('common.minLength', { minLength: '{{minLength}}' }) %>",
          invalidEmail: "<%= i18n.__('common.emailMustBeValid') %>",
          invalidPassword: "<%= i18n.__('common.passwordTooShort') %>",
          phoneRequired: "<%= i18n.__('common.{{field}}Required',{field:i18n.__('common.phone')}) %>",
          emailRequired: "<%= i18n.__('common.{{field}}Required',{field:i18n.__('common.email')}) %>",
          nameRequired: "<%= i18n.__('common.{{field}}Required',{field:i18n.__('common.name')}) %>",
          nameWordLengthAtLeastTwoWords: "<%= i18n.__('auth.nameWordLengthAtLeastTwoWords') %>",
          nameTooShort: "<%= i18n.__('auth.nameTooShort') %>",
          invalidPhone: "<%= i18n.__('common.phoneNoLess') %>",
          passwordRequired: "<%= i18n.__('common.passwordRequired') %>",
          invalidStartPhone: "<%= i18n.__('common.invalidStartPhone') %>",
          nationalIdMinAndMax: "<%= i18n.__('auth.nationalIdMinAndMax') %>",
          accountNumberMinimum: "<%= i18n.__('auth.accountNumberMinimum') %>",
          accountNumberDigitsOnly: "<%= i18n.__('auth.accountNumberDigitsOnly') %>",
          invalidIban: "<%= i18n.__('auth.invalidIban') %>",
          commercialRegistrationNumberLength: "<%= i18n.__('auth.commercialRegistrationNumberLength') %>",
          nameCannotContainNumbers: "<%= i18n.__('common.nameCannotContainNumbers') %>",
        }
      };

      try {

        const trimmedValue = input.value.trim();
        const minLength = input.type === "password" ? 6 : 2;
        const feedback = input.nextElementSibling;

        const fieldMessages = {
          password: i18n.common.passwordRequired,
          phone: i18n.common.phoneRequired,
          email: i18n.common.emailRequired,
          name: i18n.common.nameRequired,
          nameWordLengthAtLeastTwoWords: i18n.common.nameWordLengthAtLeastTwoWords,
          nameTooShort: i18n.common.nameTooShort,
          nationalIdMinAndMax: i18n.common.nationalIdMinAndMax,
          invalidIban: i18n.common.invalidIban,
          accountNumberMinimum: i18n.common.accountNumberMinimum,
          commercialRegistrationNumberLength: i18n.common.commercialRegistrationNumberLength,
          nameCannotContainNumbers: i18n.common.nameCannotContainNumbers,
        };


        const messages = {
          empty: (!input.hasAttribute('data-edit') && fieldMessages[input.name])
            ? fieldMessages[input.name]
            : (!input.hasAttribute('data-edit') ? i18n.common.emptyField : ''),
          minLength: i18n.common.minLength.replace('{{minLength}}', minLength),
          invalidEmail: i18n.common.invalidEmail,
          invalidPassword: i18n.common.invalidPassword,
          invalidPhone: i18n.common.invalidPhone,
          invalidIban: i18n.common.invalidIban,
        };

        let errorMessage = "";

        if (!trimmedValue) errorMessage = input.required ? messages.empty : "";

        else if (input.name === 'name') {
          const words = trimmedValue.split(/\s+/);
          const anyWordTooShort = words.some(word => word.length < 2);

          if (anyWordTooShort) {
            errorMessage = i18n.common.nameTooShort;
          }
        }


        else if (input.name === 'nationalId') {
          const nationalIdError = validateNationalId(trimmedValue);
          if (nationalIdError) errorMessage = nationalIdError;
        }

        else if (input.name === 'accountNumber') {
          const accountNumberError = validateAccountNumber(trimmedValue);
          if (accountNumberError) errorMessage = accountNumberError;
        }

        else if (input.name === 'phone') {
          const phoneError = validatePhone(trimmedValue);
          if (phoneError) errorMessage = phoneError;

        }

        else if (input.name === 'iban') {
          const ibanError = validateIban(trimmedValue);
          if (ibanError) errorMessage = ibanError;
        }

        else if (input.name === 'commercialRegistrationNumber') {
          const commercialRegistrationNumberError = validateCommercialRegistrationNumber(trimmedValue);
          if (commercialRegistrationNumberError) errorMessage = commercialRegistrationNumberError;
        }

        else if (trimmedValue.length < minLength) errorMessage = input.type === "password" ? messages.invalidPassword : messages.minLength;

        updateInputState(input, feedback, errorMessage);

      } catch (_error) {}

      // Supported countries: extend this map to add more IBAN formats.
      // length = total IBAN length, regex = full structural pattern.
      const IBAN_RULES = {
        SA: { length: 24, regex: /^SA\d{22}$/ } // Saudi Arabia: SA + 2 check digits + 22 BBAN digits
      };

      function validateIban(value) {
        const iban = (value || '').replace(/\s+/g, '').toUpperCase();

        // Must start with a 2-letter country code we support.
        const country = iban.slice(0, 2);
        const rule = IBAN_RULES[country];
        if (!rule) {
          return i18n.common.invalidIban;
        }

        // Validate exact length and structure for that country.
        if (iban.length !== rule.length || !rule.regex.test(iban)) {
          return i18n.common.invalidIban;
        }

        // Validate the IBAN checksum (ISO 7064, MOD-97-10).
        if (!isValidIbanChecksum(iban)) {
          return i18n.common.invalidIban;
        }

        return "";
      }

      function isValidIbanChecksum(iban) {
        // Move the 4 leading characters (country code + check digits) to the end.
        const rearranged = iban.slice(4) + iban.slice(0, 4);
        // Replace each letter with its numeric value (A=10 ... Z=35).
        const numeric = rearranged.replace(/[A-Z]/g, ch => (ch.charCodeAt(0) - 55).toString());
        // Compute mod 97 piece by piece to avoid big-number overflow.
        let remainder = 0;
        for (let i = 0; i < numeric.length; i++) {
          remainder = (remainder * 10 + (numeric.charCodeAt(i) - 48)) % 97;
        }
        return remainder === 1;
      }

      function validateCommercialRegistrationNumber(value) {
        if (!/^\d{10}$/.test(value)) {
          return i18n.common.commercialRegistrationNumberLength;
        }
      }

      function validateNationalId(value) {
        if (!/^\d{10,}$/.test(value)) {
          return i18n.common.nationalIdMinAndMax;
        }
      }

      function validateAccountNumber(value) {
        // Must contain digits only — no letters, spaces, or special characters.
        if (!/^\d+$/.test(value)) {
          return i18n.common.accountNumberDigitsOnly;
        }
        // Must be within the allowed digit count (10–24).
        if (value.length < 10 || value.length > 24) {
          return i18n.common.accountNumberMinimum;
        }
        return "";
      }

      function isValidPhone(value) {
        return /^(05|01)\d{8}$/.test(value);
      }

      function validatePhone(value) {

        // Accept Saudi formats: 10 digits starting 05/01, or 9 digits starting 5/1.
        if (!/^0?[51]/.test(value)) {
          return i18n.common.invalidStartPhone;
        }

        if (!/^\d{9,10}$/.test(value)) {
          return i18n.common.invalidPhone;
        }

        return "";
      }

      function isValidPassword(value) {
        return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/.test(value);
      }

      function updateInputState(input, feedback, errorMessage) {
        if (errorMessage) {
          feedback.textContent = errorMessage;
          input.classList.add('is-invalid');
          input.style.border = '1px solid red';
          input.setCustomValidity(errorMessage);
          return;
        }

        feedback.textContent = '';
        input.classList.remove('is-invalid');
        input.style.border = '';
        input.setCustomValidity('');
      }
    }




    $(document).ready(function () {

      $(document).on('submit', '#createProvider', function (e) {

        e.preventDefault();

        let confirm = "<%=i18n.__('common.add')%>"

        let objData = new FormData(this);

        let isValidImage = true;

        const file = $("#avatar")[0]?.files[0];

        isValidImage = file ? /(jpg|jpeg|png)$/.test(file.type) : true;


        if (isValidImage) {
          ajaxUpload($(this), objData, "uploadWithImage", confirm);
        }

      })

      $(document).on('submit', '#editProvider', function (e) {

        e.preventDefault();

        $("#overlay").fadeIn(300);
        let confirm = "<%=i18n.__('common.edit')%>"
        var objData = new FormData(this);

        let isValidImage = true;

        const file = $("#avatar")[0]?.files[0];

        isValidImage = file ? /(jpg|jpeg|png)$/.test(file.type) : true;

        if (isValidImage) {
          ajaxUpload($(this), objData, "uploadWithImage", confirm);
        }

      });
    })


  </script>
