// Business Loan Calculator JavaScript
(function() {
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('business-loan-form').addEventListener('submit', calculate);
    });

    function calculate(e) {
        e.preventDefault();

        // Input values
        const amount = parseFloat(document.getElementById('amount').value);
        const annualInterest = parseFloat(document.getElementById('interest').value) / 100;
        const years = parseInt(document.getElementById('term').value);
        const frequency = parseInt(document.getElementById('frequency').value);
        const fees = parseFloat(document.getElementById('fees').value) || 0;

        // Validations
        if (isNaN(amount) || isNaN(annualInterest) || isNaN(years) || isNaN(frequency)) {
            alert('Please enter valid numbers in all fields.');
            return;
        }

        // Calculations
        const periods = years * frequency;
        const ratePerPeriod = annualInterest / frequency;

        const payment = (amount * ratePerPeriod) / (1 - Math.pow(1 + ratePerPeriod, -periods));
        const totalPayment = (payment * periods) + fees;
        const totalInterest = (payment * periods) - amount;

        // Display results
        if (isFinite(payment)) {
            document.getElementById('payment-amount').textContent = payment.toFixed(2);
            document.getElementById('total-interest').textContent = totalInterest.toFixed(2);
            document.getElementById('total-cost').textContent = totalPayment.toFixed(2);

            generateAmortizationSchedule(amount, ratePerPeriod, payment, periods);

            document.getElementById('results').style.display = 'block';
        } else {
            alert('Calculation error. Please check your input values.');
        }
    }

    function generateAmortizationSchedule(principal, ratePerPeriod, payment, periods) {
        const scheduleBody = document.querySelector('#amortization-schedule tbody');
        scheduleBody.innerHTML = '';

        let remainingBalance = principal;

        for (let i = 1; i <= periods; i++) {
            const interestPayment = remainingBalance * ratePerPeriod;
            const principalPayment = payment - interestPayment;
            remainingBalance -= principalPayment;

            remainingBalance = remainingBalance < 0 ? 0 : remainingBalance;

            const row = scheduleBody.insertRow();
            row.insertCell(0).textContent = i;
            row.insertCell(1).textContent = payment.toFixed(2);
            row.insertCell(2).textContent = principalPayment.toFixed(2);
            row.insertCell(3).textContent = interestPayment.toFixed(2);
            row.insertCell(4).textContent = remainingBalance.toFixed(2);
        }
    }
})();


// Auto Loan Calculator JavaScript
(function() {
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('auto-loan-form').addEventListener('submit', calculateAutoLoan);
    });

    function calculateAutoLoan(e) {
        e.preventDefault();

        // Input values
        const vehiclePrice = parseFloat(document.getElementById('vehicle-price').value) || 0;
        const downPayment = parseFloat(document.getElementById('down-payment').value) || 0;
        const tradeIn = parseFloat(document.getElementById('trade-in').value) || 0;
        const salesTaxRate = parseFloat(document.getElementById('sales-tax').value) / 100 || 0;
        const fees = parseFloat(document.getElementById('fees').value) || 0;
        const annualInterestRate = parseFloat(document.getElementById('interest-rate').value) / 100 || 0;
        const loanTermYears = parseFloat(document.getElementById('loan-term').value) || 0;
        const paymentFrequency = parseInt(document.getElementById('payment-frequency').value);

        // Validations
        if (vehiclePrice <= 0 || annualInterestRate < 0 || loanTermYears <= 0 || paymentFrequency <= 0) {
            alert('Please enter valid numbers in the required fields.');
            return;
        }

        // Calculations
        const taxableAmount = vehiclePrice - tradeIn;
        const salesTax = taxableAmount * salesTaxRate;
        const totalVehicleCost = vehiclePrice + salesTax + fees - downPayment - tradeIn;
        const loanAmount = totalVehicleCost;

        const totalPayments = loanTermYears * paymentFrequency;
        const ratePerPeriod = annualInterestRate / paymentFrequency;

        const payment = (loanAmount * ratePerPeriod) / (1 - Math.pow(1 + ratePerPeriod, -totalPayments));
        const totalPayment = payment * totalPayments;
        const totalInterest = totalPayment - loanAmount;

        // Display results
        if (isFinite(payment)) {
            document.getElementById('loan-amount').textContent = loanAmount.toFixed(2);
            document.getElementById('auto-payment-amount').textContent = payment.toFixed(2);
            document.getElementById('auto-total-interest').textContent = totalInterest.toFixed(2);
            document.getElementById('auto-total-cost').textContent = totalPayment.toFixed(2);

            generateAutoAmortizationSchedule(loanAmount, ratePerPeriod, payment, totalPayments);

            document.getElementById('auto-results').style.display = 'block';
        } else {
            alert('Calculation error. Please check your input values.');
        }
    }

    function generateAutoAmortizationSchedule(principal, ratePerPeriod, payment, totalPayments) {
        const scheduleBody = document.querySelector('#auto-amortization-schedule tbody');
        scheduleBody.innerHTML = '';

        let remainingBalance = principal;

        for (let i = 1; i <= totalPayments; i++) {
            const interestPayment = remainingBalance * ratePerPeriod;
            const principalPayment = payment - interestPayment;
            remainingBalance -= principalPayment;

            remainingBalance = remainingBalance < 0 ? 0 : remainingBalance;

            const row = scheduleBody.insertRow();
            row.insertCell(0).textContent = i;
            row.insertCell(1).textContent = payment.toFixed(2);
            row.insertCell(2).textContent = principalPayment.toFixed(2);
            row.insertCell(3).textContent = interestPayment.toFixed(2);
            row.insertCell(4).textContent = remainingBalance.toFixed(2);
        }
    }
})();
