{% load recruitmentfilters horillafilters %} {% load basefilters %} {% load static %}
{% load i18n %} {% include 'filter_tags.html' %}

{% if data %}
	<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;">
		{% trans "Unselect All Candidates" %}
	</div>
	<div class="oh-checkpoint-badge text-info mb-2" id="exportsection" style="cursor: pointer;">
		{% trans "Export Candidates" %}
	</div>
	<div class="oh-checkpoint-badge text-danger mb-2" id="selectedCandidate" >
	</div>
{% endif %}
{% if data %}
<div class="oh-card">
    {% for candidate_list in data %}
    <div class="oh-accordion-meta">
		<div class="oh-accordion-meta__item">
			<div class="oh-accordion-meta__header" onclick='$(this).toggleClass("oh-accordion-meta__header--show");'>
				<span class="oh-accordion-meta__title pt-3 pb-3">
					<div class="oh-tabs__input-badge-container">
						<span
							class="oh-badge oh-badge--secondary oh-badge--small oh-badge--round mr-1"
							title="{{candidate_list.list.paginator.count}} {% trans "Candidates" %}"
						>
						{{candidate_list.list.paginator.count}}
						</span>
						{{candidate_list.grouper}}
					</div>
				</span>
			</div>
			<div class="oh-accordion-meta__body d-none">
				<div class="oh-sticky-table oh-sticky-table--no-overflow mb-5">
					<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" hx-target='#section' hx-get="{% url 'search-candidate' %}?{{pd}}&orderby=name&view=list">{% trans "Candidates" %}</div>
									<div class="oh-sticky-table__th">{% trans "Email" %}</div>
									<div class="oh-sticky-table__th">{% trans "Phone" %}</div>
									<div class="oh-sticky-table__th">{% trans "Recruitment" %}</div>
									<div class="oh-sticky-table__th">{% trans "Job Position" %}</div>
									<div class="oh-sticky-table__th">{% trans "Resume" %}</div>
									<div class="oh-sticky-table__th" style="width: 230px;">{% trans "Options" %}</div>
            						<div class="oh-sticky-table__th oh-sticky-table__right"  style="width: 190px;">{% trans "Actions" %}</div>
								</div>
							</div>
							{% for cand in candidate_list.list %}
							<div class="oh-sticky-table__tbody ui-sortable">
								<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
									{% 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">
											<div 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>
											</div>
										</div>
									</div>

									<a href="#" style="color: inherit;text-decoration: none;" class="oh-sticky-table__td ">{{cand.email}}</a>
									<a href="#" style="color: inherit;text-decoration: none;" class="oh-sticky-table__td">{{cand.mobile}}</a>
									<a href="#" style="color: inherit;text-decoration: none;"
										class="oh-sticky-table__td">{{cand.recruitment_id}}
									</a>
									<a href="#" style="color: inherit;text-decoration: none;"
										class="oh-sticky-table__td">{{cand.job_position_id}}
									</a>
									<a style="color: inherit;text-decoration: none;" class="oh-sticky-table__td" href="{{cand.resume.url}}"
										target="_blank" rel="noopener noreferrer"><span class="oh-btn oh-btn--info"> {% trans "Resume" %}</span>
									</a>

									<div class="oh-sticky-table__td">
										{% if perms.recruitment.change_candidate %}
										<div class="oh-btn-group">
										  	{% 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>
											{% else %}
												<button class="oh-btn oh-btn--light-bkg w-100"  title='{% trans "Converted " %}' style="opacity: 30%; padding:0.8rem 1rem">
													<ion-icon name="person-circle-outline"></ion-icon>            </button>
											{% endif %}
											{% if perms.recruitment.add_skillzonecandidate %}
												<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 %}
										{% if onboarding|app_installed %}
											{% if perms.recruitment.add_rejectedcandidate or request.user|is_stagemanager %}
												<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 section" %}"
												{% else %}
												title="{% trans "Add To Rejected section" %}"
												{% endif %}>
												<ion-icon name="thumbs-down-outline"></ion-icon>
												</button>
											{% endif %}
										{% endif %}
										<button
										  type="button"
										  hx-get='{% url "send-mail" cand.id %}'
										  title="{% trans "Send Mail" %}"
										  hx-target="#objectDetailsModalTarget"
										  hx-swap="innerHTML"
										  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>
										</div>
									  {% endif %}
									  </div>
									  <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>
								</div>
							</div>
							{% endfor %}
						</div>
					</div>
				</div>
				<div class="oh-pagination">
                    <span class="oh-pagination__page">
                      {% trans "Page" %} {{ candidate_list.list.number }} {% trans "of" %} {{ candidate_list.list.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="{{candidate_list.dynamic_name}}"
                        class="oh-pagination__input"
                        value="{{candidate_list.list.number}}"
                        hx-get="{% url 'search-candidate' %}?{{pd}}" hx-target="#section"
                        min="1"
                      />
                      <span class="oh-pagination__label"
                        >{% trans "of" %} {{candidate_list.list.paginator.num_pages}}</span
                      >
                      </div>
                      <ul class="oh-pagination__items">
                      {% if candidate_list.list.has_previous %}
                      <li class="oh-pagination__item oh-pagination__item--wide">
                        <a
                        hx-target="#section"
                        hx-get="{% url 'search-candidate' %}?{{pd}}&{{candidate_list.dynamic_name}}=1"
                        class="oh-pagination__link"
                        >{% trans "First" %}</a
                        >
                      </li>
                      <li class="oh-pagination__item oh-pagination__item--wide">
                        <a
                        hx-target="#section"
                        hx-get="{% url 'search-candidate' %}?{{pd}}&{{candidate_list.dynamic_name}}={{ candidate_list.list.previous_page_number }}"
                        class="oh-pagination__link"
                        >{% trans "Previous" %}</a
                        >
                      </li>
                      {% endif %} {% if candidate_list.list.has_next %}
                      <li class="oh-pagination__item oh-pagination__item--wide">
                        <a
                        hx-target="#section"
                        hx-get="{% url 'search-candidate' %}?{{pd}}&{{candidate_list.dynamic_name}}={{ candidate_list.list.next_page_number }}"
                        class="oh-pagination__link"
                        >{% trans "Next" %}</a
                        >
                      </li>
                      <li class="oh-pagination__item oh-pagination__item--wide">
                        <a
                        hx-target="#section"
                        hx-get="{% url 'search-candidate' %}?{{pd}}&{{candidate_list.dynamic_name}}={{ candidate_list.list.paginator.num_pages }}"
                        class="oh-pagination__link"
                        >{% trans "Last" %}</a
                        >
                      </li>
                      {% endif %}
                      </ul>
                    </nav>
                    </div>
			</div>
		</div>
	</div>
    {% endfor %}

	<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>
</div>
{% else %}
	<div class="oh-wrapper">
		<div class="oh-404">
			<img style="    width: 150px;height: 150px;" src="{% static 'images/ui/candidate.png' %}" class="oh-404__image mb-4" alt="Page not found. 404."/>
			<h5 class="oh-404__subtitle">{% trans "No group result found!" %}</h5>
		</div>
	</div>
{% endif %}


<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 section?",
	  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 section?",
	  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 section?",
	  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, #exportsection").hide();
	  if (ids.length) {
		$("#unselectAllInstances, #selectedCandidate, #exportsection").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()
	  });
	  $("#exportsection").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>
