<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$formatQty = static fn($value): string => number_format((float)$value, 0, ',', ' ');
$formatPercent = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' %';
$formatDate = static function ($value): string {
    if (empty($value)) {
        return '-';
    }
    return date('d/m/Y', strtotime((string)$value));
};
$badge = static function (string $statut): string {
    return match ($statut) {
        'brouillon' => 'secondary',
        'validée', 'envoyée' => 'primary',
        'partiellement_reçue' => 'warning',
        'reçue' => 'success',
        'annulée' => 'danger',
        default => 'light',
    };
};
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Tableau de bord achats</h1>
        <p class="text-muted mb-0">Vue rapide des commandes fournisseurs, réceptions attendues, hausses d’achat et marges faibles.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=commandes_fournisseurs_create" class="btn darlink-btn-primary">Nouvelle commande</a>
        <a href="index.php?page=commandes_fournisseurs_analyse" class="btn btn-outline-secondary">Analyse marge</a>
        <a href="index.php?page=commandes_fournisseurs_historique" class="btn btn-outline-secondary">Historique</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">Commandes en cours</div>
            <div class="h4 mb-0"><?= (int)($stats['commandes_en_cours'] ?? 0) ?></div>
            <div class="small text-muted"><?= $formatMoney($stats['total_en_cours_ttc'] ?? 0) ?> TTC</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Réceptions partielles</div>
            <div class="h4 mb-0 text-warning"><?= (int)($stats['receptions_partielles'] ?? 0) ?></div>
            <div class="small text-muted">Commandes non terminées</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Commandes en retard</div>
            <div class="h4 mb-0 text-danger"><?= (int)($stats['commandes_en_retard'] ?? 0) ?></div>
            <div class="small text-muted">Date prévue dépassée</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Reste à recevoir</div>
            <div class="h4 mb-0"><?= $formatQty($stats['quantite_restante'] ?? 0) ?></div>
            <div class="small text-muted"><?= $formatMoney($stats['montant_restant_ht'] ?? 0) ?> HT</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">Réceptions attendues</h5>
                <a href="index.php?page=commandes_fournisseurs" class="btn btn-sm btn-outline-secondary">Toutes les commandes</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead>
                    <tr>
                        <th>Commande</th>
                        <th>Fournisseur</th>
                        <th>Date prévue</th>
                        <th class="text-end">Reste</th>
                        <th class="text-end">Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($expectedReceptions)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Aucune réception attendue.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($expectedReceptions as $row): ?>
                        <?php $late = !empty($row['date_livraison_prevue']) && strtotime((string)$row['date_livraison_prevue']) < strtotime(date('Y-m-d')); ?>
                        <tr class="<?= $late ? 'table-danger' : '' ?>">
                            <td>
                                <strong><?= htmlspecialchars($row['numero']) ?></strong>
                                <div><span class="badge text-bg-<?= $badge((string)$row['statut']) ?>"><?= htmlspecialchars($row['statut']) ?></span></div>
                            </td>
                            <td><?= htmlspecialchars($row['fournisseur_nom']) ?></td>
                            <td><?= $formatDate($row['date_livraison_prevue'] ?? null) ?></td>
                            <td class="text-end">
                                <?= $formatQty($row['quantite_restante'] ?? 0) ?>
                                <div class="small text-muted"><?= $formatMoney($row['montant_restant_ht'] ?? 0) ?> HT</div>
                            </td>
                            <td class="text-end"><a href="index.php?page=commandes_fournisseurs_receive&id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-outline-success">Réception</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">Commandes fournisseurs en cours</h5>
                <a href="index.php?page=commandes_fournisseurs_create" class="btn btn-sm darlink-btn-primary">Créer</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead>
                    <tr>
                        <th>Commande</th>
                        <th>Fournisseur</th>
                        <th class="text-end">Total TTC</th>
                        <th class="text-end">Reçu</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($ordersInProgress)): ?>
                        <tr><td colspan="4" class="text-center text-muted py-4">Aucune commande en cours.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($ordersInProgress as $row): ?>
                        <?php
                        $ordered = (float)($row['quantite_commandee'] ?? 0);
                        $received = (float)($row['quantite_recue'] ?? 0);
                        $percent = $ordered > 0 ? min(100, round(($received / $ordered) * 100, 0)) : 0;
                        ?>
                        <tr>
                            <td>
                                <a href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$row['id'] ?>"><strong><?= htmlspecialchars($row['numero']) ?></strong></a>
                                <div class="small text-muted">Prévue : <?= $formatDate($row['date_livraison_prevue'] ?? null) ?></div>
                            </td>
                            <td><?= htmlspecialchars($row['fournisseur_nom']) ?></td>
                            <td class="text-end"><?= $formatMoney($row['total_ttc'] ?? 0) ?></td>
                            <td class="text-end">
                                <?= $percent ?> %
                                <div class="progress" style="height: 6px;">
                                    <div class="progress-bar" role="progressbar" style="width: <?= (int)$percent ?>%;" aria-valuenow="<?= (int)$percent ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </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 marge faible</h5>
                <span class="badge text-bg-danger"><?= (int)($analysisStats['nb_marges_faibles'] ?? 0) ?></span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Article</th><th class="text-end">Achat réf.</th><th class="text-end">Vente HT</th><th class="text-end">Marge</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($marginAlerts)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Aucune marge faible détectée.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($marginAlerts as $row): ?>
                        <tr class="table-danger">
                            <td><strong><?= htmlspecialchars($row['reference']) ?></strong><div class="small text-muted"><?= htmlspecialchars($row['designation']) ?></div></td>
                            <td class="text-end"><?= $formatMoney($row['prix_achat_reference'] ?? 0) ?></td>
                            <td class="text-end"><?= $formatMoney($row['prix_vente_ht'] ?? 0) ?></td>
                            <td class="text-end"><strong><?= $formatPercent($row['marge_reelle_pourcentage'] ?? 0) ?></strong></td>
                            <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="index.php?page=articles_achats&id=<?= (int)$row['id'] ?>">Corriger</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">Hausses prix d’achat</h5>
                <span class="badge text-bg-warning"><?= (int)($analysisStats['nb_hausses'] ?? 0) ?></span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Article</th><th class="text-end">Achat actuel</th><th class="text-end">Dernier achat</th><th class="text-end">Écart</th><th></th></tr></thead>
                    <tbody>
                    <?php if (empty($priceIncreaseAlerts)): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">Aucune hausse détectée.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($priceIncreaseAlerts as $row): ?>
                        <tr class="table-warning">
                            <td><strong><?= htmlspecialchars($row['reference']) ?></strong><div class="small text-muted"><?= htmlspecialchars($row['designation']) ?></div></td>
                            <td class="text-end"><?= $formatMoney($row['prix_achat_ht'] ?? 0) ?></td>
                            <td class="text-end"><?= $formatMoney($row['dernier_prix_achat_ht'] ?? 0) ?></td>
                            <td class="text-end"><strong><?= $formatMoney($row['ecart_prix_achat'] ?? 0) ?></strong><div class="small text-muted"><?= $formatPercent($row['ecart_prix_achat_pourcentage'] ?? 0) ?></div></td>
                            <td class="text-end"><a class="btn btn-sm btn-outline-secondary" href="index.php?page=commandes_fournisseurs_historique&article_id=<?= (int)$row['id'] ?>">Historique</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 sur 12 mois</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Fournisseur</th><th class="text-end">Commandes</th><th class="text-end">Total HT</th></tr></thead>
                    <tbody>
                    <?php if (empty($topSuppliers)): ?>
                        <tr><td colspan="3" class="text-center text-muted py-4">Aucune donnée fournisseur.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($topSuppliers as $row): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($row['fournisseur_nom']) ?></strong><div class="small text-muted"><?= htmlspecialchars($row['code_fournisseur'] ?? '') ?></div></td>
                            <td class="text-end"><?= (int)($row['nombre_commandes'] ?? 0) ?></td>
                            <td class="text-end"><?= $formatMoney($row['total_ht'] ?? 0) ?></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">Top articles achetés sur 12 mois</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead><tr><th>Article</th><th class="text-end">Qté commandée</th><th class="text-end">Total HT</th></tr></thead>
                    <tbody>
                    <?php if (empty($topArticles)): ?>
                        <tr><td colspan="3" class="text-center text-muted py-4">Aucune donnée article.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($topArticles as $row): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars((string)($row['reference'] ?? '')) ?></strong><div class="small text-muted"><?= htmlspecialchars((string)($row['designation'] ?? '')) ?></div></td>
                            <td class="text-end"><?= $formatQty($row['quantite_commandee'] ?? 0) ?></td>
                            <td class="text-end"><?= $formatMoney($row['total_ht'] ?? 0) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
