<?php

/**

 * Payments Manual Entry Form

 */

// Get students for dropdown

require_once '../../config.php';

$conn = getDBConnection();

$students = $conn->query("SELECT id, student_id, first_name, last_name, class FROM students WHERE status = 'active' ORDER BY first_name");

$feeStructures = $conn->query("SELECT * FROM fee_structures ORDER BY class_name, fee_type");

?>

<div class="row-counter">

    <span><i class="fas fa-credit-card me-2"></i>Entering Payments - <span id="row-count">1</span> record(s)</span>

    <button type="button" class="btn btn-sm btn-primary" onclick="addRow()">

        <i class="fas fa-plus me-2"></i>Add Another Payment

    </button>

</div>



<div id="rows-container">

    <!-- Row 1 -->

    <div class="data-row mb-4 p-3 border rounded">

        <div class="d-flex justify-content-between mb-3">

            <h6 class="text-primary">Payment #1</h6>

            <span class="remove-row" onclick="removeRow(this)" title="Remove this payment">

                <i class="fas fa-times-circle"></i>

            </span>

        </div>

        <div class="row">

            <div class="col-md-4 mb-3">

                <label class="form-label">Student <span class="text-danger">*</span></label>

                <select class="form-select student-select" name="payments[0][student_id]" required>

                    <option value="">Select Student</option>

                    <?php while($student = $students->fetch_assoc()): ?>

                    <option value="<?php echo $student['id']; ?>" data-id="<?php echo $student['student_id']; ?>">

                        <?php echo $student['first_name'] . ' ' . $student['last_name'] . ' (' . $student['student_id'] . ' - ' . $student['class'] . ')'; ?>

                    </option>

                    <?php endwhile; ?>

                </select>

            </div>

            <div class="col-md-4 mb-3">

                <label class="form-label">Fee Structure <span class="text-danger">*</span></label>

                <select class="form-select" name="payments[0][fee_structure_id]" required>

                    <option value="">Select Fee</option>

                    <?php 

                    mysqli_data_seek($feeStructures, 0);

                    while($fee = $feeStructures->fetch_assoc()): 

                    ?>

                    <option value="<?php echo $fee['id']; ?>" data-amount="<?php echo $fee['amount']; ?>">

                        <?php echo $fee['class_name'] . ' - ' . $fee['fee_type'] . ' (₵' . number_format($fee['amount'], 2) . ')'; ?>

                    </option>

                    <?php endwhile; ?>

                </select>

            </div>

            <div class="col-md-4 mb-3">

                <label class="form-label">Amount Paid (₵) <span class="text-danger">*</span></label>

                <input type="number" step="0.01" class="form-control amount-paid" name="payments[0][amount_paid]" required>

            </div>

        </div>

        <div class="row">

            <div class="col-md-4 mb-3">

                <label class="form-label">Payment Date <span class="text-danger">*</span></label>

                <input type="date" class="form-control" name="payments[0][payment_date]" value="<?php echo date('Y-m-d'); ?>" required>

            </div>

            <div class="col-md-4 mb-3">

                <label class="form-label">Payment Method</label>

                <select class="form-select" name="payments[0][payment_method]">

                    <option value="cash">Cash</option>

                    <option value="card">Card</option>

                    <option value="bank_transfer">Bank Transfer</option>

                    <option value="online">Online</option>

                </select>

            </div>

            <div class="col-md-4 mb-3">

                <label class="form-label">Transaction ID</label>

                <input type="text" class="form-control" name="payments[0][transaction_id]" placeholder="Optional">

            </div>

        </div>

        <div class="row">

            <div class="col-md-12 mb-3">

                <label class="form-label">Notes</label>

                <textarea class="form-control" name="payments[0][notes]" rows="2" placeholder="Optional notes"></textarea>

            </div>

        </div>

    </div>

</div>



<script>

let rowCount = 1;



// Reset student and fee data for fresh queries

<?php 

mysqli_data_seek($students, 0);

mysqli_data_seek($feeStructures, 0);

?>



function addRow() {

    const container = document.getElementById('rows-container');

    const template = container.children[0].cloneNode(true);

    

    // Update indices

    rowCount++;

    template.querySelectorAll('[name^="payments"]').forEach(input => {

        const name = input.getAttribute('name');

        input.setAttribute('name', name.replace(/\[\d+\]/, `[${rowCount-1}]`));

        if (input.type === 'select-one') {

            input.selectedIndex = 0;

        } else if (input.type !== 'date') {

            input.value = '';

        }

    });

    

    // Update header

    template.querySelector('h6').textContent = `Payment #${rowCount}`;

    

    container.appendChild(template);

    document.getElementById('row-count').textContent = rowCount;

    

    // Re-attach event listeners

    attachFeeAmountListeners();

}



function removeRow(btn) {

    if (rowCount > 1) {

        btn.closest('.data-row').remove();

        rowCount--;

        document.getElementById('row-count').textContent = rowCount;

        

        // Renumber remaining rows

        document.querySelectorAll('.data-row').forEach((row, index) => {

            row.querySelector('h6').textContent = `Payment #${index + 1}`;

            row.querySelectorAll('[name^="payments"]').forEach(input => {

                const name = input.getAttribute('name');

                input.setAttribute('name', name.replace(/\[\d+\]/, `[${index}]`));

            });

        });

        

        // Re-attach event listeners

        attachFeeAmountListeners();

    }

}



// Auto-fill amount when fee is selected

function attachFeeAmountListeners() {

    document.querySelectorAll('select[name$="[fee_structure_id]"]').forEach(select => {

        select.addEventListener('change', function() {

            const selected = this.options[this.selectedIndex];

            const amount = selected.dataset.amount;

            if (amount) {

                const row = this.closest('.data-row');

                const amountInput = row.querySelector('.amount-paid');

                if (amountInput) {

                    amountInput.value = amount;

                }

            }

        });

    });

}



// Initialize listeners

attachFeeAmountListeners();

</script>