<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Facture <?= htmlspecialchars($facture['numero']) ?></h1>
        <p class="text-muted mb-0"><?= htmlspecialchars($facture['client_nom']) ?></p>
    </div>
    <?php
        $documentId = (int)($facture['document_id'] ?? 0);
        $reste = (float)($facture['reste_du'] ?? 0);
        $regle = (float)($facture['montant_regle'] ?? 0);
    ?>
    <div class="d-flex gap-2 flex-wrap">
        <a href="index.php?page=factures" class="btn btn-outline-secondary">Retour</a>
        <?php if ($reste > 0.005): ?>
            <a href="index.php?page=factures_edit&id=<?= (int)$facture['id'] ?>" class="btn btn-outline-warning">✏ Modifier la facture</a>
        <?php endif; ?>
        <?php if ($reste > 0): ?>
            <a href="index.php?page=encaissements_create&facture_id=<?= (int)$facture['id'] ?>" class="btn btn-outline-success">💰 Encaisser</a>
        <?php endif; ?>
        <?php if ($documentId > 0): ?>
            <a href="index.php?page=avoirs_create&facture_id=<?= $documentId ?>" class="btn btn-outline-info">🧾 Créer un avoir</a>
        <?php endif; ?>
        <a href="index.php?page=factures_pdf&id=<?= (int)$facture['id'] ?>" target="_blank" class="btn btn-outline-primary">📄 Générer le PDF</a>
    </div>
</div>

<?php $cycleType = 'FACTURE'; require __DIR__ . '/../partials/document_cycle.php'; ?>

<div class="darlink-card p-4 mb-4">
    <div class="row g-3">
        <div class="col-md-3"><strong>Date facture :</strong><br><?= htmlspecialchars($facture['date_facture']) ?></div>
        <div class="col-md-3"><strong>Échéance :</strong><br><?= htmlspecialchars($facture['date_echeance'] ?? '-') ?></div>
        <div class="col-md-3"><strong>Statut :</strong><br><span class="badge text-bg-light border"><?= htmlspecialchars(($facture['statut'] ?? '') === 'émise' ? 'En cours' : ($facture['statut'] ?? '')) ?></span></div>
        <div class="col-md-3"><strong>Bon de livraison :</strong><br><?= htmlspecialchars($facture['bl_numero'] ?? '-') ?></div>
        <div class="col-md-6"><strong>Adresse client :</strong><br><?= nl2br(htmlspecialchars(trim(($facture['adresse'] ?? '') . ' ' . ($facture['ville'] ?? '')) ?: '-')) ?></div>
        <div class="col-md-6"><strong>Observations :</strong><br><?= nl2br(htmlspecialchars($facture['observations'] ?: '-')) ?></div>
    </div>
</div>

<div class="darlink-card p-4 mb-4">
    <div class="table-responsive">
        <table class="table table-hover align-middle darlink-table">
            <thead>
            <tr>
                <th>Réf.</th><th>Désignation</th><th>Unité</th><th class="text-end">Qté</th><th class="text-end">PU HT</th><th class="text-end">Remise</th><th class="text-end">TVA</th><th class="text-end">Total HT</th><th class="text-end">Total TTC</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($lignes as $ligne): ?>
                <tr>
                    <td><?= htmlspecialchars($ligne['reference']) ?></td>
                    <td><?= htmlspecialchars($ligne['designation']) ?></td>
                    <td><?= htmlspecialchars($ligne['unite']) ?></td>
                    <td class="text-end"><?= number_format((float)$ligne['quantite'], 2, ',', ' ') ?></td>
                    <td class="text-end"><?= number_format((float)$ligne['prix_vente_ht'], 2, ',', ' ') ?></td>
                    <td class="text-end"><?= number_format((float)$ligne['remise'], 2, ',', ' ') ?> %</td>
                    <td class="text-end"><?= number_format((float)$ligne['taux_tva'], 2, ',', ' ') ?> %</td>
                    <td class="text-end"><?= number_format((float)$ligne['total_ht'], 2, ',', ' ') ?></td>
                    <td class="text-end"><?= number_format((float)$ligne['total_ttc'], 2, ',', ' ') ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
            <tr><th colspan="7" class="text-end">Total HT</th><th colspan="2" class="text-end"><?= number_format((float)$facture['total_ht'], 2, ',', ' ') ?> MAD</th></tr>
            <tr><th colspan="7" class="text-end">TVA</th><th colspan="2" class="text-end"><?= number_format((float)$facture['total_tva'], 2, ',', ' ') ?> MAD</th></tr>
            <tr><th colspan="7" class="text-end">Total TTC</th><th colspan="2" class="text-end fs-5"><?= number_format((float)$facture['total_ttc'], 2, ',', ' ') ?> MAD</th></tr>
            <tr><th colspan="7" class="text-end">Montant réglé</th><th colspan="2" class="text-end text-success"><?= number_format((float)$facture['montant_regle'], 2, ',', ' ') ?> MAD</th></tr>
            <tr><th colspan="7" class="text-end">Reste dû</th><th colspan="2" class="text-end text-danger"><?= number_format((float)$facture['reste_du'], 2, ',', ' ') ?> MAD</th></tr>
            </tfoot>
        </table>
    </div>
</div>

<div class="darlink-card p-4 mb-4 no-print">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Encaissements</h5>
        <?php if ((float)$facture['reste_du'] > 0): ?>
            <a href="index.php?page=encaissements_create&facture_id=<?= (int)$facture['id'] ?>" class="btn btn-sm btn-outline-success">+ Encaisser</a>
        <?php endif; ?>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle darlink-table">
            <thead>
            <tr>
                <th>Type</th>
                <th>Date</th>
                <th>Mode</th>
                <th>Référence</th>
                <th class="text-end">Montant</th>
                <th>Observations</th>
                <th class="text-end">Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($encaissements)): ?>
                <tr><td colspan="7" class="text-center text-muted py-3">Aucun encaissement enregistré pour cette facture.</td></tr>
            <?php endif; ?>
            <?php foreach ($encaissements as $encaissement): ?>
                <?php $isCancelled = (int)($encaissement['actif'] ?? 1) !== 1; ?>
                <tr class="<?= $isCancelled ? 'text-muted opacity-75' : '' ?>">
                    <td>
                        <?php if ($isCancelled): ?>
                            <span class="badge text-bg-secondary">Annulé</span>
                        <?php else: ?>
                            <span class="badge text-bg-success">Encaissement</span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($encaissement['date_encaissement']) ?></td>
                    <td><?= htmlspecialchars($encaissement['mode_reglement']) ?></td>
                    <td><?= htmlspecialchars($encaissement['reference_reglement'] ?? '-') ?></td>
                    <td class="text-end <?= $isCancelled ? 'text-decoration-line-through' : 'text-success' ?>"><?= number_format((float)$encaissement['montant'], 2, ',', ' ') ?> MAD</td>
                    <td><?= htmlspecialchars($encaissement['observations'] ?? '-') ?></td>
                    <td class="text-end text-nowrap">
                        <?php if (!$isCancelled): ?>
                            <a href="index.php?page=encaissements_edit&id=<?= (int)$encaissement['id'] ?>" class="btn btn-sm btn-outline-warning">✏ Modifier</a>
                            <form method="post" action="index.php?page=encaissements_cancel" class="d-inline" onsubmit="return confirm('Confirmer l’annulation de cet encaissement ? Le règlement restera visible dans l’historique mais ne sera plus comptabilisé.');">
                                <input type="hidden" name="encaissement_id" value="<?= (int)$encaissement['id'] ?>">
                                <input type="hidden" name="return_to" value="facture">
                                <button type="submit" class="btn btn-sm btn-outline-danger">⛔ Annuler</button>
                            </form>
                        <?php else: ?>
                            <span class="small text-muted">Aucune action</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
