<?php use App\Core\Csrf;use App\Core\Permission; ?>
<link rel="stylesheet" href="/public/assets/css/cda-accounting-ui-964.css?v=9.6.4">
<link rel="stylesheet" href="/public/assets/css/cda-accounting-entries-975.css?v=9.6.75">
<?php if($invoice['status']==='draft'):?><div style="display:flex;gap:.6rem;justify-content:flex-end;flex-wrap:wrap;margin:1rem"><a class="btn secondary" href="/public/facturation/modifier?id=<?=(int)$invoice['id']?>">Modifier le brouillon</a><?php if(Permission::can('facturation.archive')):?><form method="post" action="/public/facturation/brouillon/supprimer" onsubmit="return confirm('Supprimer ce brouillon ? Ses lignes retourneront dans À facturer.');"><?=Csrf::field()?><input type="hidden" name="id" value="<?=(int)$invoice['id']?>"><button class="btn danger">Supprimer le brouillon</button></form><?php endif?></div><?php endif?>
<link rel="stylesheet" href="/public/assets/css/cda-billing-959.css"><main class="billing"><header class="billing-head"><div><a class="back" href="/public/facturation">← Retour</a><h1><?=htmlspecialchars($invoice['document_number']?:'Brouillon #'.$invoice['id'])?></h1><p><?=htmlspecialchars($invoice['nom'].' '.$invoice['prenom'])?> · compte client <strong><?=htmlspecialchars($invoice['client_account'])?></strong></p></div><div><a class="btn secondary" target="_blank" href="/public/facturation/imprimer?id=<?=$invoice['id']?>">Facture Studio / PDF</a> <a class="btn secondary" href="/public/facturation/ecritures.csv?id=<?=$invoice['id']?>">CSV comptable</a> <a class="btn secondary" href="/public/facturation/echeances">Rappels</a></div></header>
<div class="table-wrap"><table><tr><th>Libellé</th><th>Activité</th><th>Période</th><th class="num">Brut</th><th class="num">Réduction</th><th class="num">Net</th></tr><?php foreach($invoice['lines'] as $l):?><tr><td><?=htmlspecialchars($l['description'])?></td><td><?=htmlspecialchars(trim(($l['pole_code']??'').' '.($l['project_code']??'')))?></td><td><?=htmlspecialchars(($l['service_start']?:'—').' → '.($l['service_end']?:'—'))?></td><td class="num"><?=number_format((float)$l['gross_amount'],2,',',' ')?> €</td><td class="num"><?=number_format((float)$l['discount_amount'],2,',',' ')?> €</td><td class="num"><?=number_format((float)$l['net_amount'],2,',',' ')?> €</td></tr><?php endforeach?><tr><th colspan="5">Total final</th><th class="num"><?=number_format((float)$invoice['total_amount'],2,',',' ')?> €</th></tr></table></div>
<section class="actions"><?php if($invoice['status']==='draft'&&Permission::can('facturation.create')):?><form method="post" action="/public/facturation/emettre"><input type="hidden" name="_csrf" value="<?=Csrf::token()?>"><input type="hidden" name="id" value="<?=$invoice['id']?>"><button class="btn">Émettre et numéroter</button></form><?php endif?><?php if($invoice['status']!=='draft'):?><form method="post" action="/public/facturation/email"><input type="hidden" name="_csrf" value="<?=Csrf::token()?>"><input type="hidden" name="id" value="<?=$invoice['id']?>"><button class="btn secondary">Envoyer par e-mail</button></form><?php endif?></section>
<?php $availableAdvances=array_filter($clientAdvances??[],static fn(array $a):bool=>(float)$a['available_amount']>0); ?>
<?php if($invoice['document_type']==='invoice'&&$invoice['status']!=='draft'&&$availableAdvances&&Permission::can('facturation.payments')):?><section class="panel invoice-advances"><h2>Avances disponibles pour cet adhérent</h2><p>Utilisez tout ou partie d’une avance sans créer un nouvel encaissement en caisse.</p><?php foreach($availableAdvances as $advance):?><form class="advance-use-row" method="post" action="/public/comptabilite/tresorerie/avance-client/affecter"><input type="hidden" name="_csrf" value="<?=Csrf::token()?>"><input type="hidden" name="advance_id" value="<?=$advance['id']?>"><input type="hidden" name="invoice_id" value="<?=$invoice['id']?>"><input type="hidden" name="return_invoice" value="1"><div><strong><?=htmlspecialchars($advance['receipt_number'])?></strong><small>Reçue le <?=htmlspecialchars($advance['received_date'])?> · <?=htmlspecialchars($advance['register_name'])?></small></div><span>Disponible : <strong><?=number_format((float)$advance['available_amount'],2,',',' ')?> €</strong></span><label>Montant à utiliser<input type="number" name="amount" min="0.01" step="0.01" max="<?=htmlspecialchars((string)min((float)$advance['available_amount'],max(0,(float)$invoice['total_amount']-(float)$invoice['paid_amount'])))?>" value="<?=htmlspecialchars((string)min((float)$advance['available_amount'],max(0,(float)$invoice['total_amount']-(float)$invoice['paid_amount'])))?>" required></label><button class="btn">Affecter à cette facture</button></form><?php endforeach?></section><?php endif?>
<?php if($invoice['document_type']==='invoice'&&Permission::can('facturation.payments')):?><section class="panel"><h2>Règlements</h2><form class="grid" method="post" action="/public/facturation/reglement"><input type="hidden" name="_csrf" value="<?=Csrf::token()?>"><input type="hidden" name="id" value="<?=$invoice['id']?>"><label>Date<input type="date" name="payment_date" value="<?=date('Y-m-d')?>"></label><label>Montant<input type="number" step="0.01" name="amount" required></label><label>Mode<select name="method"><option>Carte bancaire</option><option>Chèque</option><option>Espèces</option><option>Virement</option><option>Prélèvement</option></select></label><label>Référence / numéro chèque<input name="reference"></label><button class="btn">Ajouter</button></form><?php foreach($invoice['payments'] as $p):?><p><?=htmlspecialchars($p['payment_date'].' · '.$p['payment_method'])?> — <?=number_format((float)$p['amount'],2,',',' ')?> € <?php if(stripos((string)$p['payment_method'],'esp')!==false):?>· <a target="_blank" href="/public/facturation/recu-especes?payment_id=<?=$p['id']?>">Imprimer / PDF</a> <form style="display:inline" method="post" action="/public/facturation/recu-especes/email"><input type="hidden" name="_csrf" value="<?=Csrf::token()?>"><input type="hidden" name="payment_id" value="<?=$p['id']?>"><input type="hidden" name="invoice_id" value="<?=$invoice['id']?>"><button>Envoyer le reçu par e-mail</button></form><?php endif?></p><?php endforeach?></section><?php endif?>
<?php if(Permission::can('facturation.schedules')):?><section class="panel"><h2>Échéancier</h2><form class="grid" method="post" action="/public/facturation/echeancier"><input type="hidden" name="_csrf" value="<?=Csrf::token()?>"><input type="hidden" name="invoice_id" value="<?=$invoice['id']?>"><label>Date prévue<input type="date" name="due_date" required></label><label>Montant<input type="number" step="0.01" name="amount" required></label><label>Mode<select name="payment_method"><option>Chèque</option><option>Virement</option><option>Prélèvement</option></select></label><label>N° chèque<input name="cheque_number"></label><label>Banque émettrice<input name="drawer_bank"></label><button class="btn">Ajouter</button></form><table><tr><th>N°</th><th>Date</th><th>Mode</th><th>Chèque</th><th>Banque</th><th>Montant</th><th>État</th></tr><?php foreach($invoice['schedules']??[] as $s):?><tr><td><?=$s['installment_number']?></td><td><?=$s['due_date']?></td><td><?=$s['payment_method']?></td><td><?=htmlspecialchars($s['cheque_number']??'')?></td><td><?=htmlspecialchars($s['drawer_bank']??'')?></td><td><?=number_format((float)$s['amount'],2,',',' ')?> €</td><td><?=$s['status']?></td></tr><?php endforeach?></table></section><?php endif?>
<?php
$accountingEntries = $invoice['entries'] ?? [];
$journalGroups = [
    'VE' => ['title' => 'Journal des ventes', 'entries' => []],
    'OD' => ['title' => 'Opérations diverses', 'entries' => []],
];
$otherJournalGroups = [];
foreach ($accountingEntries as $entry) {
    $journalCode = strtoupper(trim((string)($entry['journal_code'] ?? '')));
    if (isset($journalGroups[$journalCode])) {
        $journalGroups[$journalCode]['entries'][] = $entry;
        continue;
    }
    $otherCode = $journalCode !== '' ? $journalCode : 'AUTRE';
    $otherJournalGroups[$otherCode] ??= [
        'title' => 'Journal '.$otherCode,
        'entries' => [],
    ];
    $otherJournalGroups[$otherCode]['entries'][] = $entry;
}
$journalGroups += $otherJournalGroups;
?>
<section class="panel accounting-entries-panel">
    <div class="accounting-entries-heading">
        <div>
            <h2>Écritures comptables</h2>
            <p>Les ventes et les opérations diverses sont présentées séparément.</p>
        </div>
        <a class="btn secondary" href="/public/facturation/ecritures.csv?id=<?=(int)$invoice['id']?>">Télécharger le CSV</a>
    </div>

    <?php if (!$accountingEntries): ?>
        <p class="accounting-entries-empty">Aucune écriture comptable n’a encore été générée.</p>
    <?php else: ?>
        <?php foreach ($journalGroups as $journalCode => $group): ?>
            <?php if (!$group['entries']) continue; ?>
            <?php
            $totalDebit = 0.0;
            $totalCredit = 0.0;
            foreach ($group['entries'] as $entry) {
                $totalDebit += (float)($entry['debit'] ?? 0);
                $totalCredit += (float)($entry['credit'] ?? 0);
            }
            $isBalanced = abs($totalDebit - $totalCredit) < 0.005;
            ?>
            <section class="accounting-journal">
                <header class="accounting-journal-head">
                    <div>
                        <span class="accounting-journal-code"><?=htmlspecialchars((string)$journalCode)?></span>
                        <h3><?=htmlspecialchars($group['title'])?></h3>
                    </div>
                    <span class="accounting-balance <?=$isBalanced ? 'is-balanced' : 'is-unbalanced'?>">
                        <?=$isBalanced ? 'Équilibré' : 'À contrôler'?>
                    </span>
                </header>
                <div class="accounting-entries-table-wrap">
                    <table class="accounting-entries-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Journal</th>
                                <th>Compte</th>
                                <th>Libellé</th>
                                <th class="money">Débit</th>
                                <th class="money">Crédit</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($group['entries'] as $entry): ?>
                                <tr>
                                    <td data-label="Date"><?=htmlspecialchars((string)($entry['entry_date'] ?? ''))?></td>
                                    <td data-label="Journal"><span class="journal-pill"><?=htmlspecialchars((string)($entry['journal_code'] ?? ''))?></span></td>
                                    <td data-label="Compte"><strong><?=htmlspecialchars((string)($entry['account_number'] ?? ''))?></strong></td>
                                    <td data-label="Libellé"><?=htmlspecialchars((string)($entry['label'] ?? ''))?></td>
                                    <td data-label="Débit" class="money"><?=number_format((float)($entry['debit'] ?? 0),2,',',' ')?> €</td>
                                    <td data-label="Crédit" class="money"><?=number_format((float)($entry['credit'] ?? 0),2,',',' ')?> €</td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th colspan="4">Total du journal <?=htmlspecialchars((string)$journalCode)?></th>
                                <th class="money"><?=number_format($totalDebit,2,',',' ')?> €</th>
                                <th class="money"><?=number_format($totalCredit,2,',',' ')?> €</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </section>
        <?php endforeach; ?>
    <?php endif; ?>
</section></main>
