document.addEventListener('DOMContentLoaded', function () {
  document.addEventListener('input', function (e) {
    const id = e.target.id || '';

    if (id.startsWith('price_net_') || id.startsWith('price_gross_')) {
      const rowId = id.split('_').pop();
      const netInput = document.getElementById('price_net_' + rowId);
      const grossInput = document.getElementById('price_gross_' + rowId);
      const taxInput = document.getElementById('price_tax_' + rowId);
      if (!netInput || !grossInput || !taxInput) return;

      const taxRate = parseFloat(taxInput.value.replace(',', '.')) || 0;
      const net = parseFloat(netInput.value.replace(',', '.'));
      const gross = parseFloat(grossInput.value.replace(',', '.'));

      if (id.startsWith('price_net_') && !isNaN(net)) {
        grossInput.value = (net * (1 + taxRate / 100)).toFixed(2).replace('.', ',');
      } else if (id.startsWith('price_gross_') && !isNaN(gross)) {
        netInput.value = formatDynamic(gross / (1 + taxRate / 100));
      }
      return;
    }

    if (id === 'price_net' || id === 'price_gross') {
      const netInput = document.getElementById('price_net');
      const grossInput = document.getElementById('price_gross');
      const taxInput = document.getElementById('price_tax');
      if (!netInput || !grossInput || !taxInput) return;

      const taxRate = parseFloat(taxInput.value.replace(',', '.')) || 0;
      const net = parseFloat(netInput.value.replace(',', '.'));
      const gross = parseFloat(grossInput.value.replace(',', '.'));

      if (id === 'price_net' && !isNaN(net)) {
        grossInput.value = (net * (1 + taxRate / 100)).toFixed(2).replace('.', ',');
      } else if (id === 'price_gross' && !isNaN(gross)) {
        netInput.value = formatDynamic(gross / (1 + taxRate / 100));
      }
    }
    
    if (id === 'charge_free_net' || id === 'charge_free_gross') {
      const netInput = document.getElementById('charge_free_net');
      const grossInput = document.getElementById('charge_free_gross');
      const taxInput = document.getElementById('price_tax');
      if (!netInput || !grossInput || !taxInput) return;

      const taxRate = parseFloat(taxInput.value.replace(',', '.')) || 0;
      const net = parseFloat(netInput.value.replace(',', '.'));
      const gross = parseFloat(grossInput.value.replace(',', '.'));

      if (id === 'charge_free_net' && !isNaN(net)) {
        grossInput.value = (net * (1 + taxRate / 100)).toFixed(2).replace('.', ',');
      } else if (id === 'charge_free_gross' && !isNaN(gross)) {
        netInput.value = formatDynamic(gross / (1 + taxRate / 100));
      }
    }
  });
  

  function formatDynamic(value) {
    let str = value.toFixed(5);
    str = str.replace(/0+$/, '');
    str = str.replace(/\.$/, '');
    const parts = str.split('.');
    if (parts.length === 2 && parts[1].length > 2) {
      return value.toFixed(parts[1].length).replace('.', ','); 
    }
    return value.toFixed(2).replace('.', ',');
  }
  
  document.querySelectorAll('.toggle_disabled').forEach(function (link) {
		link.addEventListener('click', function (e) {
			e.preventDefault();
			
			const targetId = this.getAttribute('data-id');
			const textarea = document.getElementById(targetId);
			
			if (textarea) {
				if (textarea.disabled) {
					textarea.disabled = false;
					this.querySelector('i').textContent = 'link_off';
				} else {
					textarea.disabled = true;
					this.querySelector('i').textContent = 'link';
				}
			}
		});
	});
	
  document.querySelectorAll('.toggle_readonly').forEach(function (link) {
		link.addEventListener('click', function (e) {
			e.preventDefault();
			
			const targetId = this.getAttribute('data-id');
			const input = document.getElementById(targetId);
			
			if (input) {
				if (input.readOnly) {
					input.readOnly = false;
					this.querySelector('i').textContent = 'link_off';
				} else {
					input.readOnly = true;
					this.querySelector('i').textContent = 'link';
				}
			}
		});
	});
  
  document.querySelectorAll('.toggle_multi').forEach(function (link) {
		link.addEventListener('click', function (e) {
			e.preventDefault();
			
			const targetId = this.getAttribute('data-id');
			if (!targetId) return;

			const scope = link.closest('form') || document;
			const targets = scope.querySelectorAll('.' + targetId);
  		if (!targets.length) return;
  		
  		const currentlyDisabled = Array.from(targets).some(el => el.disabled === true);
 		 	const newDisabled = !currentlyDisabled;
 		 	
 		 	targets.forEach(el => {
    		if ('disabled' in el) el.disabled = newDisabled;
    		if (!('disabled' in el)) {
			    el.style.display = newDisabled ? 'none' : '';
			  }
    	});
    	
    	const icon = link.querySelector('i');
    	if (icon) icon.textContent = newDisabled ? 'link' : 'link_off';
  		
		});
	});
	
	document.addEventListener("click", function (e) {
    const a = e.target.closest(".generate_code");
    if (!a) return;
    e.preventDefault();

    const input = document.getElementById("code");
    if (!input) return;

    input.value = generateCouponCode(12);
    input.dispatchEvent(new Event("input", { bubbles: true }));
    input.focus();
    input.select();
  });
  
  function generateCouponCode(len = 12) {
    const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    let out = "";
    const rnd = (n) => {
      if (window.crypto && crypto.getRandomValues) {
        const buf = new Uint32Array(1);
        crypto.getRandomValues(buf);
        return buf[0] % n;
      }
      return Math.floor(Math.random() * n);
    };

    for (let i = 0; i < len; i++) out += chars[rnd(chars.length)];

    return out;
  }
	
});
