{% extends 'gakusei/layout.html' %}


{% block body %}
    <div class="container d-flex justify-content-center align-items-center" style="min-height: 80vh;">
        <div class="bg-white p-4 rounded shadow" style="width: 100%; max-width: 900px;">
            <h1>Formulario de Pago</h1>
m            {% if error_message %}
                <div class="alert alert-danger" role="alert">
                    {{ error_message }}
                </div>
            {% endif %}
            <form method="post">
                {% csrf_token %}
                <div class="form-container">
                    <div class="form-column">
                        <div class="form-group">
                            {{ form.student_name.label_tag }}
                            {{ form.student_name }}
                            <datalist id="student_name_datalist"></datalist>
                        </div>
                        <div class="form-group">
                            {{ form.student_id.label_tag }}
                            {{ form.student_id }}
                            <datalist id="student_id_datalist"></datalist>
                        </div>
                        <div class="form-group">
                            {{ form.clase.label_tag }}
                            {{ form.clase }}
                        </div>
                        <div class="form-group">
                            {{ form.amount.label_tag }}
                            {{ form.amount }}
                        </div>
                        <div class="form-group">
                            {{ form.payment_date.label_tag }}
                            {{ form.payment_date }}
                        </div>
                        <div class="form-group">
                            {{ form.payment_method.label_tag }}
                            {{ form.payment_method }}
                        </div>
                    </div>
                    <div class="form-column">
                        <div class="form-group">
                            {{ form.email.label_tag }}
                            {{ form.email }}
                            <datalist id="student_email_datalist"></datalist>
                        </div>
                        <div class="form-group">
                            {{ form.issued_by.label_tag }}
                            {{ form.issued_by }}
                        </div>
                        <div class="form-group">
                            {{ form.reference_code.label_tag }}
                            {{ form.reference_code }}
                        </div>
                        <div class="form-group">
                            {{ form.payment_concept.label_tag }}
                            {{ form.payment_concept }}
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="id_month">Mes cancelado</label>
                    {{ form.month }}
                </div>
                <button type="submit">Enviar</button>
            </form>
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script>
            document.addEventListener('DOMContentLoaded', function() {
                let estudiantes = [];
                fetch('/estudiantes-autocomplete/')
                    .then(response => response.json())
                    .then(data => {
                        estudiantes = data.results;
                        // Rellenar datalists
                        const nameDatalist = document.getElementById('student_name_datalist');
                        const idDatalist = document.getElementById('student_id_datalist');
                        const emailDatalist = document.getElementById('student_email_datalist');
                        nameDatalist.innerHTML = '';
                        idDatalist.innerHTML = '';
                        emailDatalist.innerHTML = '';
                        estudiantes.forEach(est => {
                            const nameOption = document.createElement('option');
                            nameOption.value = est.full_name;
                            nameDatalist.appendChild(nameOption);
                            const idOption = document.createElement('option');
                            idOption.value = est.cedula;
                            idDatalist.appendChild(idOption);
                            const emailOption = document.createElement('option');
                            emailOption.value = est.email;
                            emailDatalist.appendChild(emailOption);
                        });
                    });

                // Inputs
                const nameInput = document.getElementById('id_student_name');
                const idInput = document.getElementById('id_student_id');
                const emailInput = document.getElementById('id_email');

                function fillFields(est) {
                    if (est) {
                        nameInput.value = est.full_name;
                        idInput.value = est.cedula;
                        emailInput.value = est.email;
                    }
                }

                nameInput.addEventListener('change', function() {
                    const est = estudiantes.find(e => e.full_name === nameInput.value);
                    if (est) {
                        idInput.value = est.cedula;
                        emailInput.value = est.email;
                    }
                });
            });
            $(function() {
                // Cambia los IDs si tus campos tienen otros
                const idInput = $('#id_student_id');
                const nameInput = $('#id_student_name');
                const emailInput = $('#id_email');

                idInput.on('change blur', function() {
                    var cedula = $(this).val();
                    if (cedula) {
                        $.get('/buscar-estudiante/', {cedula: cedula}, function(data) {
                            if (data && data.nombre) {
                                nameInput.val(data.nombre);
                                emailInput.val(data.email);
                            } else {
                                nameInput.val('');
                                emailInput.val('');
                            }
                        });
                    }
                });
            });
            </script>
            <style>
.autocomplete-suggestions {
    border: 1px solid #ccc;
    background: #fff;
    position: absolute;
    z-index: 1000;
    max-height: 200px;
    overflow-y: auto;
    width: 100%;
}
.autocomplete-suggestion {
    padding: 8px;
    cursor: pointer;
}
.autocomplete-suggestion:hover {
    background: #f0f0f0;
}
</style>
<script>
$(function() {
    function setupAutocomplete($input, field) {
        let $suggestionsBox = $('<div class="autocomplete-suggestions"></div>').insertAfter($input).hide();

        $input.on('input', function() {
            let term = $(this).val();
            if (term.length > 0) {
                $.get('/autocomplete-estudiante/', {term: term, field: field}, function(data) {
                    $suggestionsBox.empty();
                    if (data.length > 0) {
                        data.forEach(function(item) {
                            $suggestionsBox.append(
                                $('<div class="autocomplete-suggestion"></div>')
                                    .text(item.cedula_full + ' - ' + item.nombre + ' - ' + item.email)
                                    .data('cedula', item.cedula) // solo número
                                    .data('nombre', item.nombre)
                                    .data('email', item.email)
                            );
                        });
                        $suggestionsBox.show();
                    } else {
                        $suggestionsBox.hide();
                    }
                });
            } else {
                $suggestionsBox.hide();
            }
        });

        $suggestionsBox.on('click', '.autocomplete-suggestion', function() {
            $('#id_student_id').val($(this).data('cedula')).trigger('change');
            $('#id_student_name').val($(this).data('nombre'));
            $('#id_email').val($(this).data('email'));
            $suggestionsBox.hide();
        });

        // Ocultar sugerencias si se hace click fuera
        $(document).on('click', function(e) {
            if (!$(e.target).closest($suggestionsBox).length && !$(e.target).is($input)) {
                $suggestionsBox.hide();
            }
        });
    }

    setupAutocomplete($('#id_student_id'), 'cedula');
    setupAutocomplete($('#id_student_name'), 'nombre');
    setupAutocomplete($('#id_email'), 'email');
});
</script>
        </div>
    </div>

    <div class="container d-flex justify-content-center align-items-center mt-5 mb-5">
        <div class="bg-white p-4 rounded shadow" style="width: 100%; max-width: 1100px;">
            <h2>Historial de Pagos</h2>
            <!-- Dropdown de filtro por letra inicial del estudiante -->
            <div class="mb-3">
                <span>Filtrar por estudiante: </span>
                <div class="btn-group">
                  <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                    {% if request.GET.letra %}{{ request.GET.letra }}{% else %}A-Z{% endif %}
                  </button>
                  <ul class="dropdown-menu">
                    <li><a class="dropdown-item {% if not request.GET.letra %}active{% endif %}" href="?">Todos</a></li>
                    <li><hr class="dropdown-divider"></li>
                    {% for letra in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" %}
                      <li><a class="dropdown-item {% if request.GET.letra == letra %}active{% endif %}" href="?letra={{ letra }}">{{ letra }}</a></li>
                    {% endfor %}
                  </ul>
                </div>
            </div>
            <div style="overflow-x:auto;">
                <table class="table table-striped table-bordered mt-4">
                    <thead class="table-dark">
                        <tr>
                            <th>Fecha</th>
                            <th>Estudiante</th>
                            <th>Cédula</th>
                            <th>Monto</th>
                            <th>Método</th>
                            <th>Referencia</th>
                            <th>Concepto</th>
                            <th>Emitido por</th>
                            <th>Mes</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for pago in historial_pagos %}
                        <tr>
                            <td>{{ pago.payment_date|date:"j \d\e F \d\e Y" }}</td>
                            <td>{{ pago.get_student_name }}</td>
                            <td>{{ pago.get_student_id }}</td>
                            <td>{{ pago.amount }}</td>
                            <td>{{ pago.payment_method }}</td>
                            <td>{{ pago.reference_code }}</td>
                            <td>{{ pago.payment_concept }}</td>
                            <td>{{ pago.issued_by }}</td>
                            <td>{{ pago.month }}</td>
                            <td>
                                <form method="post" action="{% url 'facturapago-delete' pago.id %}" style="display:inline;">
                                    {% csrf_token %}
                                    <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('¿Seguro que deseas eliminar este pago?');">Eliminar</button>
                                </form>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="10" class="text-center">No hay pagos registrados.</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
{% endblock %}
