<?php
use App\Core\Csrf;
use App\Core\Permission;

$denoms = [500, 200, 100, 50, 20, 10, 5, 2, 1, .5, .2, .1, .05, .02, .01];
$cashTotal = array_sum(array_map(static fn(array $register): float => (float)($register['current_balance'] ?? 0), $registers));
$chequesPending = array_filter($cheques, static fn(array $cheque): bool => in_array($cheque['status'] ?? '', ['received', 'pending_deposit'], true));
$chequesTotal = array_sum(array_map(static fn(array $cheque): float => (float)($cheque['amount'] ?? 0), $chequesPending));
?>
<link rel="stylesheet" href="/public/assets/css/cda-accounting-ui-964.css?v=9.6.4">
<main class="accounting-page">
    <section class="cda-hero accounting-hero">
        <div>
            <span class="cda-eyebrow">AXIOM Studio · Comptabilité</span>
            <h2>Trésorerie, caisses et chèques</h2>
            <p>Suivez les espèces, les remises et les chèques depuis un espace unique.</p>
        </div>
        <div class="cda-actionbar">
            <a class="cda-btn cda-btn-secondary" href="/public/facturation">Facturation</a><a class="cda-btn cda-btn-secondary" href="/public/comptabilite/tresorerie/journal">Journal de caisse</a>
            <?php if (Permission::can('treasury.treasurer')): ?>
            <a class="cda-btn cda-btn-primary" href="/public/comptabilite/tresorerie/depot-especes">+ Dépôt d’espèces</a>
            <?php endif; ?>
        </div>
    </section>

    <section class="accounting-kpis" aria-label="Indicateurs de trésorerie">
        <article class="accounting-kpi"><span class="accounting-kpi-icon">€</span><div><small>Espèces en caisse</small><strong><?= number_format($cashTotal, 2, ',', ' ') ?> €</strong></div></article>
        <article class="accounting-kpi"><span class="accounting-kpi-icon">▣</span><div><small>Caisses actives</small><strong><?= count($registers) ?></strong></div></article>
        <article class="accounting-kpi"><span class="accounting-kpi-icon">✉</span><div><small>Chèques à remettre</small><strong><?= count($chequesPending) ?></strong><em><?= number_format($chequesTotal, 2, ',', ' ') ?> €</em></div></article>
        <article class="accounting-kpi"><span class="accounting-kpi-icon">⇄</span><div><small>Remises à accepter</small><strong><?= count($pending) ?></strong></div></article>
    </section>

    <?php if ($registers): ?>
    <section class="cash-card-grid" aria-label="Caisses">
        <?php foreach ($registers as $register): ?>
        <article class="cash-summary-card<?= $register['is_treasurer_cash'] ? ' is-primary' : '' ?>">
            <div class="cash-summary-head">
                <span class="studio-badge"><?= $register['is_treasurer_cash'] ? 'Caisse trésorière' : 'Caisse attribuée' ?></span>
                <span class="cash-summary-code"><?= htmlspecialchars((string)($register['code'] ?? '')) ?></span>
            </div>
            <h3><?= htmlspecialchars((string)$register['name']) ?></h3>
            <strong><?= number_format((float)$register['current_balance'], 2, ',', ' ') ?> €</strong>
            <small><?= htmlspecialchars(trim(($register['holder_prenom'] ?? '') . ' ' . ($register['holder_nom'] ?? '')) ?: 'Non attribuée') ?></small>
        </article>
        <?php endforeach; ?>
    </section>
    <?php else: ?>
    <section class="cda-panel accounting-empty"><span>▣</span><h3>Aucune caisse configurée</h3><p>Créez la caisse principale de la trésorière pour commencer.</p></section>
    <?php endif; ?>

    <?php if (Permission::can('treasury.cash.manage')): ?>
    <section class="cda-panel accounting-panel client-advance-panel">
        <div class="cda-panel-head"><div><span class="cda-eyebrow">Encaissement avant facturation</span><h3>Saisir une avance client en espèces</h3></div><span class="panel-icon">€</span></div>
        <p class="accounting-help">L’avance crédite immédiatement la caisse et reste disponible sur le compte de l’adhérent jusqu’à son affectation à une facture.</p>
        <form class="accounting-form-grid" method="post" action="/public/comptabilite/tresorerie/avance-client">
            <?= Csrf::field() ?>
            <label>Adhérent<select name="client_id" required><option value="">Rechercher et sélectionner</option><?php foreach ($clients as $client): ?><option value="<?= (int)$client['id'] ?>"><?= htmlspecialchars($client['code_client'].' · '.$client['nom'].' '.$client['prenom']) ?></option><?php endforeach; ?></select></label>
            <label>Caisse encaissante<select name="register_id" required><option value="">Sélectionner la caisse</option><?php foreach ($registers as $register): ?><option value="<?= (int)$register['id'] ?>"><?= htmlspecialchars($register['name']) ?></option><?php endforeach; ?></select></label>
            <label>Date de réception<input type="date" name="received_date" value="<?= date('Y-m-d') ?>" required></label>
            <label>Montant reçu<input type="number" step="0.01" min="0.01" name="amount" placeholder="0,00" required></label>
            <label class="advance-notes">Motif ou observation<input name="notes" placeholder="Ex. avance inscription piano"></label>
            <div class="accounting-form-actions"><button class="cda-btn accounting-btn-primary">Encaisser et créer le reçu</button></div>
        </form>
    </section>
    <?php endif; ?>

    <section class="cda-panel accounting-panel">
        <div class="cda-panel-head"><div><span class="cda-eyebrow">Comptes adhérents</span><h3>Avances à affecter</h3></div><span class="accounting-count"><?= count(array_filter($advances, static fn(array $a): bool => (float)$a['available_amount'] > 0)) ?></span></div>
        <div class="accounting-table-wrap"><table class="accounting-table"><thead><tr><th>Reçu</th><th>Adhérent</th><th>Date</th><th>Reçu</th><th>Disponible</th><th>Affectation</th></tr></thead><tbody>
        <?php if (!$advances): ?><tr><td colspan="6" class="accounting-table-empty">Aucune avance client enregistrée.</td></tr><?php endif; ?>
        <?php foreach ($advances as $advance): ?><tr><td><a target="_blank" href="/public/comptabilite/tresorerie/avance-client/recu?id=<?= (int)$advance['id'] ?>"><strong><?= htmlspecialchars($advance['receipt_number']) ?></strong></a><div class="advance-actions"><form method="post" action="/public/comptabilite/tresorerie/avance-client/email"><?=Csrf::field()?><input type="hidden" name="id" value="<?=$advance['id']?>"><button>Envoyer</button></form><?php if((float)$advance['available_amount']>0&&Permission::can('treasury.treasurer')):?><form method="post" action="/public/comptabilite/tresorerie/avance-client/rembourser" onsubmit="return confirm('Rembourser tout le reliquat disponible ?')"><?=Csrf::field()?><input type="hidden" name="id" value="<?=$advance['id']?>"><input type="hidden" name="reason" value="Remboursement demandé"><button>Rembourser</button></form><?php endif?></div></td><td><?= htmlspecialchars($advance['code_client'].' · '.$advance['nom'].' '.$advance['prenom']) ?></td><td><?= htmlspecialchars($advance['received_date']) ?></td><td><?= number_format((float)$advance['amount'],2,',',' ') ?> €</td><td><strong><?= number_format((float)$advance['available_amount'],2,',',' ') ?> €</strong></td><td><?php if ((float)$advance['available_amount'] > 0 && $advance['open_invoices']): ?><form class="advance-allocation-form" method="post" action="/public/comptabilite/tresorerie/avance-client/affecter"><?= Csrf::field() ?><input type="hidden" name="advance_id" value="<?= (int)$advance['id'] ?>"><select name="invoice_id" required><option value="">Choisir une facture</option><?php foreach($advance['open_invoices'] as $invoice): ?><option value="<?= (int)$invoice['id'] ?>"><?= htmlspecialchars($invoice['document_number']) ?> · reste <?= number_format((float)$invoice['total_amount']-(float)$invoice['paid_amount'],2,',',' ') ?> €</option><?php endforeach; ?></select><input type="number" name="amount" step="0.01" min="0.01" max="<?= htmlspecialchars((string)$advance['available_amount']) ?>" value="<?= htmlspecialchars((string)$advance['available_amount']) ?>" required><button class="cda-btn accounting-btn-primary">Affecter</button></form><?php elseif ((float)$advance['available_amount'] > 0): ?><small>En attente d’une facture</small><?php else: ?><span class="studio-badge"><?=htmlspecialchars($advance['status'])?></span><?php endif; ?></td></tr><?php endforeach; ?>
        </tbody></table></div>
    </section>

    <?php if ($pending && Permission::can('treasury.treasurer')): ?>
    <section class="cda-panel accounting-panel accounting-alert-panel">
        <div class="cda-panel-head"><div><span class="cda-eyebrow">Action requise</span><h3>Remises à accepter</h3></div><span class="accounting-count"><?= count($pending) ?></span></div>
        <div class="accounting-list">
            <?php foreach ($pending as $transfer): ?>
            <div class="accounting-list-row">
                <div><strong><?= htmlspecialchars($transfer['source_name'] . ' → ' . $transfer['target_name']) ?></strong><small>Remise de caisse en attente</small></div>
                <strong><?= number_format((float)$transfer['amount'], 2, ',', ' ') ?> €</strong>
                <form method="post" action="/public/comptabilite/tresorerie/remise/accepter"><?= Csrf::field() ?><input type="hidden" name="id" value="<?= (int)$transfer['id'] ?>"><button class="cda-btn accounting-btn-primary">Accepter</button></form>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <div class="accounting-layout">
        <div class="accounting-main-column">
            <section class="cda-panel accounting-panel">
                <div class="cda-panel-head"><div><span class="cda-eyebrow">Mouvement interne</span><h3>Remise à la trésorière</h3></div><span class="panel-icon">⇄</span></div>
                <p class="accounting-help">Transférez les espèces d’une caisse attribuée vers la caisse principale.</p>
                <form class="accounting-form-grid" method="post" action="/public/comptabilite/tresorerie/remise">
                    <?= Csrf::field() ?>
                    <label>Source<select name="source_register_id" required><option value="">Sélectionner une caisse</option><?php foreach ($registers as $register): if (!$register['is_treasurer_cash']): ?><option value="<?= (int)$register['id'] ?>"><?= htmlspecialchars($register['name']) ?> · <?= number_format((float)$register['current_balance'], 2, ',', ' ') ?> €</option><?php endif; endforeach; ?></select></label>
                    <label>Destination<select name="target_register_id" required><option value="">Sélectionner la caisse principale</option><?php foreach ($registers as $register): if ($register['is_treasurer_cash']): ?><option value="<?= (int)$register['id'] ?>"><?= htmlspecialchars($register['name']) ?></option><?php endif; endforeach; ?></select></label>
                    <label>Montant<input type="number" step="0.01" min="0.01" name="amount" placeholder="0,00" required></label>
                    <div class="accounting-form-actions"><button class="cda-btn accounting-btn-primary">Demander la remise</button></div>
                </form>
            </section>

            <section class="cda-panel accounting-panel">
                <div class="cda-panel-head"><div><span class="cda-eyebrow">Rapprochement</span><h3>Contrôle mensuel de caisse</h3></div><span class="panel-icon">✓</span></div>
                <form method="post" action="/public/comptabilite/tresorerie/comptage">
                    <?= Csrf::field() ?>
                    <div class="accounting-form-grid accounting-form-grid-2">
                        <label>Caisse<select name="register_id" required><option value="">Sélectionner une caisse</option><?php foreach ($registers as $register): ?><option value="<?= (int)$register['id'] ?>"><?= htmlspecialchars($register['name']) ?></option><?php endforeach; ?></select></label>
                        <label>Mois contrôlé<input type="month" name="period_month" value="<?= date('Y-m') ?>" required></label>
                    </div>
                    <div class="denomination-head"><strong>Comptage des billets et pièces</strong><small>Indiquez la quantité de chaque valeur.</small></div>
                    <div class="denomination-grid">
                        <?php foreach ($denoms as $denom): ?>
                        <label><span><?= number_format($denom, 2, ',', ' ') ?> €</span><input type="number" min="0" name="quantity[<?= $denom ?>]" value="0"></label>
                        <?php endforeach; ?>
                    </div>
                    <div class="accounting-form-actions"><button class="cda-btn accounting-btn-primary">Enregistrer le comptage</button></div>
                </form>
            </section>
        </div>

        <aside class="accounting-side-column">
            <?php if (Permission::can('treasury.settings')): ?>
            <details class="cda-panel accounting-panel accounting-details">
                <summary><span><span class="cda-eyebrow">Paramétrage</span><strong>Créer une caisse</strong></span><span class="details-plus">+</span></summary>
                <form class="accounting-stack-form" method="post" action="/public/comptabilite/tresorerie/caisse">
                    <?= Csrf::field() ?>
                    <label>Code<input name="code" placeholder="Ex. CAISSE-02" required></label>
                    <label>Nom<input name="name" placeholder="Ex. Caisse accueil" required></label>
                    <label>Détenteur<select name="holder_user_id"><option value="">Non attribuée</option><?php foreach ($users as $person): ?><option value="<?= (int)$person['id'] ?>"><?= htmlspecialchars($person['prenom'] . ' ' . $person['nom']) ?></option><?php endforeach; ?></select></label>
                    <label>Solde initial<input type="number" step="0.01" name="opening_balance" value="0"></label>
                    <label class="accounting-check"><input type="checkbox" name="is_treasurer_cash" value="1"><span>Caisse principale de la trésorière</span></label>
                    <button class="cda-btn accounting-btn-primary">Créer la caisse</button>
                </form>
            </details>
            <?php endif; ?>

            <section class="cda-panel accounting-panel accounting-shortcuts">
                <span class="cda-eyebrow">Accès rapides</span><h3>Comptabilité</h3>
                <a href="/public/facturation"><span>€</span><div><strong>Facturation</strong><small>Factures, avoirs et règlements</small></div><b>›</b></a>
                <?php if (Permission::can('treasury.treasurer')): ?><a href="/public/comptabilite/tresorerie/depot-especes"><span>⇢</span><div><strong>Dépôt d’espèces</strong><small>Préparer l’écriture CM</small></div><b>›</b></a><?php endif; ?>
                <?php if (Permission::can('facturation.settings')): ?><a href="/public/facturation/parametres"><span>⚙</span><div><strong>Paramètres</strong><small>Comptes et journaux</small></div><b>›</b></a><?php endif; ?>
            </section>
        </aside>
    </div>

    <section class="cda-panel accounting-panel">
        <div class="cda-panel-head"><div><span class="cda-eyebrow">Validation trésorière</span><h3>Derniers contrôles de caisse</h3></div><span class="accounting-count"><?=count($cashCounts)?></span></div>
        <div class="accounting-table-wrap"><table class="accounting-table"><thead><tr><th>Mois</th><th>Caisse</th><th>Théorique</th><th>Compté</th><th>Écart</th><th>État</th><th></th></tr></thead><tbody><?php if(!$cashCounts):?><tr><td colspan="7" class="accounting-table-empty">Aucun contrôle enregistré.</td></tr><?php endif?><?php foreach($cashCounts as $count):?><tr><td><?=htmlspecialchars($count['period_month'])?></td><td><?=htmlspecialchars($count['register_name'])?></td><td><?=number_format((float)$count['theoretical_amount'],2,',',' ')?> €</td><td><?=number_format((float)$count['counted_amount'],2,',',' ')?> €</td><td class="<?=$count['difference_amount']!=0?'count-difference':''?>"><?=number_format((float)$count['difference_amount'],2,',',' ')?> €</td><td><span class="studio-badge"><?=htmlspecialchars($count['status'])?></span></td><td><?php if($count['status']==='draft'&&Permission::can('treasury.treasurer')):?><form method="post" action="/public/comptabilite/tresorerie/comptage/valider"><?=Csrf::field()?><input type="hidden" name="id" value="<?=$count['id']?>"><button class="cda-btn accounting-btn-primary">Valider</button></form><?php endif?></td></tr><?php endforeach?></tbody></table></div>
    </section>

    <section class="cda-panel accounting-panel">
        <div class="cda-panel-head"><div><span class="cda-eyebrow">Encaissements</span><h3>Journal des chèques</h3></div><span class="accounting-count"><?= count($cheques) ?></span></div>
        <form method="post" action="/public/comptabilite/tresorerie/cheques/bordereau">
            <?= Csrf::field() ?>
            <div class="accounting-table-wrap"><table class="accounting-table"><thead><tr><th class="check-col"></th><th>Chèque</th><th>Adhérent</th><th>Facture</th><th>État</th><th class="amount-col">Montant</th></tr></thead><tbody>
            <?php if (!$cheques): ?><tr><td colspan="6" class="accounting-table-empty">Aucun chèque enregistré.</td></tr><?php endif; ?>
            <?php foreach ($cheques as $cheque): ?><tr><td><?php if (in_array($cheque['status'], ['received', 'pending_deposit'], true)): ?><input type="checkbox" name="cheque_ids[]" value="<?= (int)$cheque['id'] ?>"><?php endif; ?></td><td><strong><?= htmlspecialchars($cheque['cheque_number']) ?></strong></td><td><?= htmlspecialchars($cheque['prenom'] . ' ' . $cheque['nom']) ?></td><td><?= htmlspecialchars($cheque['document_number']) ?></td><td><span class="studio-badge"><?= htmlspecialchars($cheque['status']) ?></span></td><td class="amount-col"><strong><?= number_format((float)$cheque['amount'], 2, ',', ' ') ?> €</strong></td></tr><?php endforeach; ?>
            </tbody></table></div>
            <?php if ($chequesPending): ?><div class="accounting-form-actions"><button class="cda-btn accounting-btn-primary">Créer le bordereau sélectionné</button></div><?php endif; ?>
        </form>
    </section>

    <section class="cda-panel accounting-panel">
        <div class="cda-panel-head"><div><span class="cda-eyebrow">Banque</span><h3>Bordereaux de chèques</h3></div><span class="accounting-count"><?= count($deposits) ?></span></div>
        <div class="accounting-list">
            <?php if (!$deposits): ?><div class="accounting-table-empty">Aucun bordereau créé.</div><?php endif; ?>
            <?php foreach ($deposits as $deposit): ?><div class="accounting-list-row"><div><strong><?= htmlspecialchars($deposit['deposit_number']) ?></strong><small><span class="studio-badge"><?= htmlspecialchars($deposit['status']) ?></span></small></div><strong><?= number_format((float)$deposit['total_amount'], 2, ',', ' ') ?> €</strong><?php if ($deposit['status'] === 'draft'): ?><form method="post" action="/public/comptabilite/tresorerie/cheques/deposer"><?= Csrf::field() ?><input type="hidden" name="id" value="<?= (int)$deposit['id'] ?>"><button class="cda-btn accounting-btn-primary">Remettre sur CM</button></form><?php endif; ?></div><?php endforeach; ?>
        </div>
    </section>
</main>
