<!-- installment_calculator.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installment Calculator</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .result-box {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-top: 20px;
        }
        
        #product_results {
            position: absolute;
            max-height: 200px;
            overflow-y: auto;
            background: white;
            width: 100%;
            z-index: 1000;
            display: none;
        }

        .product_item {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .product_item:hover {
            background-color: #e9ecef !important;
        }

        .form-group {
            position: relative;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <h4>Installment Calculator</h4>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label>Search Product:</label>
                    <input type="text" class="form-control" id="product_search" placeholder="Enter product name or barcode">
                    <div id="product_results"></div>
                </div>
                
                <div class="form-group">
                    <label>Product Price:</label>
                    <input type="number" class="form-control" id="product_price" readonly>
                </div>

                <div class="form-group">
                    <label>Down Payment:</label>
                    <input type="number" class="form-control" id="down_payment" value="0" min="0">
                </div>

                <div class="form-group">
                    <label>Number of Months:</label>
                    <input type="number" class="form-control" id="months" value="1" min="1">
                </div>

                <div class="form-group">
                    <label>Interest Rate (% per year):</label>
                    <input type="number" step="0.01" class="form-control" id="interest_rate" value="0" min="0">
                </div>

                <div class="form-group">
                    <label>Apply Interest After Months:</label>
                    <input type="number" class="form-control" id="interest_start_month" value="0" min="0">
                </div>

                <button class="btn btn-primary" onclick="calculateInstallment()">Calculate</button>
                <button class="btn btn-secondary" onclick="resetCalculator()">Reset</button>
            </div>

            <div class="col-md-6">
                <div class="result-box">
                    <h5>Payment Summary</h5>
                    <table class="table table-sm">
                        <tr>
                            <td>Total Product Price:</td>
                            <td id="total_price">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Down Payment:</td>
                            <td id="down_payment_display">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Remaining Amount:</td>
                            <td id="remaining_amount">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Total Interest:</td>
                            <td id="total_interest">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Total Amount with Interest:</td>
                            <td id="total_with_interest">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Monthly Payment (Before Interest):</td>
                            <td id="monthly_payment">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Monthly Payment (With Interest):</td>
                            <td id="monthly_payment_with_interest">LKR 0.00</td>
                        </tr>
                        <tr>
                            <td>Profit from Interest:</td>
                            <td id="interest_profit">LKR 0.00</td>
                        </tr>
                    </table>

                    <div id="monthly_breakdown" class="mt-4">
                        <h6>Monthly Payment Breakdown</h6>
                        <table class="table table-sm" id="breakdown_table">
                            <thead>
                                <tr>
                                    <th>Month</th>
                                    <th>Payment</th>
                                    <th>Interest</th>
                                    <th>Total</th>
                                    <th>Remaining</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
            // Product search
            $('#product_search').on('input', function() {
                var search = $(this).val();
                if(search != "") {
                    $.ajax({
                        url: "search_product.php",
                        method: "POST",
                        data: {query: search},
                        success: function(data) {
                            $('#product_results').show().html(data);
                        }
                    });
                } else {
                    $('#product_results').hide();
                }
            });

            // Product selection
            $(document).on('click', '.product_item', function() {
                let productName = $(this).text();
                let productPrice = $(this).data('price');
                
                $('#product_search').val(productName);
                $('#product_price').val(productPrice);
                $('#product_results').hide();
                
                calculateInstallment();
            });

            // Auto-calculate on input change
            $('#down_payment, #months, #interest_rate, #interest_start_month').on('input', function() {
                calculateInstallment();
            });
        });

        
        

     // Replace the existing calculateInstallment function with this corrected version:

function calculateInstallment() {
    const productPrice = parseFloat($('#product_price').val()) || 0;
    const downPayment = parseFloat($('#down_payment').val()) || 0;
    const months = parseInt($('#months').val()) || 1;
    const yearlyInterestRate = parseFloat($('#interest_rate').val()) || 0;
    const interestStartMonth = parseInt($('#interest_start_month').val()) || 0;

    // Validate inputs
    if (downPayment > productPrice) {
        alert('Down payment cannot be greater than product price');
        $('#down_payment').val(0);
        return;
    }

    const remainingAmount = productPrice - downPayment;
    const monthlyPaymentWithoutInterest = remainingAmount / months;
    
    // Calculate total interest based on remaining balance at interest start month
    let totalInterest = 0;
    let monthlyPaymentWithInterest = monthlyPaymentWithoutInterest;
    
    if (interestStartMonth < months) {
        // Calculate remaining balance at interest start month
        const remainingBalanceAtInterestStart = remainingAmount - (monthlyPaymentWithoutInterest * interestStartMonth);
        // Calculate interest on remaining balance
        totalInterest = remainingBalanceAtInterestStart * (yearlyInterestRate / 100);
        
        // Calculate new monthly payment for remaining months with interest
        const remainingMonths = months - interestStartMonth;
        monthlyPaymentWithInterest = (remainingBalanceAtInterestStart + totalInterest) / remainingMonths;
    }

    let breakdown = [];
    let remainingBalance = remainingAmount;

    // Generate monthly breakdown
    for(let month = 1; month <= months; month++) {
        let currentPayment = monthlyPaymentWithoutInterest;
        let monthlyInterest = 0;
        let totalMonthlyPayment = currentPayment;

        if (month > interestStartMonth) {
            // After interest start month, use the payment amount with interest
            currentPayment = monthlyPaymentWithInterest;
            monthlyInterest = totalInterest / (months - interestStartMonth);
            totalMonthlyPayment = currentPayment;
        }

        breakdown.push({
            month: month,
            payment: currentPayment - monthlyInterest,  // Principal payment
            interest: monthlyInterest,
            total: totalMonthlyPayment,
            remaining: Math.max(0, remainingBalance - currentPayment)
        });

        remainingBalance -= currentPayment;
    }

    // Update display
    $('#total_price').text('LKR ' + productPrice.toFixed(2));
    $('#down_payment_display').text('LKR ' + downPayment.toFixed(2));
    $('#remaining_amount').text('LKR ' + remainingAmount.toFixed(2));
    $('#total_interest').text('LKR ' + totalInterest.toFixed(2));
    $('#total_with_interest').text('LKR ' + (remainingAmount + totalInterest).toFixed(2));
    $('#monthly_payment').text('LKR ' + monthlyPaymentWithoutInterest.toFixed(2));
    $('#monthly_payment_with_interest').text('LKR ' + monthlyPaymentWithInterest.toFixed(2));
    $('#interest_profit').text('LKR ' + totalInterest.toFixed(2));

    // Update breakdown table
    updateBreakdownTable(breakdown);
}

function updateBreakdownTable(breakdown) {
    let breakdownHtml = '';
    breakdown.forEach(row => {
        breakdownHtml += `
            <tr>
                <td>${row.month}</td>
                <td>LKR ${row.payment.toFixed(2)}</td>
                <td>LKR ${row.interest.toFixed(2)}</td>
                <td>LKR ${row.total.toFixed(2)}</td>
                <td>LKR ${row.remaining.toFixed(2)}</td>
            </tr>
        `;
    });
    $('#breakdown_table tbody').html(breakdownHtml);
}


    </script>
</body>
</html>