{% extends 'base.html' %}
{% load static %}
{% block title %}{{ title }} - Rapha-Bethel BNPS{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.bootstrap5.min.css" rel="stylesheet">
<style>
    .ts-control { border-radius: 0.375rem !important; padding: 0.45rem 0.75rem !important; }
    button:disabled { cursor: not-allowed; opacity: 0.7; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div><h1 class="h3 mb-0">{{ title }}</h1></div>
        <a href="{% url 'finance:payment_list' %}" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-2"></i>Back</a>
    </div>

    <div class="row justify-content-center">
        <div class="col-md-8">
            {% if selected_invoice %}
            <div class="alert alert-info shadow-sm mb-4 border-start border-info border-4">
                <i class="fas fa-file-invoice me-2"></i>Recording payment for <strong>{{ selected_invoice.invoice_number }}</strong>
                <br><small class="ms-4 text-dark">{{ selected_invoice.student.get_full_name }} &bull; Current Balance: <strong>{{ selected_invoice.balance|floatformat:0 }} XAF</strong></small>
            </div>
            {% endif %}

            <div class="card shadow border-0">
                <div class="card-header py-3 bg-success text-white">
                    <h6 class="m-0 fw-bold"><i class="fas fa-money-bill-wave me-2"></i>New Transaction Details</h6>
                </div>
                <div class="card-body p-4">
                    <form method="post" id="paymentForm">
                        {% csrf_token %}
                        <!-- Hidden token to prevent duplicate submissions -->
                        <input type="hidden" name="submit_token" value="{{ submit_token }}">
                        
                        {% if form.non_field_errors %}
                            <div class="alert alert-danger">
                                {% for error in form.non_field_errors %}
                                    {{ error }}
                                {% endfor %}
                            </div>
                        {% endif %}

                        <div class="mb-4">
                            <label class="form-label fw-bold">Select Invoice <span class="text-danger">*</span></label>
                            {{ form.invoice }}
                            {% if form.invoice.errors %}
                                <div class="text-danger small">{{ form.invoice.errors }}</div>
                            {% endif %}
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Amount to Pay (XAF) <span class="text-danger">*</span></label>
                                {{ form.amount }}
                                {% if form.amount.errors %}
                                    <div class="text-danger small">{{ form.amount.errors }}</div>
                                {% endif %}
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Date of Payment <span class="text-danger">*</span></label>
                                {{ form.payment_date }}
                                {% if form.payment_date.errors %}
                                    <div class="text-danger small">{{ form.payment_date.errors }}</div>
                                {% endif %}
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Payment Method <span class="text-danger">*</span></label>
                                {{ form.payment_method }}
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Status</label>
                                {{ form.status }}
                            </div>
                        </div>

                        <div id="mobilemoneyFields" class="row mb-3 p-3 bg-light rounded-3 mx-0" style="display:none;">
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Provider</label>
                                {{ form.mobile_money_provider }}
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Phone Number</label>
                                {{ form.mobile_money_number }}
                            </div>
                        </div>

                        <div id="bankFields" class="row mb-3 p-3 bg-light rounded-3 mx-0" style="display:none;">
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Bank Name</label>
                                {{ form.bank_name }}
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small">Cheque/Ref Number</label>
                                {{ form.cheque_number }}
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Transaction Reference ID</label>
                            {{ form.transaction_id }}
                            <small class="text-muted d-block">Optional - helps prevent duplicate payments</small>
                            {% if form.transaction_id.errors %}
                                <div class="text-danger small">{{ form.transaction_id.errors }}</div>
                            {% endif %}
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Internal Notes</label>
                            {{ form.notes }}
                        </div>

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                            <a href="{% url 'finance:payment_list' %}" class="btn btn-light px-4">Cancel</a>
                            <button type="submit" id="submitBtn" class="btn btn-success px-5 fw-bold">
                                <i class="fas fa-check-circle me-2"></i>Record Payment
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('paymentForm');
    const submitBtn = document.getElementById('submitBtn');
    let isSubmitting = false;
    
    if (!form) return;
    
    // Single submission protection
    form.addEventListener('submit', function(e) {
        if (isSubmitting) {
            e.preventDefault();
            return false;
        }
        
        isSubmitting = true;
        
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
        }
        
        return true;
    });
    
    // TomSelect for invoice dropdown
    const invoiceSelect = document.querySelector('select[name="invoice"]');
    if (invoiceSelect) {
        new TomSelect(invoiceSelect, {
            create: false,
            placeholder: "Search by student name or invoice number...",
            maxOptions: 100,
            sortField: { field: "text", direction: "asc" }
        });
    }
    
    // Bootstrap styling
    document.querySelectorAll('input:not(.form-check-input), select:not([name="invoice"]), textarea').forEach(function(el) {
        el.classList.add(el.tagName === 'SELECT' ? 'form-select' : 'form-control');
    });
    
    // Dynamic field toggling
    const methodSelect = document.querySelector('[name="payment_method"]');
    const mobileMoneyDiv = document.getElementById('mobilemoneyFields');
    const bankDiv = document.getElementById('bankFields');
    
    function toggleFields() {
        if (!methodSelect) return;
        const value = methodSelect.value;
        
        if (mobileMoneyDiv) {
            mobileMoneyDiv.style.display = value === 'mobile_money' ? 'flex' : 'none';
        }
        if (bankDiv) {
            bankDiv.style.display = (value === 'bank_transfer' || value === 'cheque') ? 'flex' : 'none';
        }
    }
    
    if (methodSelect) {
        methodSelect.addEventListener('change', toggleFields);
        toggleFields();
    }
});
</script>
{% endblock %}
{% endblock %}