{% load basefilters %}
{% load i18n %}{% load static %} {% load recruitmentfilters horillafilters %}

{% if messages %}
<div class="oh-wrapper">
  {% for message in messages %}
  <div class="oh-alert-container">
    <div class="oh-alert oh-alert--animated {{message.tags}}">
      {{ message }}
    </div>
  </div>
  {% endfor %}
</div>
{% endif %}
<style>
  .note-modal-backdrop {
      z-index: 998 !important;
  }

  .tooltip {
      position: relative;
      display: inline-block; /* Ensures that the tooltip container doesn't stretch to the full width */
  }

  .tooltip .tooltiptext {
      visibility: hidden;
      width: auto; /* Allow the tooltip width to adjust based on content */
      max-width: auto; /* Limit the maximum width of the tooltip to prevent it from overflowing */
      background-color: green;
      color: white;
      text-align: center;
      border-radius: 6px;
      padding: 5px;
      position: absolute;
      z-index: 1;
      bottom: 5%;
      left: 50%;
      transform: translateX(5%);
      opacity: 0;
      transition: opacity 0.3s;
      white-space: nowrap; /* Prevents the text from wrapping */
      overflow: hidden; /* Hides any overflowed content */
      font-size: 15px;
  }

  .tooltip:hover .tooltiptext {
      visibility: visible;
      opacity: 1;
  }
</style>

{% include 'filter_tags.html' %}

{% if data %}
  <!-- start of select all -->

  <div class="oh-checkpoint-badge text-success mb-2" id="selectAllInstances" style="cursor: pointer;">
    {% trans "Select All Candidates" %}
  </div>
  <div class="oh-checkpoint-badge text-secondary mb-2" id="unselectAllInstances" style="cursor: pointer;display: none;">
    {% trans "Unselect All Candidates" %}
  </div>
  <div class="oh-checkpoint-badge text-info mb-2" id="exportCandidates" style="cursor: pointer;display: none;">
      {% trans "Export Candidates" %}
  </div>
  <div class="oh-checkpoint-badge text-danger mb-2" id="selectedCandidate" style="display: none">
  </div>
  <!-- start of select all -->
  <!-- start of column toggle button -->
  <div class="oh-table_sticky--wrapper">
    <div class="oh-sticky-dropdown--header">
      <div class="oh-dropdown" x-data="{open: false}">
        <button class="oh-sticky-dropdown_btn " @click="open = !open"><ion-icon name="ellipsis-vertical-sharp"
          role="img" class="md hydrated" aria-label="ellipsis vertical sharp"></ion-icon></button>
        <div class="oh-dropdown__menu oh-sticky-table_dropdown" x-show="open" @click.outside="open = false">
        <ul class="oh-dropdown__items" id="CandidateCells">
        </ul>
        </div>
      </div>
    </div>
  </div>
  <!-- end of column toggle button -->
  <div id="candidate-toggle-table" data-table-name="candidate_toggle_tab">
    <!-- start of sticky table -->
    <div class="oh-sticky-table">
      <div class="oh-sticky-table__table oh-table--sortable">
        <div class="oh-sticky-table__thead">
          <div class="oh-sticky-table__tr">
            <div class="oh-sticky-table__th" style="width:10px;">
              <div class="centered-div" align="center">
                <input type="checkbox" class="oh-input oh-input__checkbox group-select"
                onchange="$(this).closest('.oh-sticky-table').find('.candidate-checkbox').prop('checked',$(this).is(':checked')).change();"
                 title="Select All"  />
              </div>
            </div>
            <div class="oh-sticky-table__th {% if request.sort_option.order == '-name' %}arrow-up {% elif request.sort_option.order == 'name' %}arrow-down {% else %} arrow-up-down {% endif %}"  hx-target='#section' hx-get="{% url 'search-candidate' %}?{{pd}}&orderby=name&view=list">{% trans "Candidates" %}</div>
            <div data-cell-index="1" data-cell-title='{% trans "Email" %}' class="oh-sticky-table__th">{% trans "Email" %}</div>
            <div data-cell-index="2" data-cell-title='{% trans "Phone" %}' class="oh-sticky-table__th">{% trans "Phone" %}</div>
            <div data-cell-index="3" data-cell-title='{% trans "Rating" %}' class="oh-sticky-table__th">{% trans "Rating" %}</div>
            <div data-cell-index="4" data-cell-title='{% trans "Recruitment" %}' class="oh-sticky-table__th">{% trans "Recruitment" %}</div>
            <div data-cell-index="5" data-cell-title='{% trans "Job Position" %}' class="oh-sticky-table__th">{% trans "Job Position" %}</div>
            <div data-cell-index="6" data-cell-title='{% trans "Resume" %}' class="oh-sticky-table__th">{% trans "Resume" %}</div>
            {% if perms.recruitment.change_candidate or perms.recruitment.add_rejectedcandidate or perms.recruitment.add_skillzonecandidate %}
              <div class="oh-sticky-table__th" style="width: 230px;">{% trans "Options" %}</div>
            {% endif %}
            {% if perms.recruitment.change_candidate or perms.recruitment.delete_candidate %}
              <div class="oh-sticky-table__th oh-sticky-table__right"  style="width: 190px;">{% trans "Actions" %}</div>
            {% endif %}
          </div>
        </div>
        {% for cand in data %}
        <div class="oh-sticky-table__tbody ui-sortable {% if cand.email in emp_list %} to-employee {% endif %}">
          <div class="oh-sticky-table__tr ui-sortable-handle">
            <div class="oh-sticky-table__sd {% if cand.canceled %} row-status--red
            {% elif cand.hired %} row-status--yellow
            {% elif cand.converted %} row-status--blue
            {% else %} row-status--purple
            {% endif %}">
              <div class="centered-div">
                <input
                  type="checkbox"
                  id="{{cand.id}}"
                  onchange="highlightRow($(this))"
                  class="oh-input candidate-checkbox oh-input__checkbox all-candidate-row"
                />
              </div>
            </div>
            <div class="oh-sticky-table__td candidate {% if cand.hired %}hired-cand{% endif %}">
              <div class="d-flex">
                <a href="{% url 'candidate-view-individual' cand.id %}" style="color: inherit;text-decoration: none;"
                class="oh-profile oh-profile--md">
                  <div class="oh-profile__avatar mr-1">
                    <img src="{{cand.get_avatar}}"
                    class="oh-profile__image"
                    alt="Username" />
                  </div>
                  <span class="oh-profile__name oh-text--dark">{{cand}}</span>
                </a>
                {% if cand.email in emp_list %}
                  <span class="tooltip">
                    <span class="material-symbols-outlined ms-2" style="flex-direction: row-reverse;color:green;">
                        how_to_reg
                      </span>
                      <span class="tooltiptext fw-bold">
                        {% trans "Converted to employee." %}
                      </span>
                  </span>
                {% endif %}
              </div>
            </div>

            <a data-cell-index="1" href="{% url 'candidate-view-individual' cand.id %}" style="color: inherit;text-decoration: none;" class="oh-sticky-table__td ">{{cand.email}}</a>
            <a data-cell-index="2" href="{% url 'candidate-view-individual' cand.id %}" style="color: inherit;text-decoration: none;" class="oh-sticky-table__td">{{cand.mobile}}</a>
            <a data-cell-index="3" href="{% url 'candidate-view-individual' cand.id %}" style="color: inherit;text-decoration: none;" class="oh-sticky-table__td">
              {% with request.user.employee_get.candidate_rating.all as candidate_ratings  %}
                <form >
                  <div class="d-block mb-0">
                    <div class="oh-rate" onmouseenter="event.stopPropagation()">
                      {% for i in "54321" %}
                      <input type="radio" id="star{{i}}{{cand.id}}" name="rating" class="rating-radio" value="{{i}}" disabled {% if cand.candidate_rating.all|avg_rating:cand == i %} checked {% endif %} />
                      <label for="star{{i}}{{cand.id}}" >5 {% trans "Stars" %}</label>
                      {% endfor %}
                    </div>
                    <span id="rating-radio-error"></span>
                  </div>
                </form>
              {% endwith %}
            </a>
            <a data-cell-index="4" href="{% url 'candidate-view-individual' cand.id %}" style="color: inherit;text-decoration: none;"
              class="oh-sticky-table__td">{{cand.recruitment_id}}</a>
            <a data-cell-index="5" href="{% url 'candidate-view-individual' cand.id %}" style="color: inherit;text-decoration: none;"
              class="oh-sticky-table__td">{{cand.job_position_id}}</a>

            <div data-cell-index="6" class="oh-sticky-table__td " onclick="event.stopPropagation()">
              <a
                style="text-decoration: none"
                class="oh-btn oh-btn--light"
                href="{{cand.resume.url}}"
                target="_blank"
                title="{% trans 'Resume' %}"
                rel="noopener noreferrer"
                >
                <span class="oh-file-icon oh-file-icon--pdf"></span> &nbsp {% trans "View" %}
              </a>
            </div>
            {% if perms.recruitment.change_candidate or perms.recruitment.add_rejectedcandidate or perms.recruitment.add_skillzonecandidate %}
              <div class="oh-sticky-table__td">
                <div class="oh-btn-group">
                  {% if perms.recruitment.change_candidate %}
                    {% if not cand.email in emp_list and not cand.start_onboard %}
                      <a href="{% url 'candidate-conversion' cand.id %}"
                        onclick="return confirm('{% trans "Are you sure you want to convert this candidate into an employee?" %}')"
                        class="oh-btn oh-btn--light-bkg w-100"
                        title='{% trans "To employee " %}'
                        style="padding:0.8rem 1rem"
                      >
                        <ion-icon name="person-circle-outline"></ion-icon></a>
                    {% elif cand.email in emp_list %}
                      <button class="oh-btn oh-btn--light-bkg w-100"  title='{% trans "Converted " %}' style="opacity: 30%; padding:0.8rem 1rem" disabled>
                        <ion-icon name="person-circle-outline"></ion-icon></button>
                    {% else %}
                      <button class="oh-btn oh-btn--light-bkg w-100"  title='{% trans "Candidate in Onboarding " %}' style="opacity: 30%; padding:0.8rem 1rem" disabled>
                        <ion-icon name="person-circle-outline"></ion-icon></button>
                    {% endif %}
                  {% endif %}
                  {% if perms.recruitment.add_skillzonecandidate or perms.recruitment.change_candidate %}
                    {% if cand.email in emp_list %}
                      <button class="oh-btn oh-btn--light-bkg w-100"  title='{% trans "Candidate is Converted " %}' style="opacity: 30%; padding:0.8rem 1rem">
                        <ion-icon name="heart-circle-outline"></ion-icon></button>
                    {% else %}
                      <button class="oh-btn oh-btn--light-bkg w-100" title="{% trans 'To Skill zone' %}"
                          data-toggle="oh-modal-toggle"
                          data-target="#createModal"
                          hx-get="{% url 'to-skill-zone' cand.id %}"
                          hx-target="#createTarget"
                          style="padding:0.8rem 1rem"
                        >
                        <ion-icon name="heart-circle-outline"></ion-icon>
                      </button>
                    {% endif %}
                  {% endif %}
                  {% if cand.email in emp_list %}
                    <button class="oh-btn oh-btn--light-bkg w-100"  title='{% trans "Candidate is Converted " %}' style="opacity: 30%; padding:0.8rem 1rem">
                      <ion-icon name="thumbs-down-outline"></ion-icon></button>
                  {% else %}
                    {% if onboarding|app_installed %}
                      {% if perms.recruitment.add_rejectedcandidate or perms.recruitment.change_candidate %}
                        <button
                          type="button"
                          class="oh-btn oh-btn--light-bkg w-100"
                          hx-get="{% url 'add-to-rejected-candidates' %}?candidate_id={{cand.id}}"
                          hx-target="#createTarget"
                          data-toggle="oh-modal-toggle"
                          data-target="#createModal"
                          {% if cand.is_offer_rejected %}
                          style="background: #ff4500a3 !important; color: white;"
                          title="{% trans "Added In Rejected Candidates" %}"
                          {% else %}
                          title="{% trans "Add To Rejected Candidates" %}"
                          {% endif %}>
                        <ion-icon name="thumbs-down-outline"></ion-icon>
                        </button>
                      {% endif %}
                    {% endif %}
                  {% endif %}
                  {% if perms.recruitment.change_candidate %}
                    <button
                      type="button"
                      hx-get='{% url "send-mail" cand.id %}'
                      title="{% trans "Send Mail" %}"
                      hx-target="#objectDetailsModalTarget"
                      class="oh-btn oh-btn--light-bkg w-100"
                      data-toggle="oh-modal-toggle"
                      data-target="#objectDetailsModal"
                      style="padding:0.8rem 1rem"
                    >
                      <ion-icon name="mail-open-outline"></ion-icon>
                    </button>
                  {% endif %}
                </div>
              </div>
            {% endif %}
            {% if perms.recruitment.change_candidate or perms.recruitment.delete_candidate %}
              <div href="#" style="color: inherit;text-decoration: none;" class="oh-sticky-table__td oh-sticky-table__right">
                <div class="oh-btn-group">
                  {% if perms.recruitment.change_candidate %}
                  <a href="{% url 'rec-candidate-update' cand.id %}" hx-target='#updateFormContainer' hx-swap='innerHTML'
                    class="oh-btn oh-btn--light-bkg w-100" title="Edit"><ion-icon name="create-outline"></ion-icon></a>
                  {% endif %}
                  {% if perms.recruitment.delete_candidate %}
                  {% if cand.is_active %}
                  <form action="{% url 'rec-candidate-archive' cand.id  %}" title="Archive" onsubmit="return confirm('{% trans "Do you want to archive this candidate?" %}')" method='post'
                    class="w-50">
                  {% csrf_token %}
                  <button type='submit' class="oh-btn oh-btn--danger-outline oh-btn--light-bkg w-100"
                    ><ion-icon name="archive" title="Archive"></ion-icon></button>
                  </form>
                  {% else %}

                  <form action="{% url 'rec-candidate-archive' cand.id  %}"  title="Un Archive" onsubmit="return confirm('{% trans "Do you want to un-archive this candidate?" %}')" method='post'
                    class="w-100">
                    {% csrf_token %}
                    <button type='submit' class="oh-btn oh-btn--danger-outline oh-btn--light-bkg w-100"
                      ><ion-icon name="archive"></ion-icon></button>
                  </form>
                  {% endif %}
                  {% endif %}
                  {% if perms.recruitment.delete_candidate %}
                  <form action="{% url 'rec-candidate-delete' cand.id  %}" onsubmit="return confirm('{% trans "Do you want to delete this candidate?" %}')" method='post'
                    onsubmit="Are you sure want to delete this candidate?" class="w-100">
                    {% csrf_token %}
                    <button type='submit' class="oh-btn oh-btn--danger-outline oh-btn--light-bkg w-100"
                      title="Remove"><ion-icon name="trash-outline"></ion-icon></button>
                  </form>
                  {% endif %}
                </div>
              </div>
            {% endif %}

            </a>
          </div>

        </div>
        {% endfor %}
      </div>

    </div>
    <!-- end of sticky table -->

    <!-- start of pagination -->
    <div class="oh-pagination">
      <span class="oh-pagination__page" data-toggle="modal" data-target="#addEmployeeModal">
        {% trans "Page" %} {{ data.number }} {% trans "of" %} {{ data.paginator.num_pages }}.
      </span>
      <nav class="oh-pagination__nav">
        <div class="oh-pagination__input-container me-3">
          <span class="oh-pagination__label me-1">{% trans "Page" %}</span>

          <input type="number" name="page" class="oh-pagination__input" value="{{data.number}}"
            hx-get="{% url 'search-candidate' %}?{{pd}}&view=list" hx-target="#section" min="1" />
          <span class="oh-pagination__label">{% trans "of" %} {{data.paginator.num_pages}}</span>
        </div>

        <ul class="oh-pagination__items">
          {% if data.has_previous %}
          <li class="oh-pagination__item oh-pagination__item--wide">
            <a hx-target='#section' hx-get="{% url 'search-candidate' %}?{{pd}}&page=1&view=list"
              class="oh-pagination__link" onclick=tickCandidateCheckboxes()>{% trans "First" %}</a>
          </li>
          <li class="oh-pagination__item oh-pagination__item--wide">
            <a hx-target='#section'
              hx-get="{% url 'search-candidate' %}?{{pd}}&page={{ data.previous_page_number }}&view=list"
              class="oh-pagination__link" onclick=tickCandidateCheckboxes()>{% trans "Previous" %}</a>
          </li>
          {% endif %}
          {% if data.has_next %}
          <li class="oh-pagination__item oh-pagination__item--wide">
            <a hx-target='#section' hx-get="{% url 'search-candidate' %}?{{pd}}&page={{ data.next_page_number }}&view=list"
              class="oh-pagination__link" onclick=tickCandidateCheckboxes()>{% trans "Next" %}</a>
          </li>
          <li class="oh-pagination__item oh-pagination__item--wide">
            <a hx-target='#section'
              hx-get="{% url 'search-candidate' %}?{{pd}}&page={{ data.paginator.num_pages }}&view=list"
              class="oh-pagination__link" onclick=tickCandidateCheckboxes()>{% trans "Last" %}</a>
          </li>
          {% endif %}

        </ul>
      </nav>
    </div>
    <!-- end of pagination -->
  </div>

{% else %}
  <!-- start of empty page -->
  <div class="oh-404">
    <img
      style="width: 150px; height: 150px"
      src="{% static 'images/ui/no-results.png' %}"
      class="oh-404__image mb-4"
    />
    <h5 class="oh-404__subtitle">
      {% trans "No search result found!" %}
    </h5>
  </div>
  <!-- end of empty page -->
{% endif %}

<div class="oh-modal" id="sendMailModal" role="dialog" aria-labelledby="sendMailModal" aria-hidden="true">
  <div class="oh-modal__dialog">
    <div class="oh-modal__dialog-header">
      <span class="oh-modal__dialog-title" id="sendMailModalLabel">
        <h5>{% trans "Send Mail" %}</h5>
      </span>
      <button class="oh-modal__close" aria-label="Close">
        <ion-icon name="close-outline"></ion-icon>
      </button>
    </div>
    <div class="oh-modal__dialog-body" id='mail-content'>

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



<script>
  var archive_CanMessages = {
    ar: "هل ترغب حقًا في أرشفة جميع المرشحين المحددين؟",
    de: "Möchten Sie wirklich alle ausgewählten Kandidaten archivieren?",
    es: "¿Realmente deseas archivar a todos los candidatos seleccionados?",
    en: "Do you really want to archive all the selected candidates?",
    fr: "Voulez-vous vraiment archiver tous les candidats sélectionnés?",
  };

  var unarchive_CanMessages = {
    ar: "هل ترغب حقًا في إلغاء أرشفة جميع المرشحين المحددين؟",
    de: "Möchten Sie wirklich alle ausgewählten Kandidaten aus der Archivierung nehmen?",
    es: "¿Realmente deseas desarchivar a todos los candidatos seleccionados?",
    en: "Do you really want to unarchive all the selected candidates?",
    fr: "Voulez-vous vraiment désarchiver tous les candidats sélectionnés?",
  };

  var delete_CanMessages = {
    ar: "هل ترغب حقًا في حذف جميع المرشحين المحددين؟",
    de: "Möchten Sie wirklich alle ausgewählten Kandidaten löschen?",
    es: "¿Realmente deseas eliminar a todos los candidatos seleccionados?",
    en: "Do you really want to delete all the selected candidates?",
    fr: "Voulez-vous vraiment supprimer tous les candidats sélectionnés?",
  };

  var noRowMessages = {
    ar: "لم يتم تحديد أي صفوف.",
    de: "Es wurden keine Zeilen ausgewählt.",
    es: "No se han seleccionado filas.",
    en: "No rows have been selected.",
    fr: "Aucune ligne n'a été sélectionnée.",
  };

  var rowMessages = {
    ar: " تم الاختيار",
    de: " Ausgewählt",
    es: " Seleccionado",
    en: " Selected",
    fr: " Sélectionné",
  };
  function makeListUnique1(list) {
    return Array.from(new Set(list));
  }
  function arrayDifference(arr1, arr2) {
    return arr1.filter(element => !arr2.includes(element));
  }

  function removeElementFromArray(array, elementToRemove) {
    const indexToRemove = array.indexOf(elementToRemove);

    if (indexToRemove !== -1) {
      array.splice(indexToRemove, 1);
    }
    return array
  }
  function addingCandidateIds() {
    var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "[]");
    var domNotCheckedIds = []

    var selectedCount = 0;

    $(".all-candidate-row:checked").each(function () {
      ids.push(this.id);
    });

    $.each($(".candidate-checkbox:checked").not(), function (indexInArray, valueOfElement) {
      domNotCheckedIds.push($(valueOfElement).attr("id"))
    });

    ids = makeListUnique1(ids);
    ids = arrayDifference(ids, domNotCheckedIds)
    var selectedCount = ids.length;
  }

  function tickCandidateCheckboxes() {
    var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "[]");
    var uniqueIds = makeListUnique1(ids);
    $.each(uniqueIds, function (indexInArray, valueOfElement) {
      checkbox = $("#" + valueOfElement)
      checkbox.prop("checked", true).change()
    });

    addingCandidateIds()
  }

  function updateCount() {
    var ids = makeListUnique1(JSON.parse($("#selectedInstances").attr("data-ids") || "[]"));
    $("#unselectAllInstances, #selectedCandidate, #exportCandidates").hide();
    if (ids.length) {
      $("#unselectAllInstances, #selectedCandidate, #exportCandidates").show();
      $("#selectedCandidate").text("{% trans "Selected" %}" + " -" + ids.length);
    }
  }

  $(".all-candidate-row").change(function (e) {
    var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "[]");
    if ($(this).is(":checked")) {
      ids.push($(this).attr("id"))
      $("#selectedInstances").attr("data-ids", JSON.stringify(makeListUnique1(ids)));
    } else {
      $(".group-select").prop("checked",false)
      $("#selectedInstances").attr("data-ids", JSON.stringify(makeListUnique1(removeElementFromArray(ids, this.id))));
    }
    updateCount()
  });


  function getCurrentLanguageCode(callback) {
    var languageCode = $("#main-section-data").attr("data-lang");
    var allowedLanguageCodes = ["ar", "de", "es", "en", "fr"];
    if (allowedLanguageCodes.includes(languageCode)) {
      callback(languageCode);
    } else {
      $.ajax({
        type: "GET",
        url: "/employee/get-language-code/",
        success: function (response) {
          var ajaxLanguageCode = response.language_code;
          $("#main-section-data").attr("data-lang", ajaxLanguageCode);
          callback(
            allowedLanguageCodes.includes(ajaxLanguageCode)
              ? ajaxLanguageCode
              : "en"
          );
        },
        error: function () {
          callback("en");
        },
      });
    }
  }

  $(document).ready(function () {
    var excelMessages = {
      ar: "هل ترغب في تنزيل ملف Excel؟",
      de: "Möchten Sie die Excel-Datei herunterladen?",
      es: "¿Desea descargar el archivo de Excel?",
      en: "Do you want to download the excel file?",
      fr: "Voulez-vous télécharger le fichier Excel?",
    };
    var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "[]");
    var uniqueIds = makeListUnique1(ids);
    var selectedCount = uniqueIds.length;
    var message1 = rowMessages[languageCode];
    $("#selectAllInstances").click(function () {
      $("#selectedInstances").attr("data-clicked", 1);
      var savedFilters = JSON.parse(localStorage.getItem("savedFilters"));
      if (savedFilters && savedFilters["filterData"] !== null) {
        var filter = savedFilters["filterData"];
        $.ajax({
          url: '{% url "candidate-select-filter" %}',
          data: { page: "all", filter: JSON.stringify(filter) },
          type: "GET",
          dataType: "json",
          success: function (response) {
            var employeeIds = response.employee_ids;
            var selectedCount = employeeIds.length;
            var selectedCount = employeeIds.length;

            var selectedCount = employeeIds.length;

            for (var i = 0; i < employeeIds.length; i++) {
              var empId = employeeIds[i];
              $("#" + empId).prop("checked", true).change();
            }
            var previousIds = $("#selectedInstances").attr("data-ids")
            $("#selectedInstances").attr("data-ids", JSON.stringify(Array.from(new Set([...employeeIds, ...JSON.parse(previousIds)]))));
            tickCandidateCheckboxes();
          },
          error: function (xhr, status, error) {
            console.error("Error:", error);
          },
        });
      } else {
        $.ajax({
          url: '{% url "candidate-select" %}',
          data: { page: "all" },
          type: "GET",
          dataType: "json",
          success: function (response) {
            var employeeIds = response.employee_ids;
            var selectedCount = employeeIds.length;
            for (var i = 0; i < employeeIds.length; i++) {
              var empId = employeeIds[i];
              $("#" + empId).prop("checked", true);
            }
            $("#selectedInstances").attr(
              "data-ids",
              JSON.stringify(employeeIds)
            );
          },
          error: function (xhr, status, error) {
            console.error("Error:", error);
          },
        });
      }
    });
    $("#unselectAllInstances").click(function () {
      $("#selectedInstances").attr("data-ids", "[]");
      tickCandidateCheckboxes()
      $(".all-candidate-row").prop("checked", false).change()
    });
    $("#exportCandidates").click(function (e) {
      var currentDate = new Date().toISOString().slice(0, 10);
      var languageCode = null;
      ids = [];
      ids.push($("#selectedInstances").attr("data-ids"));
      ids = JSON.parse($("#selectedInstances").attr("data-ids"));
      getCurrentLanguageCode(function (code) {
        languageCode = code;
        var confirmMessage = excelMessages[languageCode];
        Swal.fire({
          text: confirmMessage,
          icon: "question",
          showCancelButton: true,
          confirmButtonColor: "#008000",
          cancelButtonColor: "#d33",
          confirmButtonText: "Confirm",
        }).then(function (result) {
          if (result.isConfirmed) {
            $.ajax({
              type: "GET",
              url: "/recruitment/candidate-info-export",
              data: {
                ids: JSON.stringify(ids),
              },
              dataType: "binary",
              xhrFields: {
                responseType: "blob",
              },
              success: function (response) {
                const file = new Blob([response], {
                  type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                });
                const url = URL.createObjectURL(file);
                const link = document.createElement("a");
                link.href = url;
                link.download = "Candidate_file_" + currentDate + ".xlsx";
                document.body.appendChild(link);
                link.click();
              },
              error: function (xhr, textStatus, errorThrown) {
                console.error("Error downloading file:", errorThrown);
              },
            });
          }
        });
      });
    });
  });
  // toggle columns //
  toggleColumns("candidate-toggle-table", "CandidateCells")
  localStorageCandidateCells = localStorage.getItem("candidate_toggle_tab")
  if (!localStorageCandidateCells) {
    $("#CandidateCells").find("[type=checkbox]").prop("checked", true)
  }

  updateCount()
  tickCandidateCheckboxes()
</script>
