{% extends "base.html" %}
{% load static %}

{% block title %}Purchase Return - {{ po.po_number }}{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2 class="mb-4">Purchase Return for PO {{ po.po_number }}</h2>

    <form method="POST">
        {% csrf_token %}
        {{ formset.management_form }}

        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Return Items</h5>
            </div>
            <div class="card-body table-responsive">
                <table class="table table-bordered">
                    <thead class="table-light">
                        <tr>
                            <th>Product</th>
                            <th>Unit Price</th>
                            <th>Purchased Qty</th>
                            <th>Return Quantity</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for form in formset %}
                        <tr>
                            <td>{{ form.product }}</td>
                            <td>
                                {{ form.price }}
                            </td>
                            <td>
                                {% for item in po.items.all %}
                                    {% if item.product.id == form.initial.product %}
                                        <span class="purchased-qty" data-product-id="{{ form.initial.product }}">{{ item.quantity }}</span>
                                    {% endif %}
                                {% endfor %}
                            </td>
                            <td>
                                {{ form.quantity }}
                                {% if form.quantity.errors %}
                                    <div class="text-danger small">{{ form.quantity.errors }}</div>
                                {% endif %}
                                <div class="invalid-feedback d-none">Cannot exceed purchased quantity</div>
                            </td>
                            <td>
                                <span class="row-total">0.00</span>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                    <tfoot class="table-light">
                        <tr>
                            <td></td>
                            <td colspan="3" class="text-end"><strong>Grand Total:</strong></td>
                            <td><strong id="grand-total">0.00</strong></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="mb-3">
            <label for="id_notes" class="form-label">Notes</label>
            <textarea name="notes" id="id_notes" class="form-control" rows="3"></textarea>
        </div>

        <div class="d-flex justify-content-between">
            <a href="{% url 'purchase_order_detail' po.id %}" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> Cancel
            </a>
            <button type="submit" class="btn btn-success">
                <i class="bi bi-save"></i> Process Return
            </button>
        </div>
    </form>
</div>

<!-- Toast Notification -->
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1055;">
    <div id="liveToast" class="toast align-items-center text-bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body" id="toast-body">
          <!-- Dynamic message here -->
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>
  </div>
  

<script>
document.addEventListener('DOMContentLoaded', function() {
    function updateTotals() {
        let grandTotal = 0;

        document.querySelectorAll('tbody tr').forEach(row => {
            const priceInput = row.querySelector('input[name$="-price"]');
            const quantityInput = row.querySelector('input[name$="-quantity"]');
            const totalCell = row.querySelector('.row-total');
            const purchasedQtySpan = row.querySelector('.purchased-qty');
            const invalidFeedback = row.querySelector('.invalid-feedback');

            if (priceInput && quantityInput && totalCell && purchasedQtySpan) {
                const price = parseFloat(priceInput.value) || 0;
                const quantity = parseFloat(quantityInput.value) || 0;
                const purchasedQty = parseFloat(purchasedQtySpan.textContent) || 0;

                // Live validation
                if (quantity > purchasedQty) {
                    invalidFeedback.textContent = `Cannot return more than ${purchasedQty}`;
                    invalidFeedback.classList.remove('d-none');
                    quantityInput.classList.add('is-invalid');
                } else {
                    invalidFeedback.textContent = '';
                    invalidFeedback.classList.add('d-none');
                    quantityInput.classList.remove('is-invalid');
                }

                const total = price * quantity;
                totalCell.textContent = total.toFixed(2);

                if (!quantityInput.classList.contains('is-invalid')) {
                    grandTotal += total;
                }
            }
        });

        document.getElementById('grand-total').textContent = grandTotal.toFixed(2);
    }

    // Bind events
    document.querySelectorAll('input[name$="-quantity"], input[name$="-price"]').forEach(input => {
        input.addEventListener('input', updateTotals);
    });

    // Form submission prevention
    const form = document.querySelector('form');
    form.addEventListener('submit', function(e) {
        const hasError = document.querySelectorAll('.is-invalid').length > 0;
        if (hasError) {
            e.preventDefault();
            showToast('Please fix quantity errors before submitting!');
        }
    });

    function showToast(message) {
        const toastBody = document.getElementById('toast-body');
        toastBody.textContent = message;

        const toastElement = document.getElementById('liveToast');
        const toast = new bootstrap.Toast(toastElement);
        toast.show();
    }

    // Initialize
    updateTotals();
});

</script>
{% endblock %}


<style>
    #grand-total {
        background-color: #fff3cd;
        padding: 5px 10px;
        border-radius: 5px;
        display: inline-block;
    }
</style>