/*
 * Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you require will output into a single css file (app.css in this case)
require('../css/admin.css');
require('bootstrap');
require('../css/common.css');
require('../js/geoloc.js');
const $ = require("jquery");

$('#flash-messages').flashNotification('init');

$(document).ready(function() {

	/*
	 * On user edit page, on the rolesgroup checkbox:
	 *		- display 'group' select if "Gestionnaire de groupe" is checked
	 *		- display 'comptoir' select if "Comptoir" is checked
	*/
	function possiblegroups_display_selects(e) {
		var label = $(this).closest('li').find('.control-label__text')[0].textContent.trim().toLowerCase()
		var isChecked = $(this).closest('li').find('.checked').length > 0

		if (label.includes('comptoir')) {
			if (isChecked) {
				$('.comptoirsgeres_select').removeClass('hide')
			} else {
				$('.comptoirsgeres_select').addClass('hide')
			}
		} else if (label.includes('groupe') || label.includes('contact')) {
			if (isChecked) {
				$('.groupesgeres_select').removeClass('hide')
			} else {
				$('.groupesgeres_select').addClass('hide')
			}
		}
	}

	$('.possible_group_cblist li .checkbox label').on('click', possiblegroups_display_selects);
	$('.possible_group_cblist li .checkbox label ins').on('click', possiblegroups_display_selects);


	$('.editableboolean').on('click', function (e) {
	    e.preventDefault();
	    var self = $(this);
	    $.ajax({
	        url : self.data('url'),
	        type: 'post',
	        data : {'value' : (self.data('value') == 'true')},
	        success: function(data) {
	            if(data.status == 'success' && !data.messages) {
	                if (data.newvalue == 'false') {
	                    self.text('non');
	                    self.data('value', 'false');
	                    self.addClass('label-danger');
	                    self.removeClass('label-success');
	                } else {
	                    self.data('value', 'true');
	                    self.text('oui');
	                    self.removeClass('label-danger');
	                    self.addClass('label-success');
	                }
	            } else {
	                // $(this).addClass('error');
	            }
	        }
	    });
	});

	// Hide or display Cotisation, Profils de Cotisation and Products Families submenu depending on TAV env and/or household mode
	const tav_env = document.getElementsByName('is-tav-env')[0].getAttribute('content');
	const household_based_allowance = document.getElementsByName('is-household-based-allowance')[0].getAttribute('content');

	let linksToCotisationAdherent = $('a[href="/admin/cotisation_adherent/list"]');
	for(let i = 0 ; i < linksToCotisationAdherent.length ; i++) {
		if(linksToCotisationAdherent[i].innerText === "Cotisation") {
			linksToCotisationAdherent[i].parentNode.style.display = (tav_env === "1") ? "none" : "";
		}
	}
	let linksToCotisationPresta = $('a[href="/admin/cotisation_prestataire/list"]');
	for(let i = 0 ; i < linksToCotisationPresta.length ; i++) {
		if(linksToCotisationPresta[i].innerText === "Cotisation") {
			linksToCotisationPresta[i].parentNode.style.display = (tav_env === "1") ? "none" : "";
		}
	}
	let linksToProfilDeCotisation = $('a[href="/admin/profilcotisation/list"]');
	for(let i = 0 ; i < linksToProfilDeCotisation.length ; i++) {
		if(linksToProfilDeCotisation[i].innerText === "Profils De Cotisation") {
			linksToProfilDeCotisation[i].parentNode.style.display = (tav_env === "1" && household_based_allowance === "0") ? "" : "none";
		}
	}
	let linksToProductsFamily = $('a[href="/admin/app/productfamily/list"]');
	for(let i = 0 ; i < linksToProductsFamily.length ; i++) {
		if(linksToProductsFamily[i].innerText === "Familles de produits") {
			linksToProductsFamily[i].parentNode.style.display = (tav_env === "1") ? "" : "none";
		}
	}
	let linksToThirdPartyFinancers = $('a[href="/admin/app/thirdpartyfinancer/list"]');
	for(let i = 0 ; i < linksToThirdPartyFinancers.length ; i++) {
		if(linksToThirdPartyFinancers[i].innerText === "Liste") {			
			linksToThirdPartyFinancers[i].closest("li.treeview").style.display = (tav_env === "1" && household_based_allowance === "1") ? "" : "none";
		}
	}


	var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

	var moyenDePaiement = document.querySelector('[id$="_moyenDePaiement"].select2-container a span');
	if(moyenDePaiement) {
		var moyenDePaiementObserver = new MutationObserver(actionOnMoyenDePaiementChange);
		moyenDePaiementObserver.observe(moyenDePaiement, {
			childList: true
		});
		function actionOnMoyenDePaiementChange() {
			var selector = document.querySelector('[id$="_jourPrelevement"].form-group');
			if (selector !== null) {
				selector.style.display = moyenDePaiement.innerHTML === "prélèvement" ? "" : "none";
			}
		}
		actionOnMoyenDePaiementChange();
	}

	var recevoirUnRappel = document.querySelector('[id$="_mailRappelCotisation"].form-group div div label div');
	if(recevoirUnRappel) {
		var recevoirUnRappelObserver = new MutationObserver(actionOnRecevoirUnRappelChange);
		recevoirUnRappelObserver.observe(recevoirUnRappel, {
			attributes: true
		});
		function actionOnRecevoirUnRappelChange() {
			var selector = document.querySelector('[id$="_jourMailRappelCotisation"].form-group');
			if (selector !== null) {
				selector.style.display = recevoirUnRappel.classList.contains('checked') ? "" : "none";
			}
		}
		actionOnRecevoirUnRappelChange();
	}

	if($(".fixBalanceAdherentFormPart").length > 0) {
		if (!$(".fixBalanceAdherentFormPart").parent().parent().hasClass('has-error')) {
			$(".fixBalanceAdherentFormPart").parent().parent().hide();
		}
		$(".fixBalanceAdherentFormPart").first().parent().parent().before(
			"<div class='form-group'><input class='btn btn-primary' type='button' id='showFieldsToFixBalance' value='Afficher les champs pour corriger le solde'></input></div>"
		);

		$('#showFieldsToFixBalance').on('click', function (e) {
			$(".fixBalanceAdherentFormPart").parent().parent().toggle();
		});
	}

	if($(".cancelRecurrentPaymentFormPart").length > 0) {
		if (!$(".cancelRecurrentPaymentFormPart").parent().parent().hasClass('has-error')) {
			$(".cancelRecurrentPaymentFormPart").parent().parent().hide();
		}

		// Add descriptive text
		$(".cancelRecurrentPaymentFormPart").first().parent().parent().prepend( 
			`<p class="help-block">${$(".recurrentPaymentReason").first().val()}</p> <p class="help-block">Cette action va indiquer au kohinos que le paiement récurrent Payzen a été résilié manuellement de façon anticipée.</p>`

		)

		// Add hide/show button with event handler
		$(".cancelRecurrentPaymentFormPart").first().parent().parent().before(
			"<div class='form-group'><input class='btn btn-primary' type='button' id='showFieldsToCancelRecurringPayment' value='Afficher les champs pour annuler le paiment récurrent en cours'></input></div>"
		);

		$('#showFieldsToCancelRecurringPayment').on('click', function (e) {
			$(".cancelRecurrentPaymentFormPart").parent().parent().toggle();
		});
	}
});
