<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$formatQty = static fn($value): string => number_format((float)$value, 0, ',', ' ');
$statusLabel = static fn($statut): string => match ((string)$statut) {
    'validée' => 'Validée',
    'partiellement_reçue' => 'Partielle',
    'reçue' => 'Reçue',
    default => ucfirst((string)$statut),
};
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Historique achats</h1>
        <p class="text-muted mb-0">Analyse par fournisseur, article, période, prix d’achat et quantités.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=commandes_fournisseurs" class="btn btn-darlink-outline-secondary">← Commandes fournisseurs</a>
        <a href="index.php?page=commandes_fournisseurs_create" class="btn darlink-btn-primary">+ Nouvelle commande</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 concernées</div>
            <div class="h4 mb-0"><?= (int)($stats['nombre_commandes'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Total achats HT</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['total_ht'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Quantité commandée / reçue</div>
            <div class="h5 mb-0"><?= $formatQty($stats['quantite_commandee'] ?? 0) ?> / <?= $formatQty($stats['quantite_recue'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Prix achat moyen</div>
            <div class="h4 mb-0"><?= $formatMoney($stats['prix_moyen'] ?? 0) ?></div>
        </div>
    </div>
</div>

<div class="darlink-card p-4 mb-4">
    <form method="get" class="row g-3 align-items-end">
        <input type="hidden" name="page" value="commandes_fournisseurs_historique">
        <div class="col-md-3">
            <label class="form-label">Fournisseur</label>
            <select name="fournisseur_id" class="form-select form-darlink">
                <option value="0">Tous les fournisseurs</option>
                <?php foreach ($fournisseurs as $fournisseur): ?>
                    <option value="<?= (int)$fournisseur['id'] ?>" <?= (int)($filters['fournisseur_id'] ?? 0) === (int)$fournisseur['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars(($fournisseur['code_fournisseur'] ?? '') . ' — ' . $fournisseur['raison_sociale']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Article</label>
            <select name="article_id" class="form-select form-darlink">
                <option value="0">Tous les articles</option>
                <?php foreach ($articles as $article): ?>
                    <option value="<?= (int)$article['id'] ?>" <?= (int)($filters['article_id'] ?? 0) === (int)$article['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($article['reference'] . ' — ' . $article['designation']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label">Du</label>
            <input type="date" name="date_from" class="form-control form-darlink" value="<?= htmlspecialchars($filters['date_from'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Au</label>
            <input type="date" name="date_to" class="form-control form-darlink" value="<?= htmlspecialchars($filters['date_to'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Recherche</label>
            <input type="text" name="q" class="form-control form-darlink" value="<?= htmlspecialchars($filters['q'] ?? '') ?>" placeholder="N°, article...">
        </div>
        <div class="col-md-12 text-end">
            <button type="submit" class="btn darlink-btn-primary">Filtrer</button>
            <a href="index.php?page=commandes_fournisseurs_historique" class="btn btn-outline-secondary">Réinitialiser</a>
        </div>
    </form>
</div>

<div class="darlink-card p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Détail des achats</h5>
        <span class="text-muted small"><?= count($history) ?> ligne(s) affichée(s), maximum 500</span>
    </div>
    <div class="table-responsive">
        <table class="table table-hover align-middle darlink-table">
            <thead>
            <tr>
                <th>Date</th>
                <th>Commande</th>
                <th>Fournisseur</th>
                <th>Article</th>
                <th class="text-end">Qté commandée</th>
                <th class="text-end">Qté reçue</th>
                <th class="text-end">Prix achat HT</th>
                <th class="text-end">Total HT</th>
                <th>Statut</th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($history)): ?>
                <tr><td colspan="9" class="text-center text-muted py-5">Aucun historique achat pour ces critères.</td></tr>
            <?php endif; ?>
            <?php foreach ($history as $row): ?>
                <tr>
                    <td><?= htmlspecialchars(date('d/m/Y', strtotime((string)$row['date_commande']))) ?></td>
                    <td><a href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$row['commande_id'] ?>"><strong><?= htmlspecialchars($row['numero']) ?></strong></a></td>
                    <td>
                        <?= htmlspecialchars($row['fournisseur_nom']) ?>
                        <div class="small text-muted"><?= htmlspecialchars($row['code_fournisseur'] ?? '') ?></div>
                    </td>
                    <td>
                        <strong><?= htmlspecialchars($row['reference'] ?: ($row['article_reference_actuelle'] ?? '')) ?></strong>
                        <div class="small text-muted"><?= htmlspecialchars($row['designation'] ?: ($row['article_designation_actuelle'] ?? '')) ?></div>
                    </td>
                    <td class="text-end"><?= $formatQty($row['quantite'] ?? 0) ?></td>
                    <td class="text-end"><?= $formatQty($row['quantite_recue'] ?? 0) ?></td>
                    <td class="text-end"><?= $formatMoney($row['prix_achat_ht'] ?? 0) ?></td>
                    <td class="text-end"><strong><?= $formatMoney($row['total_ht'] ?? 0) ?></strong></td>
                    <td><span class="badge text-bg-light border"><?= htmlspecialchars($statusLabel($row['statut'] ?? '')) ?></span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
