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

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

{% block content %}
    {% set totalDu = summary.totalDu + 0 %}
    {% set totalPaye = summary.totalPaye + 0 %}
    {% set reste = summary.reste + 0 %}
    {% set solde = cashSummary.solde + 0 %}
    {% set collectionRate = totalDu > 0 ? ((totalPaye / totalDu) * 100)|round(0, 'floor') : 0 %}

    <style>
        .finance-home{display:grid;gap:1.15rem}
        .finance-actions{display:flex;gap:.75rem;flex-wrap:wrap;justify-content:flex-end}
        .finance-hero{display:grid;grid-template-columns:minmax(0,1.4fr) minmax(310px,.75fr);gap:1rem;align-items:stretch}
        .finance-balance-card{position:relative;overflow:hidden;border-radius:18px;padding:1.35rem;background:linear-gradient(135deg,var(--admin-primary),var(--admin-primary-strong));color:#fff;box-shadow:0 22px 50px color-mix(in srgb,var(--admin-primary) 22%,transparent)}
        .finance-balance-card:after{content:"";position:absolute;inset:auto -80px -120px auto;width:260px;height:260px;border-radius:50%;background:rgba(255,255,255,.08)}
        .finance-balance-label{font-size:.78rem;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:rgba(255,255,255,.7)}
        .finance-balance-value{display:block;margin:.5rem 0 .35rem;font-size:clamp(2rem,4vw,3.6rem);font-weight:900;line-height:1}
        .finance-balance-card p{max-width:620px;margin:0;color:rgba(255,255,255,.78)}
        .finance-balance-mini{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem;margin-top:1.2rem;max-width:620px}
        .finance-balance-mini div{border:1px solid rgba(255,255,255,.14);border-radius:14px;padding:.8rem;background:rgba(255,255,255,.07)}
        .finance-balance-mini span{display:block;color:rgba(255,255,255,.68);font-size:.78rem;font-weight:700}
        .finance-balance-mini strong{display:block;margin-top:.2rem;font-size:1.05rem}
        .finance-next-card{border:1px solid color-mix(in srgb,var(--admin-primary) 16%,transparent);border-radius:18px;padding:1.1rem;background:#fff;box-shadow:0 18px 44px rgba(16,32,51,.08)}
        .finance-next-card h2{margin:0;color:#102033;font-size:1.15rem}
        .finance-next-card p{margin:.3rem 0 1rem;color:#64748b}
        .finance-next-list{display:grid;gap:.65rem}
        .finance-next-link{display:flex;align-items:center;gap:.75rem;padding:.82rem;border:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:14px;background:#fff;color:#102033;text-decoration:none;transition:.18s ease}
        .finance-next-link:hover{transform:translateY(-1px);border-color:color-mix(in srgb,var(--admin-primary) 28%,transparent);box-shadow:0 14px 26px rgba(16,32,51,.08)}
        .finance-next-link .material-symbols-outlined{display:grid;place-items:center;min-width:36px;height:36px;border-radius:12px;background:color-mix(in srgb,var(--admin-primary) 10%,#fff);color:var(--admin-primary)}
        .finance-next-link strong{display:block}
        .finance-next-link small{display:block;color:#64748b}
        .finance-section-title{display:flex;align-items:flex-end;justify-content:space-between;gap:1rem;margin-top:.2rem}
        .finance-section-title h2{margin:0;font-size:1.25rem;color:#102033}
        .finance-section-title p{margin:.25rem 0 0;color:#64748b}
        .finance-health-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1rem}
        .finance-health-card{border:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:18px;padding:1rem;background:#fff;box-shadow:0 14px 34px rgba(16,32,51,.06)}
        .finance-health-card.is-warning{border-color:rgba(180,83,9,.2);background:#fffaf2}
        .finance-health-card.is-danger{border-color:rgba(159,18,57,.18);background:#fff7f8}
        .finance-health-card span{font-size:.76rem;font-weight:800;text-transform:uppercase;color:#64748b}
        .finance-health-card strong{display:block;margin:.35rem 0;font-size:1.55rem;color:#102033}
        .finance-health-card p{margin:0;color:#64748b}
        .finance-progress{height:10px;border-radius:999px;background:color-mix(in srgb,var(--admin-primary) 12%,#fff);overflow:hidden;margin-top:.8rem}
        .finance-progress i{display:block;height:100%;width:var(--rate);border-radius:inherit;background:var(--admin-primary)}
        .finance-main-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:1rem;align-items:start}
        .finance-table{width:100%;border-collapse:separate;border-spacing:0 .55rem}
        .finance-table th{font-size:.72rem;text-transform:uppercase;color:#64748b;text-align:left;padding:.35rem .75rem}
        .finance-table td{background:#fff;padding:.85rem .75rem;border-top:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-bottom:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);vertical-align:middle}
        .finance-table td:first-child{border-left:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:12px 0 0 12px}
        .finance-table td:last-child{border-right:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:0 12px 12px 0;text-align:right}
        .finance-person{display:flex;flex-direction:column;gap:.15rem}
        .finance-person strong{color:#102033}
        .finance-person small{color:#64748b}
        .finance-amount{font-weight:900;color:#102033;white-space:nowrap}
        .finance-amount.is-positive{color:var(--admin-primary)}
        .finance-amount.is-negative{color:#9f1239}
        .finance-empty{padding:1rem;border:1px dashed color-mix(in srgb,var(--admin-primary) 24%,transparent);border-radius:14px;background:color-mix(in srgb,var(--admin-primary) 4%,#fff);color:#64748b}
        .finance-feed{display:grid;gap:.7rem}
        .finance-feed-item{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:.85rem;border:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:14px;background:#fff}
        .finance-feed-item div{min-width:0}
        .finance-feed-item strong{display:block;color:#102033;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .finance-feed-item small{display:block;color:#64748b}
        .finance-settings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}
        .finance-settings-card{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:1rem;border:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:16px;background:#fff;text-decoration:none;color:#102033}
        .finance-settings-card p{margin:.2rem 0 0;color:#64748b}
        .finance-settings-card .material-symbols-outlined{color:var(--admin-primary)}
        .finance-details{border:1px solid color-mix(in srgb,var(--admin-primary) 12%,transparent);border-radius:18px;background:#fff;overflow:hidden}
        .finance-details summary{cursor:pointer;display:flex;justify-content:space-between;gap:1rem;padding:1rem 1.1rem;font-weight:850;color:#102033}
        .finance-details-body{padding:0 1rem 1rem}
        @media (max-width:1100px){
            .finance-hero,.finance-main-grid{grid-template-columns:1fr}
            .finance-health-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
        }
        @media (max-width:720px){
            .finance-actions,.finance-section-title{align-items:stretch;flex-direction:column}
            .finance-actions .admin-btn{justify-content:center}
            .finance-balance-mini,.finance-health-grid,.finance-settings{grid-template-columns:1fr}
            .finance-table{display:block;overflow-x:auto;white-space:nowrap}
        }
    </style>

    <div class="admin-page-stack finance-home">
        <section class="admin-page-header">
            <div>
                <p class="admin-eyebrow">FINANCES</p>
                <h1 class="admin-page-title">Caisse et paiements</h1>
                <p>Une vue simple pour encaisser, suivre les impayés et contrôler les sorties de {{ ecole.nom }}.</p>
            </div>
            <div class="finance-actions">
                <a class="admin-btn admin-btn-primary" href="{{ path('school_paiement_new') }}">Nouveau paiement</a>
                <a class="admin-btn admin-btn-light" href="{{ path('school_depense_new') }}">Nouvelle dépense</a>
            </div>
        </section>

        <section class="finance-hero">
            <article class="finance-balance-card">
                <span class="finance-balance-label">Solde disponible en caisse</span>
                <strong class="finance-balance-value">{{ solde|number_format(0, ',', ' ') }} FCFA</strong>
                <p>
                    Ce montant correspond aux entrées validées moins les sorties validées.
                    Il donne l’état rapide de la caisse de la madrassa.
                </p>
                <div class="finance-balance-mini">
                    <div>
                        <span>Entrées encaissées</span>
                        <strong>{{ cashSummary.totalEntrees|number_format(0, ',', ' ') }} FCFA</strong>
                    </div>
                    <div>
                        <span>Sorties enregistrées</span>
                        <strong>{{ cashSummary.totalSorties|number_format(0, ',', ' ') }} FCFA</strong>
                    </div>
                </div>
            </article>

            <aside class="finance-next-card">
                <h2>Que voulez-vous faire ?</h2>
                <p>Les actions les plus courantes sont ici.</p>
                <div class="finance-next-list">
                    <a class="finance-next-link" href="{{ path('school_paiement_new') }}">
                        <span class="material-symbols-outlined">payments</span>
                        <span><strong>Encaisser un étudiant</strong><small>Saisir un paiement reçu</small></span>
                    </a>
                    <a class="finance-next-link" href="{{ path('school_depense_new') }}">
                        <span class="material-symbols-outlined">receipt_long</span>
                        <span><strong>Ajouter une dépense</strong><small>Internet, enseignant, transport...</small></span>
                    </a>
                    <a class="finance-next-link" href="{{ path('school_paiement_index') }}">
                        <span class="material-symbols-outlined">history</span>
                        <span><strong>Consulter les paiements</strong><small>Retrouver un reçu ou un encaissement</small></span>
                    </a>
                </div>
            </aside>
        </section>

        <section>
            <div class="finance-section-title">
                <div>
                    <h2>À surveiller</h2>
                    <p>Les chiffres importants pour agir rapidement.</p>
                </div>
                <a class="admin-text-link" href="{{ path('school_paiement_index') }}">Voir tous les encaissements</a>
            </div>
            <div class="finance-health-grid">
                <article class="finance-health-card {{ reste > 0 ? 'is-warning' : '' }}">
                    <span>Reste à encaisser</span>
                    <strong>{{ reste|number_format(0, ',', ' ') }} FCFA</strong>
                    <p>{{ summary.nonPayees }} échéance(s) non payée(s).</p>
                </article>
                <article class="finance-health-card {{ summary.enRetard > 0 ? 'is-danger' : '' }}">
                    <span>Échéances en retard</span>
                    <strong>{{ summary.enRetard }}</strong>
                    <p>{{ summary.enRetard > 0 ? 'À traiter en priorité.' : 'Aucun retard signalé.' }}</p>
                </article>
                <article class="finance-health-card">
                    <span>Taux d’encaissement</span>
                    <strong>{{ collectionRate }}%</strong>
                    <p>{{ totalPaye|number_format(0, ',', ' ') }} FCFA encaissés sur {{ totalDu|number_format(0, ',', ' ') }} FCFA.</p>
                    <div class="finance-progress" style="--rate: {{ collectionRate > 100 ? 100 : collectionRate }}%"><i></i></div>
                </article>
            </div>
        </section>

        <section class="finance-main-grid">
            <article class="admin-card">
                <div class="admin-card-head">
                    <div>
                        <h2>Étudiants à relancer</h2>
                        <p>Priorité aux dossiers avec un reste à payer sur l’année en cours.</p>
                    </div>
                    <a class="admin-text-link" href="{{ path('school_etudiant_index') }}">Tous les étudiants</a>
                </div>
                {% if studentsWithDebt is empty %}
                    <div class="finance-empty">Aucun reste à payer calculé pour le moment.</div>
                {% else %}
                    <table class="finance-table">
                        <thead><tr><th>Étudiant</th><th>Statut</th><th>Reste</th><th></th></tr></thead>
                        <tbody>
                        {% for item in studentsWithDebt %}
                            <tr>
                                <td>
                                    <span class="finance-person">
                                        <strong>{{ item.etudiant.nomComplet }}</strong>
                                        <small>{{ item.etudiant.matricule ?: 'Sans matricule' }}</small>
                                    </span>
                                </td>
                                <td>{% include 'components/admin/status_badge.html.twig' with {label: item.summary.statut|replace({'_':' '}), tone: item.summary.statut == 'EN_RETARD' ? 'danger' : 'warning'} only %}</td>
                                <td class="finance-amount">{{ item.summary.reste|number_format(0, ',', ' ') }} FCFA</td>
                                <td><a class="admin-text-link" href="{{ path('school_etudiant_finance', {id: item.etudiant.id}) }}">Ouvrir</a></td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                {% endif %}
            </article>

            <article class="admin-card">
                <div class="admin-card-head">
                    <div>
                        <h2>Activité récente</h2>
                        <p>Derniers mouvements utiles, sans bruit.</p>
                    </div>
                </div>
                <div class="finance-feed">
                    {% for paiement in recentPaiements|slice(0, 3) %}
                        <a class="finance-feed-item" href="{{ path('school_paiement_show', {id: paiement.id}) }}">
                            <div>
                                <strong>{{ paiement.etudiant ? paiement.etudiant.nomComplet : 'Paiement' }}</strong>
                                <small>{{ paiement.datePaiement ? paiement.datePaiement|date('d/m/Y') : '-' }} · Paiement</small>
                            </div>
                            <span class="finance-amount is-positive">+ {{ paiement.montantTotal|number_format(0, ',', ' ') }}</span>
                        </a>
                    {% endfor %}
                    {% for depense in recentDepenses|slice(0, 3) %}
                        <a class="finance-feed-item" href="{{ path('school_depense_show', {id: depense.id}) }}">
                            <div>
                                <strong>{{ depense.categorie ? depense.categorie.libelle : 'Dépense' }}</strong>
                                <small>{{ depense.dateDepense ? depense.dateDepense|date('d/m/Y') : '-' }}{% if depense.beneficiaire %} · {{ depense.beneficiaire }}{% endif %}</small>
                            </div>
                            <span class="finance-amount is-negative">- {{ depense.montant|number_format(0, ',', ' ') }}</span>
                        </a>
                    {% endfor %}
                    {% if recentPaiements is empty and recentDepenses is empty %}
                        <div class="finance-empty">Aucune activité récente.</div>
                    {% endif %}
                </div>
            </article>
        </section>

        <section class="finance-settings">
            <a class="finance-settings-card" href="{{ path('school_finance_type_index') }}">
                <span>
                    <strong>Types de frais</strong>
                    <p>Inscription, mensualité, frais annuels, documents.</p>
                </span>
                <span class="material-symbols-outlined">arrow_forward</span>
            </a>
            <a class="finance-settings-card" href="{{ path('school_finance_regle_index') }}">
                <span>
                    <strong>Règles de frais</strong>
                    <p>Montants par année, section, classe ou programme.</p>
                </span>
                <span class="material-symbols-outlined">arrow_forward</span>
            </a>
        </section>

        <details class="finance-details">
            <summary>
                <span>Journal de caisse et solde par année</span>
                <span class="material-symbols-outlined">expand_more</span>
            </summary>
            <div class="finance-details-body">
                <section class="finance-main-grid">
                    <article>
                        <table class="finance-table">
                            <thead><tr><th>Date</th><th>Type</th><th>Libellé</th><th>Montant</th></tr></thead>
                            <tbody>
                            {% for mouvement in recentMouvements %}
                                <tr>
                                    <td>{{ mouvement.dateMouvement ? mouvement.dateMouvement|date('d/m/Y') : '-' }}</td>
                                    <td>{% include 'components/admin/status_badge.html.twig' with {label: mouvement.type == 'ENTREE' ? 'Entrée' : 'Sortie', tone: mouvement.type == 'ENTREE' ? 'success' : 'warning'} only %}</td>
                                    <td>{{ mouvement.libelle }}</td>
                                    <td class="finance-amount">{{ mouvement.montant|number_format(0, ',', ' ') }} FCFA</td>
                                </tr>
                            {% else %}
                                <tr><td colspan="4">Aucun mouvement de caisse.</td></tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </article>
                    <article>
                        <table class="finance-table">
                            <thead><tr><th>Année</th><th>Entrées</th><th>Sorties</th><th>Solde</th></tr></thead>
                            <tbody>
                            {% for row in yearlyCash %}
                                <tr>
                                    <td><strong>{{ row.annee }}</strong></td>
                                    <td>{{ row.entrees|number_format(0, ',', ' ') }}</td>
                                    <td>{{ row.sorties|number_format(0, ',', ' ') }}</td>
                                    <td class="finance-amount">{{ row.solde|number_format(0, ',', ' ') }} FCFA</td>
                                </tr>
                            {% else %}
                                <tr><td colspan="4">Aucun solde par année disponible.</td></tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </article>
                </section>
            </div>
        </details>
    </div>
{% endblock %}
