// Discount functions for billing system

function toggleDiscountInput() {
    const userRole = localStorage.getItem('role');
    const discountAllowed = ['Admin', 'Manager'].includes(userRole);
    const discountGroup = document.getElementById('discountGroup');
    
    if (discountAllowed) {
        discountGroup.style.display = 'block';
    } else {
        discountGroup.style.display = 'none';
        clearDiscount();
    }
}

function updateDiscountAmount() {
    const discountPercentageInput = document.getElementById('discountPercentage');
    const discountAmountDisplay = document.getElementById('discountAmountDisplay');
    const subtotal = cart.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0);
    
    if (!discountPercentageInput.value) {
        discountAmountDisplay.textContent = '';
        updateBillSummary();
        return;
    }
    
    const discountPercentage = parseFloat(discountPercentageInput.value);
    
    if (discountPercentage < 0 || discountPercentage > 100) {
        app.showNotification('Discount percentage must be between 0 and 100', 'error');
        discountPercentageInput.value = '';
        discountAmountDisplay.textContent = '';
        updateBillSummary();
        return;
    }
    
    const discountAmount = subtotal * (discountPercentage / 100);
    discountAmountDisplay.textContent = `-${app.formatCurrency(discountAmount)}`;
    
    updateBillSummary();
}

function clearDiscount() {
    document.getElementById('discountPercentage').value = '';
    document.getElementById('discountAmountDisplay').textContent = '';
    updateBillSummary();
}

function getManualDiscount() {
    const discountPercentageInput = document.getElementById('discountPercentage');
    if (!discountPercentageInput.value) return { percentage: 0, amount: 0 };
    
    const subtotal = cart.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0);
    const discountPercentage = parseFloat(discountPercentageInput.value);
    const discountAmount = subtotal * (discountPercentage / 100);
    
    return { percentage: discountPercentage, amount: discountAmount };
}