<?php require __DIR__ . '/directory_show.php'; ?>
<?php if ($contact['kind'] === 'organization' && !empty($contactInvoices)): $invoicePaid = (int)$contactInvoiceTotal - (int)$contactInvoiceDue; ?>
<div class="card mt-3">
    <div class="card-status-top bg-teal"></div>
    <div class="card-header">
        <h3 class="card-title">🧾 Facturation comptable</h3><a class="btn btn-sm btn-outline-teal ms-auto"
            href="/accounting?year=<?= $expensePeriodYear ?: 0 ?>">Ouvrir Comptabilité</a>
    </div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <div class="subheader">Facturé net</div>
                <div class="h2 mb-0"><?= h($money((int)$contactInvoiceTotal)) ?></div>
            </div>
            <div class="col-md-3">
                <div class="subheader">Payé</div>
                <div class="h2 mb-0 text-green"><?= h($money($invoicePaid)) ?></div>
            </div>
            <div class="col-md-3">
                <div class="subheader">Reste dû</div>
                <div class="h2 mb-0 text-orange"><?= h($money((int)$contactInvoiceDue)) ?></div>
            </div>
            <div class="col-md-3">
                <div class="subheader">Pièces</div>
                <div class="h2 mb-0"><?= count($contactInvoices) ?></div>
            </div>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-sm table-vcenter mb-0">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Référence</th>
                    <th>Type</th>
                    <th>Statut</th>
                    <th class="text-end">TTC</th>
                </tr>
            </thead>
            <tbody><?php foreach (array_slice($contactInvoices, 0, 25) as $invoice):?><tr>
                    <td><?= h($frDate($invoice['invoice_date'])) ?></td>
                    <td><a href="/accounting/edit?id=<?= (int)$invoice['id'] ?>"><?= h($invoice['reference']) ?></a>
                    </td>
                    <td><?= h(['invoice' => 'Facture','credit' => 'Avoir','adjustment' => 'Régularisation'][$invoice['document_type']] ?? $invoice['document_type']) ?>
                    </td>
                    <td><span
                            class="badge <?= $invoice['status'] === 'paid' ? 'bg-green-lt' : 'bg-orange-lt' ?>"><?= h(['paid' => 'Payée','to_pay' => 'À payer','partial' => 'Partielle','disputed' => 'Contestée','cancelled' => 'Annulée'][$invoice['status']] ?? $invoice['status']) ?></span>
                    </td>
                    <td class="text-end fw-bold"><?= h($money((int)$invoice['total_ttc_cents'])) ?></td>
                </tr><?php endforeach?></tbody>
        </table>
    </div>
</div>
<?php endif; ?>
