<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$formatDate = static fn($value): string => !empty($value) ? date('d/m/Y', strtotime((string)$value)) : '-';
$statusLabels = [
    'non_reglee' => 'Non réglée',
    'partiellement_reglee' => 'Partiellement réglée',
    'reglee' => 'Réglée',
];
$today = new DateTimeImmutable(date('Y-m-d'));
$daysDiff = static function ($date) use ($today): int {
    if (empty($date)) {
        return 0;
    }
    return (int)$today->diff(new DateTimeImmutable((string)$date))->format('%r%a');
};
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Tableau de bord fournisseurs</h1>
        <p class="text-muted mb-0">Synthèse des factures fournisseurs, retards, paiements à venir et règlements récents.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=factures_fournisseurs_echeancier" class="btn btn-outline-primary" role="button">Échéancier</a>
        <a href="index.php?page=factures_fournisseurs" class="btn btn-primary" role="button">Factures fournisseurs</a>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Total dû fournisseurs</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['total_du'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($stats['nb_a_payer'] ?? 0) ?> facture(s) à payer</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Factures en retard</div>
            <div class="h4 mb-0 text-danger"><?= $formatMoney($stats['total_retard'] ?? 0) ?></div>
            <div class="small text-muted"><?= (int)($stats['nb_retard'] ?? 0) ?> facture(s)</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">À payer sous 7 jours</div>
            <div class="h4 mb-0 text-warning"><?= $formatMoney($stats['total_7_jours'] ?? 0) ?></div>
            <div class="small text-muted">Sous 30 jours : <?= $formatMoney($stats['total_30_jours'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Réglé ce mois</div>
            <div class="h4 mb-0 text-success"><?= $formatMoney($stats['total_regle_mois'] ?? 0) ?></div>
            <div class="small text-muted">Factures réglées : <?= (int)($stats['nb_reglees'] ?? 0) ?></div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Alertes factures en retard</h5>
                <a href="index.php?page=factures_fournisseurs_echeancier&periode=retard" class="btn btn-sm btn-outline-danger">Voir les retards</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Échéance</th><th>Facture</th><th>Fournisseur</th><th class="text-end">Reste dû</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($overdueFactures)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Aucune facture fournisseur en retard.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($overdueFactures as $facture): ?>
                        <tr class="table-danger">
                            <td><strong><?= $formatDate($facture['date_echeance'] ?? null) ?></strong><br><span class="small text-muted"><?= abs($daysDiff($facture['date_echeance'] ?? null)) ?> jour(s) de retard</span></td>
                            <td><strong><?= htmlspecialchars($facture['numero_interne']) ?></strong><br><span class="small text-muted"><?= htmlspecialchars($facture['numero_facture_fournisseur']) ?></span></td>
                            <td><?= htmlspecialchars($facture['fournisseur_nom']) ?></td>
                            <td class="text-end"><strong><?= $formatMoney($facture['reste_du']) ?></strong></td>
                            <td class="text-end"><a href="index.php?page=factures_fournisseurs_reglement&id=<?= (int)$facture['id'] ?>" class="btn btn-sm btn-success">Régler</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="darlink-card p-4 h-100">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Paiements à venir</h5>
                <a href="index.php?page=factures_fournisseurs_echeancier&periode=30_jours" class="btn btn-sm btn-outline-primary">30 jours</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Échéance</th><th>Facture</th><th>Fournisseur</th><th class="text-end">Reste dû</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($upcomingFactures)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Aucun paiement à venir.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($upcomingFactures as $facture): ?>
                        <?php $diff = $daysDiff($facture['date_echeance'] ?? null); ?>
                        <tr class="<?= $diff <= 7 ? 'table-warning' : '' ?>">
                            <td><strong><?= $formatDate($facture['date_echeance'] ?? null) ?></strong><br><span class="small text-muted">Dans <?= max(0, $diff) ?> jour(s)</span></td>
                            <td><strong><?= htmlspecialchars($facture['numero_interne']) ?></strong><br><span class="small text-muted"><?= htmlspecialchars($facture['numero_facture_fournisseur']) ?></span></td>
                            <td><?= htmlspecialchars($facture['fournisseur_nom']) ?></td>
                            <td class="text-end"><strong><?= $formatMoney($facture['reste_du']) ?></strong></td>
                            <td class="text-end"><a href="index.php?page=factures_fournisseurs_show&id=<?= (int)$facture['id'] ?>" class="btn btn-sm btn-outline-primary">Ouvrir</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-md-6">
        <div class="darlink-card p-4 h-100">
            <h5 class="mb-3">Top fournisseurs à payer</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Fournisseur</th><th class="text-end">Factures</th><th class="text-end">Total dû</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($topFournisseursDue)): ?>
                        <tr><td colspan="4" class="text-center text-muted py-4">Aucun fournisseur à payer.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($topFournisseursDue as $row): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($row['fournisseur_nom']) ?></strong><br><span class="small text-muted"><?= htmlspecialchars($row['code_fournisseur'] ?? '') ?></span></td>
                            <td class="text-end"><?= (int)($row['nb_factures'] ?? 0) ?></td>
                            <td class="text-end"><strong><?= $formatMoney($row['total_du'] ?? 0) ?></strong></td>
                            <td class="text-end"><a href="index.php?page=factures_fournisseurs_echeancier&fournisseur_id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-outline-secondary">Détail</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="darlink-card p-4 h-100">
            <h5 class="mb-3">Derniers règlements fournisseurs</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Date</th><th>Fournisseur</th><th>Facture</th><th>Mode</th><th class="text-end">Montant</th></tr></thead>
                    <tbody>
                    <?php if (empty($recentReglements)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Aucun règlement enregistré.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($recentReglements as $reglement): ?>
                        <tr>
                            <td><?= $formatDate($reglement['date_reglement'] ?? null) ?></td>
                            <td><?= htmlspecialchars($reglement['fournisseur_nom']) ?></td>
                            <td><a href="index.php?page=factures_fournisseurs_show&id=<?= (int)$reglement['facture_fournisseur_id'] ?>"><?= htmlspecialchars($reglement['numero_interne']) ?></a></td>
                            <td><?= htmlspecialchars($reglement['mode_reglement'] ?: '-') ?></td>
                            <td class="text-end"><strong><?= $formatMoney($reglement['montant']) ?></strong></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
