{% extends 'school/base.html.twig' %}

{% block title %}{{ title }} | SALSABIL Madrassas{% endblock %}

{% block content %}
    <style>
        .payment-form-shell{width:100%;max-width:none}
        .payment-form-shell .admin-page-header{width:100%}
        .payment-form-shell .admin-card{width:100%}
        .payment-form-grid{display:grid;grid-template-columns:repeat(4,minmax(180px,1fr));gap:1rem;align-items:start}
        .payment-form-grid .form-row-full{grid-column:1/-1}
        .payment-form-grid .form-row-wide{grid-column:span 2}
        .payment-form-shell label{font-weight:700;color:#183835;margin-bottom:.35rem}
        .payment-form-shell input,.payment-form-shell select,.payment-form-shell textarea{width:100%;border:1px solid rgba(15,92,69,.16);border-radius:12px;padding:.78rem .9rem;background:#fff}
        .payment-form-shell input:focus,.payment-form-shell select:focus,.payment-form-shell textarea:focus{border-color:#5b3674;box-shadow:0 0 0 4px rgba(91,54,116,.1);outline:none}
        .payment-form-actions{display:flex;gap:.75rem;flex-wrap:wrap;justify-content:flex-end;margin-top:1.2rem}
        .payment-locked{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:1rem;border:1px solid rgba(15,92,69,.12);border-radius:16px;background:#f8fbfa;margin-bottom:1rem}
        .payment-locked strong{display:block;color:#102033}
        .payment-locked small{color:#64748b}
        .payment-year-hint{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.85rem 1rem;border:1px solid rgba(91,54,116,.14);border-radius:14px;background:#faf7fc;color:#563568;margin-bottom:1rem}
        .payment-year-hint strong{display:block;color:#3d264d}
        .payment-year-hint span{font-size:.9rem;color:#77598a}
        .payment-form-shell select.is-enhanced-select{position:absolute!important;width:1px!important;height:1px!important;opacity:0!important;pointer-events:none!important}
        .student-combobox{position:relative}
        .student-combobox-input{padding-right:2.65rem!important}
        .student-combobox-menu{position:absolute;z-index:30;left:0;right:0;top:calc(100% + .35rem);max-height:280px;overflow:auto;border:1px solid rgba(91,54,116,.16);border-radius:14px;background:#fff;box-shadow:0 18px 45px rgba(16,32,51,.14);padding:.35rem;display:none}
        .student-combobox.is-open .student-combobox-menu{display:block}
        .student-combobox-option{display:block;width:100%;border:0;background:transparent;text-align:left;padding:.78rem .85rem;border-radius:10px;color:#183835;font-weight:650;cursor:pointer}
        .student-combobox-option:hover,.student-combobox-option.is-selected{background:#f5eff8;color:#4a2e5f}
        .student-combobox-empty{padding:.85rem;color:#64748b}
        @media (max-width:1200px){
            .payment-form-grid{grid-template-columns:repeat(2,minmax(220px,1fr))}
        }
        @media (max-width:700px){
            .payment-form-grid{grid-template-columns:1fr}
            .payment-form-grid .form-row-wide{grid-column:1/-1}
            .payment-year-hint{align-items:flex-start;flex-direction:column}
        }
    </style>
    <div class="admin-page-stack payment-form-shell">
        <section class="admin-page-header">
            <div>
                <p class="admin-eyebrow">PAIEMENTS</p>
                <h1 class="admin-page-title">{{ title }}</h1>
                <p>Le montant reçu sera réparti automatiquement sur les échéances ouvertes de l’étudiant.</p>
            </div>
        </section>

        <section class="admin-card">
            <div class="payment-year-hint">
                <div>
                    <strong>{{ paymentYear ? 'Paiement de l’année en cours : ' ~ paymentYear.libelle : 'Paiement sans année scolaire active' }}</strong>
                    <span>{{ paymentYear ? 'Les étudiants proposés sont filtrés sur cette année scolaire.' : 'Aucune année active n’a été trouvée pour filtrer automatiquement.' }}</span>
                </div>
                <a class="admin-text-link" href="{{ lockedStudent ? path('school_etudiant_paiement_new', {id: lockedStudent.id}) : path('school_paiement_new') }}">Revenir à l’année en cours</a>
            </div>

            {% if lockedStudent %}
                <div class="payment-locked">
                    <div>
                        <strong>{{ lockedStudent.nomComplet }}</strong>
                        <small>{{ lockedStudent.matricule ?: 'Sans matricule' }} · Étudiant prérempli</small>
                    </div>
                    <a class="admin-text-link" href="{{ path('school_etudiant_finance', {id: lockedStudent.id}) }}">Voir sa fiche financière</a>
                </div>
            {% endif %}

            {{ form_start(form) }}
                <div class="payment-form-grid">
                    {% if form.etudiant is defined %}
                        <div class="form-row-wide">{{ form_row(form.etudiant) }}</div>
                    {% endif %}
                    <div>{{ form_row(form.anneeScolaire) }}</div>
                    <div>{{ form_row(form.datePaiement) }}</div>
                    <div>{{ form_row(form.modePaiement) }}</div>
                    <div>{{ form_row(form.reference) }}</div>
                    <div>{{ form_row(form.montantTotal) }}</div>
                    <div class="form-row-full">{{ form_row(form.observation) }}</div>
                </div>
                <div class="payment-form-actions">
                    <a class="admin-btn admin-btn-light" href="{{ lockedStudent ? path('school_etudiant_finance', {id: lockedStudent.id}) : path('school_paiement_index') }}">Annuler</a>
                    <button class="admin-btn admin-btn-primary" type="submit">Enregistrer le paiement</button>
                </div>
            {{ form_end(form) }}
        </section>
    </div>

    <script>
        (() => {
            const enhanceStudentSelect = (select) => {
                if (!select || select.dataset.enhanced === '1') {
                    return;
                }

                select.dataset.enhanced = '1';
                select.classList.add('is-enhanced-select');

                const wrapper = document.createElement('div');
                wrapper.className = 'student-combobox';

                const input = document.createElement('input');
                input.type = 'search';
                input.autocomplete = 'off';
                input.className = 'student-combobox-input';
                input.placeholder = select.dataset.searchPlaceholder || 'Rechercher un étudiant';

                const menu = document.createElement('div');
                menu.className = 'student-combobox-menu';

                select.parentNode.insertBefore(wrapper, select.nextSibling);
                wrapper.appendChild(input);
                wrapper.appendChild(menu);

                const options = Array.from(select.options)
                    .filter((option) => option.value !== '')
                    .map((option) => ({ value: option.value, label: option.textContent.trim() }));

                const selectedOption = select.selectedOptions[0];
                if (selectedOption && selectedOption.value !== '') {
                    input.value = selectedOption.textContent.trim();
                }

                const render = () => {
                    const query = input.value.trim().toLowerCase();
                    const matches = options.filter((option) => option.label.toLowerCase().includes(query)).slice(0, 30);
                    menu.innerHTML = '';

                    if (matches.length === 0) {
                        const empty = document.createElement('div');
                        empty.className = 'student-combobox-empty';
                        empty.textContent = 'Aucun étudiant trouvé pour cette année.';
                        menu.appendChild(empty);
                        return;
                    }

                    matches.forEach((option) => {
                        const button = document.createElement('button');
                        button.type = 'button';
                        button.className = 'student-combobox-option';
                        if (option.value === select.value) {
                            button.classList.add('is-selected');
                        }
                        button.textContent = option.label;
                        button.addEventListener('click', () => {
                            select.value = option.value;
                            input.value = option.label;
                            wrapper.classList.remove('is-open');
                            select.dispatchEvent(new Event('change', { bubbles: true }));
                        });
                        menu.appendChild(button);
                    });
                };

                input.addEventListener('focus', () => {
                    render();
                    wrapper.classList.add('is-open');
                });
                input.addEventListener('input', () => {
                    render();
                    wrapper.classList.add('is-open');
                });
                input.addEventListener('keydown', (event) => {
                    if (event.key !== 'Enter') {
                        return;
                    }
                    const first = menu.querySelector('.student-combobox-option');
                    if (first) {
                        event.preventDefault();
                        first.click();
                    }
                });

                document.addEventListener('click', (event) => {
                    if (!wrapper.contains(event.target)) {
                        wrapper.classList.remove('is-open');
                    }
                });
            };

            document.querySelectorAll('.js-student-search-select').forEach(enhanceStudentSelect);

            const yearSelect = document.querySelector('[data-payment-year-select="1"]');
            if (yearSelect) {
                yearSelect.addEventListener('change', () => {
                    const url = new URL(window.location.href);
                    if (yearSelect.value) {
                        url.searchParams.set('annee', yearSelect.value);
                    } else {
                        url.searchParams.delete('annee');
                    }
                    window.location.href = url.toString();
                });
            }
        })();
    </script>
{% endblock %}
