<?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, ',', ' ') . ' %';
$margeMin = (float)($filters['marge_min'] ?? 30);
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Analyse achats / marge</h1>
        <p class="text-muted mb-0">Contrôle des prix d’achat, marges réelles et alertes de hausse.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=commandes_fournisseurs_historique" class="btn btn-outline-secondary">Historique achats</a>
        <a href="index.php?page=articles" class="btn darlink-btn-primary">Articles</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">Articles analysés</div>
            <div class="h4 mb-0"><?= (int)($stats['nb_articles'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Hausses prix achat</div>
            <div class="h4 mb-0 text-warning"><?= (int)($stats['nb_hausses'] ?? 0) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Marges sous seuil</div>
            <div class="h4 mb-0 text-danger"><?= (int)($stats['nb_marges_faibles'] ?? 0) ?></div>
            <div class="small text-muted">Seuil : <?= $formatPercent($margeMin) ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Marge moyenne réelle</div>
            <div class="h4 mb-0"><?= $formatPercent($stats['marge_moyenne'] ?? 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_analyse">
        <div class="col-md-4">
            <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">Seuil marge minimum</label>
            <div class="input-group">
                <input type="number" step="0.01" name="marge_min" class="form-control form-darlink" value="<?= htmlspecialchars((string)$margeMin) ?>">
                <span class="input-group-text">%</span>
            </div>
        </div>
        <div class="col-md-3">
            <label class="form-label">Recherche</label>
            <input type="text" name="q" class="form-control form-darlink" value="<?= htmlspecialchars($filters['q'] ?? '') ?>" placeholder="Référence, désignation...">
        </div>
        <div class="col-md-2 text-end">
            <button type="submit" class="btn darlink-btn-primary w-100">Analyser</button>
        </div>
        <div class="col-md-12 text-end">
            <a href="index.php?page=commandes_fournisseurs_analyse" class="btn btn-sm btn-outline-secondary">Réinitialiser</a>
        </div>
    </form>
</div>

<div class="alert alert-light border mb-4">
    <strong>Lecture rapide :</strong>
    le prix d’achat de référence est le dernier prix acheté si l’article a déjà été commandé, sinon le prix d’achat actuel de la fiche article.
    Les alertes signalent les hausses d’achat et les marges réelles inférieures au seuil choisi.
</div>

<div class="darlink-card p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Contrôle articles</h5>
        <span class="text-muted small"><?= count($rows) ?> ligne(s)</span>
    </div>
    <div class="table-responsive">
        <table class="table table-hover align-middle darlink-table">
            <thead>
            <tr>
                <th>Article</th>
                <th>Fournisseur</th>
                <th class="text-end">Stock</th>
                <th class="text-end">Achat actuel</th>
                <th class="text-end">Dernier achat</th>
                <th class="text-end">Écart</th>
                <th class="text-end">Vente HT</th>
                <th class="text-end">Marge réelle</th>
                <th class="text-end">Marge %</th>
                <th>Alertes</th>
                <th class="text-end">Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="11" class="text-center text-muted py-5">Aucune donnée à analyser.</td></tr>
            <?php endif; ?>
            <?php foreach ($rows as $row): ?>
                <tr class="<?= !empty($row['alerte_marge_faible']) ? 'table-danger' : (!empty($row['alerte_hausse_achat']) ? 'table-warning' : '') ?>">
                    <td>
                        <strong><?= htmlspecialchars($row['reference']) ?></strong>
                        <div class="small text-muted"><?= htmlspecialchars($row['designation']) ?></div>
                    </td>
                    <td>
                        <?= htmlspecialchars($row['fournisseur_principal_nom'] ?: ($row['dernier_fournisseur_nom'] ?? '-')) ?>
                        <?php if (!empty($row['fournisseur_principal_code'])): ?>
                            <div class="small text-muted"><?= htmlspecialchars($row['fournisseur_principal_code']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="text-end"><?= $formatQty($row['stock_quantite'] ?? 0) ?></td>
                    <td class="text-end"><?= $formatMoney($row['prix_achat_ht'] ?? 0) ?></td>
                    <td class="text-end">
                        <?= $formatMoney($row['dernier_prix_achat_ht'] ?? 0) ?>
                        <?php if (!empty($row['date_dernier_achat'])): ?>
                            <div class="small text-muted"><?= htmlspecialchars(date('d/m/Y', strtotime((string)$row['date_dernier_achat']))) ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="text-end">
                        <?= $formatMoney($row['ecart_prix_achat'] ?? 0) ?>
                        <div class="small text-muted"><?= $formatPercent($row['ecart_prix_achat_pourcentage'] ?? 0) ?></div>
                    </td>
                    <td class="text-end"><?= $formatMoney($row['prix_vente_ht'] ?? 0) ?></td>
                    <td class="text-end"><?= $formatMoney($row['marge_reelle_dh'] ?? 0) ?></td>
                    <td class="text-end"><strong><?= $formatPercent($row['marge_reelle_pourcentage'] ?? 0) ?></strong></td>
                    <td>
                        <?php if (!empty($row['alerte_hausse_achat'])): ?>
                            <span class="badge text-bg-warning">Hausse achat</span>
                        <?php endif; ?>
                        <?php if (!empty($row['alerte_marge_faible'])): ?>
                            <span class="badge text-bg-danger">Marge faible</span>
                        <?php endif; ?>
                        <?php if (empty($row['alerte_hausse_achat']) && empty($row['alerte_marge_faible'])): ?>
                            <span class="badge text-bg-light border">OK</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-end">
                        <a href="index.php?page=articles_achats&id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-outline-primary">Prix</a>
                        <a href="index.php?page=commandes_fournisseurs_historique&article_id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-outline-secondary">Historique</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
