<script>
    // row 1
    function setVat(value) {
        document.getElementById('vat').value = value + "%";
        document.getElementById('vat').dispatchEvent(new Event('input'));
    }
 
    // logistics row 2
    const emagButton = document.getElementById('emag-courier');
    const otherButton = document.getElementById('other-logistics');
    const othersInput = document.getElementById('others');
    const logisticsOptions = document.getElementById('logistics-options');
    const logisticsAmountInput = document.getElementById('logistics-amount');
    const logisticsMessage = document.getElementById('logistics-message');
    const emagOptions = document.getElementById('emag-options');
    const otherOptions = document.getElementById('other-options');
    const customLogisticsAmountInput = document.getElementById('custom-logistics-amount');

    function selectLogistics(type) {
    if (type === 'emag') {
        emagButton.classList.add('active');
        otherButton.classList.remove('active');
        othersInput.value = "eMAG Courier";
        emagOptions.style.display = 'block';
        otherOptions.style.display = 'none';
        logisticsMessage.style.display = 'none';
        logisticsAmountInput.placeholder = "Wybierz wartość poniżej";
        logisticsAmountInput.value = '';
        customLogisticsAmountInput.value = '';
        document.getElementById('logistics-name-container').style.display = 'flex';
    } else if (type === 'other') {
        otherButton.classList.add('active');
        emagButton.classList.remove('active');
        othersInput.value = "Inna logistyka";
        emagOptions.style.display = 'none';
        otherOptions.style.display = 'block';
        logisticsMessage.style.display = 'none';
        logisticsAmountInput.value = '';
        customLogisticsAmountInput.value = '';
        document.getElementById('logistics-name-container').style.display = 'flex';
    }
    document.getElementById('logistics-amount').dispatchEvent(new Event('input'));
    document.getElementById('custom-logistics-amount').dispatchEvent(new Event('input'));
}

// row 3

   function setLogisticsAmount(amount, element) {
    const buttons = document.querySelectorAll('.logistics-buttons .btn-main');
    buttons.forEach(button => button.classList.remove('active'));
    element.classList.add('active');

    const ronpln = parseFloat(document.getElementById('ronpln').value) || 0;
    const calculatedAmount = (amount * ronpln).toFixed(2);
    logisticsAmountInput.value = calculatedAmount + " PLN";
    document.getElementById('logistics-amount').dispatchEvent(new Event('input'));
}
    
document.getElementById('ronpln').addEventListener('input', function() {
    const activeButton = document.querySelector('.logistics-buttons .btn-main.active');
    if (activeButton) {
        const amount = parseFloat(activeButton.textContent.replace(' RON', ''));
        setLogisticsAmount(amount, activeButton);
    }
});


    window.onload = function() {
    document.getElementById('logistics-name-container').style.display = 'none';
    if (!emagButton.classList.contains('active') && !otherButton.classList.contains('active')) {
        logisticsMessage.style.display = 'block';
        emagOptions.style.display = 'none';
        otherOptions.style.display = 'none';
    } else {
        logisticsMessage.style.display = 'none';
    }
};

// row 4
function calculatePlnNetto() {
    const ronBrutto = parseFloat(document.getElementById('sale-price-ron').value.replace(',', '.'));
    const vatValue = document.getElementById('vat').value.replace('%', '').replace(',', '.');
    const vatPercentage = parseFloat(vatValue) / 100;
    const ronPlnRate = parseFloat(document.getElementById('ronpln').value.replace(',', '.'));

    if (!isNaN(ronBrutto) && !isNaN(vatPercentage) && !isNaN(ronPlnRate)) {
        const plnNetto = (ronBrutto / (1 + vatPercentage)) * ronPlnRate;
        document.getElementById('pln-netto').value = plnNetto.toFixed(2) + " PLN";
    } else {
        document.getElementById('pln-netto').value = "";
    }

    checkErrors();
}

// row 5
function calculateCommission() {
    const salePricePlnNetto = parseFloat(document.getElementById('pln-netto').value.replace(',', '.'));
    const commissionPercentage = parseFloat(document.getElementById('commission-percentage').value.replace(',', '.'));

    if (!isNaN(salePricePlnNetto) && !isNaN(commissionPercentage)) {
        const commission = salePricePlnNetto * (commissionPercentage / 100);
        document.getElementById('commission-calculated').value = commission.toFixed(2) + " PLN";
    } else {
        document.getElementById('commission-calculated').value = "";
    }

    checkErrors();
}

// row 6

function calculatePromotionCost() {
    const plnNetto = parseFloat(document.getElementById('pln-netto').value.replace(',', '.'));
    const promotionPercentage = parseFloat(document.getElementById('promotion-percentage').value.replace(',', '.'));

    if (!isNaN(plnNetto) && !isNaN(promotionPercentage)) {
        const promotionCost = plnNetto * (promotionPercentage / 100);
        document.getElementById('promotion-calculated').value = promotionCost.toFixed(2) + " PLN";
        document.querySelector('.error-msg-promotion').style.display = 'none';
    } else {
        document.getElementById('promotion-calculated').value = "";
        if (isNaN(promotionPercentage)) {
            document.querySelector('.error-msg-promotion').textContent = "Wprowadź prawidłową wartość w polu Zagregowany udział kosztów promocji (%)";
            document.querySelector('.error-msg-promotion').style.display = 'block';
        }
    }

    checkErrors();
}

// row 7

function calculateGeniusCost() {
    const salePrice = parseFloat(document.getElementById('sale-price-ron').value);
    const geniusCostField = document.getElementById('calculated-genius-cost');
    const ronPlnRate = parseFloat(document.getElementById('ronpln').value.replace(',', '.'));

    if (isNaN(salePrice)) {
        geniusCostField.value = "";
        return;
    }

    let geniusCost;
    if (salePrice < 30) {
        geniusCost = 1;
    } else if (salePrice < 40) {
        geniusCost = 1.5;
    } else if (salePrice < 50) {
        geniusCost = 2;
    } else if (salePrice < 75) {
        geniusCost = 2.5;
    } else if (salePrice < 150) {
        geniusCost = 3.5;
    } else {
        geniusCost = 5;
    }
    const result = geniusCost * ronPlnRate;
    geniusCostField.value = result.toFixed(2) + " PLN";
}

// row 8

function calculateTotalCost() {
    const productCost = parseFloat(document.getElementById('product-cost').value.replace(',', '.')) || 0;
    const logisticsCost = parseFloat(document.getElementById('logistics-amount').value.replace(',', '.')) || 0;
    const customLogisticsCost = parseFloat(document.getElementById('custom-logistics-amount').value.replace(',', '.')) || 0;
    const geniusCost = parseFloat(document.getElementById('calculated-genius-cost').value.replace(',', '.')) || 0;
    const commissionCost = parseFloat(document.getElementById('commission-calculated').value.replace(',', '.')) || 0;
    const promotionCost = parseFloat(document.getElementById('promotion-calculated').value.replace(',', '.')) || 0;

    const totalCost = productCost + logisticsCost + customLogisticsCost + geniusCost + commissionCost + promotionCost;
    document.getElementById('total-cost').value = totalCost.toFixed(2) + " PLN";
}

// row 9

function calculateProfitAndMargin() {
    const salePricePlnNetto = parseFloat(document.getElementById('pln-netto').value.replace('PLN', '').replace(',', '.').trim()) || 0;
    const totalCost = parseFloat(document.getElementById('total-cost').value.replace('PLN', '').replace(',', '.').trim()) || 0;

    const profit = salePricePlnNetto - totalCost;
    document.getElementById('profit-result').value = profit.toFixed(2) + " PLN";

    const margin = salePricePlnNetto > 0 ? (profit / salePricePlnNetto) * 100 : 0;
    document.getElementById('profit-margin').value = margin.toFixed(2) + " %";
}

// errors / warnings
function checkErrors() {
    const ronBrutto = parseFloat(document.getElementById('sale-price-ron').value.replace(',', '.'));
    const vatValue = document.getElementById('vat').value.replace('%', '').replace(',', '.');
    const vatPercentage = parseFloat(vatValue) / 100;
    const ronPlnRate = parseFloat(document.getElementById('ronpln').value.replace(',', '.'));
    const commissionPercentage = parseFloat(document.getElementById('commission-percentage').value.replace(',', '.'));
    const promotionPercentage = parseFloat(document.getElementById('promotion-percentage').value.replace(',', '.'));

    const baseFieldsFilled = !isNaN(ronBrutto) && !isNaN(vatPercentage) && !isNaN(ronPlnRate);

    document.querySelectorAll('.error-msg-ronbrutto').forEach(msg => {
        msg.style.display = isNaN(ronBrutto) ? 'block' : 'none';
        msg.textContent = "Wprowadź prawidłową wartość w polu Cena sprzedaży produktu (RON brutto)";
    });

    document.querySelectorAll('.error-msg-vat').forEach(msg => {
        msg.style.display = isNaN(vatPercentage) ? 'block' : 'none';
        msg.textContent = "Wprowadź prawidłową wartość w polu Stawka VAT";
    });

    document.querySelectorAll('.error-msg-ronpln').forEach(msg => {
        msg.style.display = isNaN(ronPlnRate) ? 'block' : 'none';
        msg.textContent = "Wprowadź prawidłową wartość w polu Kurs RONPLN";
    });

    document.querySelectorAll('.error-msg-commision').forEach(msg => {
        if (isNaN(commissionPercentage)) {
            msg.textContent = "Wprowadź prawidłową wartość w polu Wysokość prowizji (%)";
            msg.style.display = 'block';
        } else {
            msg.style.display = 'none';
        }
    });

    document.querySelectorAll('.error-msg-promotion').forEach(msg => {
        if (isNaN(promotionPercentage)) {
            msg.textContent = "Wprowadź prawidłową wartość w polu Zagregowany udział kosztów promocji (%)";
            msg.style.display = 'block';
        } else {
            msg.style.display = 'none';
        }
    });

    if (!baseFieldsFilled) {
        document.querySelectorAll('.error-msg-base-fields').forEach(msg => {
            msg.textContent = "Upewnij się, że wszystkie pola powyżej są poprawnie wypełnione";
            msg.style.display = 'block';
        });
    } else {
        document.querySelectorAll('.error-msg-base-fields').forEach(msg => {
            msg.style.display = 'none';
        });
    }
}


// listeners

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('ronpln').addEventListener('input', runCalculations);
    document.getElementById('vat').addEventListener('input', runCalculations);
    document.getElementById('sale-price-ron').addEventListener('input', runCalculations);
    document.getElementById('commission-percentage').addEventListener('input', runCalculations);
    document.getElementById('promotion-percentage').addEventListener('input', runCalculations);
    document.getElementById('logistics-amount').addEventListener('input', runCalculations);
    document.getElementById('custom-logistics-amount').addEventListener('input', runCalculations);
    document.getElementById('product-cost').addEventListener('input', runCalculations);

    document.querySelectorAll('.set-vat-button').forEach(button => {
        button.addEventListener('click', runCalculations);
    });
});

function runCalculations() {
    calculatePlnNetto();
    calculateCommission();
    calculatePromotionCost();
    calculateGeniusCost();
    calculateTotalCost();
    calculateProfitAndMargin();
}

//&#80;&#114;&#111;&#112;&#101;&#114;&#116;&#121;&#32;&#111;&#102;&#32;&#79;&#108;&#105;&#109;&#112;&#32;&#77;&#97;&#114;&#107;&#101;&#116;&#112;&#108;&#97;&#99;&#101;

document.addEventListener('keydown', function(event) {
    if (event.ctrlKey && (event.key === 's' || event.key === 'u' || event.key === 'c' || event.key === 'x' || event.key === 'v' || event.key === 'p')) {
        event.preventDefault();
    }
});

document.addEventListener('contextmenu', function(event) {
    event.preventDefault();
});
</script>