// source --> https://www.dunietz-elad.co.il/wp-content/plugins/privacy-policy-popup/includes/consent-helper.js?ver=1.0.7 
/**
 * iMark PTC - Consent Helper Functions
 *
 * JavaScript functions to manage user consent preferences
 */

/**
 * Delete all cookies except the consent cookie
 */
function deleteAllTrackingCookies() {
  const cookies = document.cookie.split(';');

  cookies.forEach(cookie => {
    const name = cookie.split('=')[0].trim();

    // Skip our consent cookie
    if (name === 'privacy_consent_17623') {
      return;
    }

    console.log('Attempting to delete cookie:', name);

    // Get root domain (e.g., www.example.com -> example.com)
    const hostname = window.location.hostname;
    const parts = hostname.split('.');
    const rootDomain = parts.length > 2 ? parts.slice(-2).join('.') : hostname;

    // Delete cookie for all possible paths and domains
    const domains = [
      hostname,              // www.example.com
      '.' + hostname,        // .www.example.com
      rootDomain,            // example.com
      '.' + rootDomain,      // .example.com
      ''                     // no domain
    ];

    const paths = ['/', ''];

    domains.forEach(domain => {
      paths.forEach(path => {
        if (domain) {
          document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}; domain=${domain}`;
        } else {
          document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}`;
        }
      });
    });
  });

  console.log('All tracking cookies deletion attempted');
}

/**
 * Set user consent preferences
 * @param {Object} preferences - Consent preferences object
 * @param {boolean} preferences.analytics - Allow analytics tracking
 * @param {boolean} preferences.marketing - Allow marketing tracking
 * @param {boolean} preferences.advertising - Allow advertising tracking
 * @param {boolean} preferences.functional - Allow functional cookies
 * @returns {Object} The consent object that was set
 */
function setConsentCookie(preferences) {
  // Only delete all cookies if in opt-out mode
  if (window.consentMode === 'opt-out') {
    deleteAllTrackingCookies();
  }

  const consent = {
    analytics: preferences.analytics || false,
    marketing: preferences.marketing || false,
    advertising: preferences.advertising || false,
    functional: preferences.functional || false,
    timestamp: Math.floor(Date.now() / 1000) // Unix timestamp (seconds)
  };

  // Set cookie for 3 months
  const expiryDate = new Date();
  expiryDate.setMonth(expiryDate.getMonth() + 3);

  // Create cookie string
  const cookieValue = encodeURIComponent(JSON.stringify(consent));
  document.cookie = `privacy_consent_17623=${cookieValue}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax`;

  // Dispatch event to trigger script loading
  document.dispatchEvent(new CustomEvent('cookieConsentUpdated', {
    detail: consent
  }));

  console.log('Consent preferences saved:', consent);

  return consent;
}

/**
 * Get current consent preferences
 * @returns {Object|null} The consent object or null if not set
 */
function getConsent() {
  const cookie = document.cookie.split('; ')
    .find(row => row.startsWith('privacy_consent_17623='));

  if (!cookie) return null;

  try {
    return JSON.parse(decodeURIComponent(cookie.split('=')[1]));
  } catch (e) {
    console.error('Error parsing consent cookie:', e);
    return null;
  }
}

/**
 * Delete consent cookie (reset consent)
 */
function deleteConsentCookie() {
  document.cookie = 'privacy_consent_17623=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  console.log('Consent cookie deleted');
}

/**
 * Check if user has consented to a specific category
 * @param {string} category - The category to check (analytics, marketing, advertising, functional)
 * @returns {boolean} True if user has consented to this category
 */
function hasConsent(category) {
  const consent = getConsent();
  return consent && consent[category] === true;
}

// Usage examples (commented out):
/*
// Accept all tracking
setConsentCookie({
  analytics: true,
  marketing: true,
  advertising: true,
  functional: true
});

// Accept only analytics
setConsentCookie({
  analytics: true,
  marketing: false,
  advertising: false,
  functional: true
});

// Reject all
setConsentCookie({
  analytics: false,
  marketing: false,
  advertising: false,
  functional: false
});

// Check if user has consented to analytics
if (hasConsent('analytics')) {
  console.log('User has consented to analytics');
}

// Get current consent
const currentConsent = getConsent();
console.log(currentConsent);

// Delete consent
deleteConsentCookie();
*/

/**
 * Show / Hide custom checkboxes
 */
 
function showCustomCheckboxes(){
	const radios = document.querySelectorAll('input[name="cookies"]');
	const radio_custom = document.getElementById('customize');
	const customize_hidden = document.getElementById('customize_hidden');
	
	if(radio_custom && radio_custom.checked){
		//In case the checkbox is clicked before the js is loaded
		customize_hidden.classList = 'open';
	}
	
	radios.forEach(function(item){
		item.addEventListener('click', function(){
			if(radio_custom.checked){
				customize_hidden.classList = 'open';
			}
			else{
				customize_hidden.classList = '';
			}
		});
	});
	
	
	const custom_checkboxes = document.querySelectorAll('#customize_hidden .checkbox_holder');
	custom_checkboxes.forEach(function(item){
		
		item.querySelector('.expand_selection').addEventListener('click', function(){
			if(item.classList.contains('open')){
				item.classList.remove('open');
				item.querySelector('.expand_info').style.height = "0px";
			}
			else{
				custom_checkboxes.forEach(function(other_item){
					if(other_item.classList.contains('open')){
						other_item.classList.remove('open');
						other_item.querySelector('.expand_info').style.height = "0px";
					}
				});
				item.classList.add('open');
				const expand_info = item.querySelector('.expand_info');
				console.log(expand_info.scrollHeight);
				expand_info.style.height = expand_info.scrollHeight + 'px';
			}
		});
	});
}

function remove_loading_icon(){
	document.getElementById('privacy_policy_popup').classList = 'loaded';
}

window.addEventListener('load', function(){
	check_imark_cookie_existing();
});

function check_imark_cookie_existing(cookie_id = 'privacy_consent_17623'){
	
    // Check if consent cookie already exists
	if(document.cookie.match(/^(.*;)?\s*privacy_consent_17623\s*=\s*[^;]+(.*)?$/)){
		document.body.classList.remove('page_consent_active');
		
		if(document.getElementById('privacy_policy_popup_close').classList.contains('show_consent_popup')){
			document.getElementById('privacy_policy_popup_close').classList.remove('show_consent_popup');
			document.body.classList.remove('page_consent_nonintrusive');
		}
		return;
	}
	else{	
		document.body.classList.add('page_consent_active');
		
		if(!document.getElementById('privacy_policy_popup_close').classList.contains('show_consent_popup')){
			document.getElementById('privacy_policy_popup_close').classList.add('show_consent_popup');
		}
		if(document.getElementById('privacy_policy_popup_close').classList.contains('non-intrusive') && !document.body.classList.contains('page_consent_nonintrusive')){
			document.body.classList.add('page_consent_nonintrusive');
		}
		showCustomCheckboxes();
		
		remove_loading_icon();
	}
	
};
// source --> https://www.dunietz-elad.co.il/wp-content/themes/dunitz-elad/admin/assets/js/utms.js?ver=1739047763 
if(document.addEventListener){
    document.addEventListener('DOMContentLoaded', imark_utm_tracking);
}else{
    document.attachEvent('DOMContentLoaded', imark_utm_tracking);
}

function imark_utm_tracking(){

    const utm_list = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
    const cookie_expiry_days = 30;

    utm_list.forEach(param => {
        var paramValue = imark_get_url_param(param);
        if (paramValue) {
            imark_set_cookie(param, paramValue, cookie_expiry_days);
        }else {
            paramValue = imark_get_cookie(param);
        }

        imark_populate_form(param, paramValue, cookie_expiry_days);
    });

}

function imark_get_url_param(name){
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

function imark_set_cookie(name, value, days){

    let expires = "";
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function imark_get_cookie(name){
    const nameEQ = name + "=";
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i];
        while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1, cookie.length);
        }
        if (cookie.indexOf(nameEQ) === 0) {
            return cookie.substring(nameEQ.length, cookie.length);
        }
    }
    return '';
    
}

function imark_populate_form(param, paramValue){

    const hiddenField = document.querySelector('input[name="' + param + '"]');

    if (hiddenField) {
        hiddenField.value = paramValue;
    }

};