<link rel="stylesheet" href="/public/assets/css/cda-billing-959.css">
<link rel="stylesheet" href="/public/assets/css/cda-billing-drafts-974.css">
<?php
$draftGroups=[];$otherInvoices=[];
foreach($invoices as $invoice){
    if(($invoice['status']??'')==='draft'){
        $key=(string)$invoice['client_id'];
        if(!isset($draftGroups[$key]))$draftGroups[$key]=['client'=>$invoice,'drafts'=>[],'total'=>0.0];
        $draftGroups[$key]['drafts'][]=$invoice;
        $draftGroups[$key]['total']+=(float)$invoice['total_amount'];
    }else{$otherInvoices[]=$invoice;}
}
?>
<main class="billing">
<header class="billing-head"><div><a class="back" href="/public/">← Retour</a><h1>Facturation</h1><p>À facturer · facturé · payé · banque · comptabilité</p></div><div class="billing-top-actions"><a class="btn" href="/public/facturation/a-preparer">↻ À facturer et synchroniser</a><a class="btn secondary" href="/public/facturation/paiements-a-valider">✓ Paiements à valider</a><a class="btn" href="/public/facturation/nouvelle">+ Nouveau document</a><a class="btn secondary" href="/public/facturation/parametres">Paramètres AXIOM</a></div></header>
<div class="cards"><div><b><?=count(array_filter($invoices,fn($i)=>$i['status']==='draft'))?></b><span>Brouillons</span></div><div><b><?=count(array_filter($invoices,fn($i)=>in_array($i['status'],['issued','part_paid'],true)))?></b><span>À encaisser</span></div><div><b><?=count(array_filter($invoices,fn($i)=>$i['status']==='paid'))?></b><span>Payées</span></div></div>

<section class="drafts-section">
<div class="drafts-title"><div><h2>Brouillons regroupés par adhérent</h2><p>Le regroupement visuel ne fusionne rien. Générez chaque brouillon seul ou sélectionnez-en plusieurs pour créer une facture unique.</p></div><span><?=count($draftGroups)?> adhérent(s)</span></div>
<?php if(!$draftGroups):?><div class="draft-empty">Aucun brouillon en cours.</div><?php endif?>
<?php foreach($draftGroups as $group):$client=$group['client'];$drafts=$group['drafts'];?>
<article class="client-drafts">
<header><div class="client-avatar"><?=htmlspecialchars(mb_substr((string)$client['nom'],0,1).mb_substr((string)$client['prenom'],0,1))?></div><div><h3><?=htmlspecialchars($client['nom'].' '.$client['prenom'])?></h3><small>Compte <?=htmlspecialchars($client['client_account'])?> · <?=count($drafts)?> brouillon(s)</small></div><strong><?=number_format($group['total'],2,',',' ')?> €</strong></header>
<form method="post" action="/public/facturation/brouillons/emettre-ensemble" class="draft-group-form" onsubmit="return confirm('Réunir les brouillons cochés et générer une facture unique ?');">
<?=\App\Core\Csrf::field()?>
<div class="draft-list">
<?php foreach($drafts as $draft):?>
<div class="draft-row">
<?php if(count($drafts)>1&&\App\Core\Permission::can('facturation.create')):?><label class="draft-select"><input type="checkbox" name="draft_ids[]" value="<?=(int)$draft['id']?>"><span>Sélectionner</span></label><?php endif?>
<div class="draft-identity"><b>Brouillon #<?=(int)$draft['id']?></b><small><?=htmlspecialchars($draft['document_type'])?> · échéance <?=htmlspecialchars($draft['due_date']??'non définie')?></small></div>
<div class="draft-amount"><?=number_format((float)$draft['total_amount'],2,',',' ')?> €</div>
<div class="draft-actions"><a class="btn secondary" href="/public/facturation/voir?id=<?=(int)$draft['id']?>">Ouvrir</a><?php if(\App\Core\Permission::can('facturation.edit')):?><a class="btn secondary" href="/public/facturation/modifier?id=<?=(int)$draft['id']?>">Modifier</a><?php endif?><?php if(\App\Core\Permission::can('facturation.create')):?><button class="btn" type="submit" formaction="/public/facturation/emettre" name="id" value="<?=(int)$draft['id']?>" onclick="return confirm('Générer uniquement ce brouillon ?')">Générer seul</button><?php endif?></div>
</div>
<?php endforeach?>
</div>
<?php if(count($drafts)>1&&\App\Core\Permission::can('facturation.create')):?><footer><label class="select-all-drafts"><input type="checkbox" data-select-drafts> Tout sélectionner</label><button class="btn generate-together" type="submit">Générer ensemble les brouillons cochés</button></footer><?php endif?>
</form>
</article>
<?php endforeach?>
</section>

<section class="issued-section"><h2>Factures émises et autres documents</h2><div class="table-wrap"><table><thead><tr><th>Numéro</th><th>Adhérent / compte client</th><th>Type</th><th>État</th><th>Échéance</th><th class="num">Montant</th><th>Actions</th></tr></thead><tbody><?php if(!$otherInvoices):?><tr><td colspan="7">Aucune facture émise.</td></tr><?php endif?><?php foreach($otherInvoices as $i):?><tr><td><?=htmlspecialchars($i['document_number']?:'Document #'.$i['id'])?></td><td><?=htmlspecialchars($i['nom'].' '.$i['prenom'])?><small><?=htmlspecialchars($i['client_account'])?></small></td><td><?=htmlspecialchars($i['document_type'])?></td><td><span class="status"><?=htmlspecialchars($i['status'])?></span></td><td><?=htmlspecialchars($i['due_date']??'—')?></td><td class="num"><?=number_format((float)$i['total_amount'],2,',',' ')?> €</td><td><a class="btn secondary" href="/public/facturation/voir?id=<?=(int)$i['id']?>">Ouvrir</a></td></tr><?php endforeach?></tbody></table></div></section>
</main>
<script>document.querySelectorAll('.draft-group-form').forEach(function(form){var all=form.querySelector('[data-select-drafts]');if(all)all.addEventListener('change',function(){form.querySelectorAll('input[name="draft_ids[]"]').forEach(function(box){box.checked=all.checked;});});});</script>
