<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$statusLabels = [
    'non_reglee' => 'Non réglée',
    'partiellement_reglee' => 'Partiellement réglée',
    'reglee' => 'Réglée',
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Facture fournisseur <?= htmlspecialchars($facture['numero_interne']) ?></h1>
        <p class="text-muted mb-0"><?= htmlspecialchars($facture['fournisseur_nom']) ?> — Facture fournisseur <?= htmlspecialchars($facture['numero_facture_fournisseur']) ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=factures_fournisseurs" class="btn btn-darlink-outline-secondary">← Liste</a>
        <?php if((int)$facture['actif']===1): ?><a href="index.php?page=factures_fournisseurs_edit&id=<?= (int)$facture['id'] ?>" class="btn btn-outline-primary">Modifier</a><?php endif; ?>
        <?php if(!empty($facture['justificatif_fichier'])): ?><a href="index.php?page=factures_fournisseurs_justificatif&id=<?= (int)$facture['id'] ?>" class="btn btn-outline-secondary">Justificatif</a><?php endif; ?>
        <?php if ((float)$facture['reste_du'] > 0): ?>
            <a href="index.php?page=factures_fournisseurs_reglement&id=<?= (int)$facture['id'] ?>" class="btn btn-success">Régler</a>
        <?php endif; ?>
        <?php if (!empty($facture['commande_fournisseur_id'])): ?>
            <a href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$facture['commande_fournisseur_id'] ?>" class="btn btn-outline-primary">Commande liée</a>
        <?php endif; ?>
    </div>
</div>
<?php if((int)$facture['actif']===1): ?><form method="post" action="index.php?page=factures_fournisseurs_deactivate" class="text-end mb-3" onsubmit="return confirm('Annuler cette facture d’achat ? Elle restera dans l’historique.');"><input type="hidden" name="id" value="<?= (int)$facture['id'] ?>"><button class="btn btn-outline-danger">Annuler la facture</button></form><?php else: ?><form method="post" action="index.php?page=factures_fournisseurs_reactivate" class="text-end mb-3"><input type="hidden" name="id" value="<?= (int)$facture['id'] ?>"><button class="btn btn-outline-success">Réactiver la facture</button></form><?php endif; ?>

<div class="darlink-card p-4 mt-3"><h5>Articles et frais</h5><div class="table-responsive mt-3"><table class="table darlink-table align-middle"><thead><tr><th>Type</th><th>Référence</th><th>Désignation</th><th class="text-end">Qté</th><th class="text-end">Prix HT</th><th class="text-end">TVA</th><th class="text-end">TTC</th></tr></thead><tbody><?php if(empty($lignes)): ?><tr><td colspan="7" class="text-center text-muted">Aucune ligne détaillée.</td></tr><?php endif; ?><?php foreach($lignes as $ligne): ?><tr><td><?= ($ligne['type_ligne']??'article')==='frais'?'Frais':'Article' ?></td><td><?= htmlspecialchars($ligne['reference']?:'-') ?></td><td><?= htmlspecialchars($ligne['designation']) ?></td><td class="text-end"><?= number_format((float)$ligne['quantite'],3,',',' ') ?></td><td class="text-end"><?= $formatMoney($ligne['prix_achat_ht']) ?></td><td class="text-end"><?= number_format((float)$ligne['taux_tva'],2,',',' ') ?> %</td><td class="text-end"><strong><?= $formatMoney($ligne['total_ttc']) ?></strong></td></tr><?php endforeach; ?></tbody></table></div></div>

<div class="row g-3">
    <div class="col-md-6">
        <div class="darlink-card p-4 h-100">
            <h5>Fournisseur</h5>
            <div class="mt-3">
                <strong><?= htmlspecialchars($facture['fournisseur_nom']) ?></strong><br>
                <span class="text-muted"><?= htmlspecialchars($facture['code_fournisseur']) ?></span><br>
                <?= htmlspecialchars($facture['ville'] ?: '') ?><br>
                <?= htmlspecialchars($facture['telephone'] ?: '') ?><br>
                <?= htmlspecialchars($facture['email'] ?: '') ?>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="darlink-card p-4 h-100">
            <h5>Facture</h5>
            <div class="row mt-3 g-2">
                <div class="col-md-6"><strong>Interne :</strong> <?= htmlspecialchars($facture['numero_interne']) ?></div>
                <div class="col-md-6"><strong>Fournisseur :</strong> <?= htmlspecialchars($facture['numero_facture_fournisseur']) ?></div>
                <div class="col-md-6"><strong>Date :</strong> <?= htmlspecialchars(date('d/m/Y', strtotime((string)$facture['date_facture']))) ?></div>
                <div class="col-md-6"><strong>Échéance :</strong> <?= !empty($facture['date_echeance']) ? htmlspecialchars(date('d/m/Y', strtotime((string)$facture['date_echeance']))) : '-' ?></div>
                <div class="col-md-12"><strong>Statut :</strong> <?= htmlspecialchars($statusLabels[$facture['statut']] ?? $facture['statut']) ?></div>
                <div class="col-md-12"><strong>Commande :</strong> <?= htmlspecialchars($facture['commande_numero'] ?: '-') ?></div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mt-1">
    <div class="col-md-8">
        <div class="darlink-card p-4 h-100">
            <h5>Observations</h5>
            <p class="text-muted mb-0 mt-3"><?= nl2br(htmlspecialchars(trim((string)($facture['observations'] ?? '')) ?: 'Aucune observation.')) ?></p>
        </div>
    </div>
    <div class="col-md-4">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between mb-2"><span>Total HT</span><strong><?= $formatMoney($facture['montant_ht']) ?></strong></div>
            <div class="d-flex justify-content-between mb-2"><span>TVA</span><strong><?= $formatMoney($facture['montant_tva']) ?></strong></div>
            <div class="d-flex justify-content-between mb-2"><span>Total TTC</span><strong><?= $formatMoney($facture['montant_ttc']) ?></strong></div>
            <hr>
            <div class="d-flex justify-content-between mb-2"><span>Réglé</span><strong><?= $formatMoney($facture['montant_regle']) ?></strong></div>
            <div class="d-flex justify-content-between h5"><span>Reste dû</span><strong><?= $formatMoney($facture['reste_du']) ?></strong></div>
        </div>
    </div>
</div>


<div class="darlink-card p-4 mt-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Historique des règlements</h5>
        <a href="index.php?page=reglements_fournisseurs" class="btn btn-sm btn-outline-primary">Journal des règlements</a>
        <?php if ((float)$facture['reste_du'] > 0): ?>
            <a href="index.php?page=factures_fournisseurs_reglement&id=<?= (int)$facture['id'] ?>" class="btn btn-sm btn-success">Ajouter un règlement</a>
        <?php endif; ?>
    </div>
    <div class="table-responsive">
        <table class="table darlink-table align-middle mb-0">
            <thead>
            <tr>
                <th>Date</th>
                <th>Mode</th>
                <th>Référence</th>
                <th>Observations</th>
                <th>Statut</th><th class="text-end">Montant</th><th></th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($reglements)): ?>
                <tr><td colspan="7" class="text-center text-muted py-4">Aucun règlement enregistré.</td></tr>
            <?php endif; ?>
            <?php foreach ($reglements as $reglement): ?>
                <tr>
                    <td><?= htmlspecialchars(date('d/m/Y', strtotime((string)$reglement['date_reglement']))) ?></td>
                    <td><?= htmlspecialchars($reglement['mode_reglement'] ?: '-') ?></td>
                    <td><?= htmlspecialchars($reglement['reference_reglement'] ?: '-') ?></td>
                    <td><?= htmlspecialchars($reglement['observations'] ?: '-') ?></td>
                    <td><?= (int)$reglement['actif'] ? '<span class="badge bg-success">Actif</span>' : '<span class="badge bg-danger">Annulé</span>' ?></td>
                    <td class="text-end"><strong><?= $formatMoney($reglement['montant']) ?></strong></td>
                    <td class="text-end"><?php if((int)$reglement['actif']): ?><form method="post" action="index.php?page=reglements_fournisseurs_annuler" onsubmit="return confirm('Annuler ce règlement ? Le reste dû sera recalculé.');"><input type="hidden" name="id" value="<?= (int)$reglement['id'] ?>"><button class="btn btn-sm btn-outline-danger">Annuler</button></form><?php endif; ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
