{% extends "base.html" %}

{% block content %}
    <h1>Request New Assessments</h1>
    <form method="POST" enctype="multipart/form-data" id="request-form">
        <div id="assessment-entries">
            <!-- Assessment entry will be dynamically added here -->
        </div>
        <button type="button" class="btn btn-secondary mb-3" onclick="addAssessmentEntry()">Add Assessment</button>

        <div class="form-group">
            <label for="payment_slip">Payment Slip (PNG, JPG, JPEG, PDF):</label>
            <input type="file" id="payment_slip" name="payment_slip" class="form-control-file" accept=".png,.jpg,.jpeg,.pdf" required>
            <small class="form-text text-muted">Transfer the total amount to the bank account below and upload the payment proof.</small>
        </div>

        <div class="alert alert-info" role="alert">
            <strong>Total Cost: ₹<span id="total-cost">0.00</span></strong>
        </div>

        <button type="submit" class="btn btn-primary">Submit Request</button>
    </form>

    <div class="alert alert-secondary mt-3" role="alert">
        <div><strong>Name:</strong> Manas Life Aid and Research</div>
        <div><strong>Bank Name:</strong> State Bank Of India</div>
        <div><strong>Current A/c No:</strong> 38202577443</div>
        <div><strong>IFS Code:</strong> SBIN0000413</div>
    </div>

    <script>
        const assessments = [
            {% for assessment in assessments %}
            {
                id: "{{ assessment.id }}",
                name: "{{ assessment.name }}",
                price: parseFloat("{{ assessment.price or 0 }}"),
                min_quantity: parseInt("{{ assessment.min_quantity or 1 }}")
            },
            {% endfor %}
        ];

        let entryCounter = 0;

        function addAssessmentEntry() {
            entryCounter++;
            const entryId = `entry-${entryCounter}`;
            const newEntry = document.createElement('div');
            newEntry.classList.add('assessment-entry', 'card', 'mb-3');
            newEntry.id = entryId;
            newEntry.innerHTML = `
                <div class="card-body">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="assessment_id_${entryCounter}">Assessment:</label>
                            <select name="assessment_ids" class="form-control" required onchange="updateEntryCost('${entryId}')">
                                <option value="">Select an Assessment</option>
                                ${assessments.map(a => `<option value="${a.id}" data-price="${a.price}" data-min="${a.min_quantity}">${a.name}</option>`).join('')}
                            </select>
                        </div>
                        <div class="form-group col-md-4">
                            <label for="quantity_${entryCounter}">Quantity:</label>
                            <input type="number" name="quantities" class="form-control" min="1" required onchange="updateEntryCost('${entryId}')">
                        </div>
                        <div class="form-group col-md-2 d-flex align-items-end">
                            <button type="button" class="btn btn-danger" onclick="removeAssessmentEntry('${entryId}')">Remove</button>
                        </div>
                    </div>
                    <small class="form-text text-muted">Entry Cost: ₹<span class="entry-cost">0.00</span></small>
                </div>
            `;
            document.getElementById('assessment-entries').appendChild(newEntry);
        }

        function removeAssessmentEntry(entryId) {
            document.getElementById(entryId).remove();
            updateTotalCost();
        }

        function updateEntryCost(entryId) {
            const entry = document.getElementById(entryId);
            const assessmentSelect = entry.querySelector('select');
            const quantityInput = entry.querySelector('input[type="number"]');
            const selectedOption = assessmentSelect.options[assessmentSelect.selectedIndex];
            
            if (!selectedOption.value) {
                entry.querySelector('.entry-cost').textContent = '0.00';
                updateTotalCost();
                return;
            }

            const price = parseFloat(selectedOption.getAttribute('data-price'));
            const minQty = parseInt(selectedOption.getAttribute('data-min'));
            
            if (parseInt(quantityInput.value) < minQty) {
                quantityInput.value = minQty;
            }
            
            const quantity = parseInt(quantityInput.value) || minQty;
            quantityInput.min = minQty;

            const entryCost = price * quantity;
            entry.querySelector('.entry-cost').textContent = entryCost.toFixed(2);
            updateTotalCost();
        }

        function updateTotalCost() {
            let total = 0;
            document.querySelectorAll('.assessment-entry').forEach(entry => {
                const costText = entry.querySelector('.entry-cost').textContent;
                total += parseFloat(costText);
            });
            document.getElementById('total-cost').textContent = total.toFixed(2);
        }

        // Add one entry by default
        document.addEventListener('DOMContentLoaded', function() {
            addAssessmentEntry();
        });
    </script>
{% endblock %}
