<?php
$fmt = static fn ($v): string => number_format((float)$v, 2, ',', ' ') . ' MAD';
$qty = static fn ($v): string => number_format((float)$v, 0, ',', ' ');
$pct = static fn ($v): string => number_format((float)$v, 2, ',', ' ') . ' %';
$filters = $filters ?? [];
$kpis = $kpis ?? [];
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-1">Analyse articles vendus / performance commerciale</h1>
        <p class="text-muted mb-0">Voir ce qui se vend, ce qui rapporte et ce qui dort en stock.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=dashboard_commercial" class="btn btn-outline-secondary">Dashboard commercial</a>
        <a href="index.php?page=articles" class="btn 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 vendus</div><div class="h4 mb-1"><?= (int)($kpis['nb_articles_vendus'] ?? 0) ?></div><div class="small text-muted"><?= (int)($kpis['nb_lignes'] ?? 0) ?> ligne(s) facturées</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Quantité vendue</div><div class="h4 mb-1"><?= $qty($kpis['quantite_vendue'] ?? 0) ?></div><div class="small text-muted">Sans décimale</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">CA articles HT</div><div class="h4 mb-1"><?= $fmt($kpis['ca_ht'] ?? 0) ?></div><div class="small text-muted"><?= $fmt($kpis['ca_ttc'] ?? 0) ?> TTC</div></div></div>
    <div class="col-md-3"><div class="darlink-card p-3 h-100"><div class="text-muted small">Marge estimée</div><div class="h4 mb-1"><?= $fmt($kpis['marge_ht'] ?? 0) ?></div><div class="small text-muted"><?= $pct($kpis['marge_pourcentage'] ?? 0) ?></div></div></div>
</div>

<div class="darlink-card p-4 mb-4">
    <form method="get" action="index.php" class="row g-3 align-items-end">
        <input type="hidden" name="page" value="articles_sales_analysis">
        <div class="col-md-3">
            <label class="form-label">Article</label>
            <select name="article_id" class="form-select">
                <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(trim(($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" value="<?= htmlspecialchars((string)($filters['date_from'] ?? '')) ?>"></div>
        <div class="col-md-2"><label class="form-label">Au</label><input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars((string)($filters['date_to'] ?? '')) ?>"></div>
        <div class="col-md-2">
            <label class="form-label">Trier par</label>
            <select name="tri" class="form-select">
                <?php $tri = (string)($filters['tri'] ?? 'ca'); ?>
                <option value="ca" <?= $tri === 'ca' ? 'selected' : '' ?>>CA</option>
                <option value="quantite" <?= $tri === 'quantite' ? 'selected' : '' ?>>Quantité</option>
                <option value="marge" <?= $tri === 'marge' ? 'selected' : '' ?>>Marge</option>
                <option value="rotation" <?= $tri === 'rotation' ? 'selected' : '' ?>>Nombre de ventes</option>
            </select>
        </div>
        <div class="col-md-3 d-flex gap-2"><button class="btn btn-primary" type="submit">Filtrer</button><a href="index.php?page=articles_sales_analysis" class="btn btn-outline-secondary">Réinitialiser</a></div>
    </form>
    <?php if (!empty($filters['article_id']) || !empty($filters['date_from']) || !empty($filters['date_to']) || (($filters['tri'] ?? 'ca') !== 'ca')): ?>
        <div class="alert alert-info mt-3 mb-0 py-2">Filtres appliqués sur l’analyse. Les résultats ci-dessous sont recalculés selon les critères sélectionnés.</div>
    <?php endif; ?>
</div>

<div class="darlink-card p-4 mb-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">Articles vendus</h5>
        <span class="badge text-bg-light border">Performance commerciale</span>
    </div>
    <?php if (empty($articlesVendus)): ?>
        <p class="text-muted mb-0">Aucune vente d’article sur la période sélectionnée.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-sm align-middle">
                <thead><tr><th>Article</th><th class="text-end">Qté vendue</th><th class="text-end">Nb ventes</th><th class="text-end">CA HT</th><th class="text-end">Marge HT</th><th class="text-end">Marge %</th><th class="text-end">Stock</th><th>Dernière vente</th><th></th></tr></thead>
                <tbody>
                <?php foreach ($articlesVendus as $row): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars((string)($row['reference'] ?? '')) ?></strong><br><span class="text-muted small"><?= htmlspecialchars((string)($row['designation'] ?? '')) ?></span></td>
                        <td class="text-end"><?= $qty($row['quantite_vendue'] ?? 0) ?></td>
                        <td class="text-end"><?= (int)($row['nb_ventes'] ?? 0) ?></td>
                        <td class="text-end"><?= $fmt($row['ca_ht'] ?? 0) ?></td>
                        <td class="text-end"><?= $fmt($row['marge_ht'] ?? 0) ?></td>
                        <td class="text-end"><?= $pct($row['marge_pourcentage'] ?? 0) ?></td>
                        <td class="text-end"><?= $qty($row['stock_actuel'] ?? 0) ?></td>
                        <td><?= htmlspecialchars((string)($row['derniere_vente'] ?? '')) ?></td>
                        <td class="text-end"><?php if (!empty($row['article_id'])): ?><a class="btn btn-sm btn-outline-secondary" href="index.php?page=stock_show&id=<?= (int)$row['article_id'] ?>">Stock</a><?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<div class="row g-3">
    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <h5 class="mb-3">Articles peu vendus</h5>
            <?php if (empty($articlesPeuVendus)): ?>
                <p class="text-muted mb-0">Aucune donnée.</p>
            <?php else: ?>
                <div class="table-responsive"><table class="table table-sm align-middle"><thead><tr><th>Article</th><th class="text-end">Qté</th><th class="text-end">CA HT</th><th class="text-end">Stock</th></tr></thead><tbody>
                <?php foreach ($articlesPeuVendus as $row): ?>
                    <tr><td><?= htmlspecialchars(trim(($row['reference'] ?? '') . ' — ' . ($row['designation'] ?? ''), ' —')) ?></td><td class="text-end"><?= $qty($row['quantite_vendue'] ?? 0) ?></td><td class="text-end"><?= $fmt($row['ca_ht'] ?? 0) ?></td><td class="text-end"><?= $qty($row['stock_actuel'] ?? 0) ?></td></tr>
                <?php endforeach; ?>
                </tbody></table></div>
            <?php endif; ?>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="darlink-card p-4 h-100">
            <h5 class="mb-3">Articles sans vente sur la période</h5>
            <?php if (empty($articlesSansVente)): ?>
                <p class="text-muted mb-0">Aucun article sans vente détecté.</p>
            <?php else: ?>
                <div class="table-responsive"><table class="table table-sm align-middle"><thead><tr><th>Article</th><th class="text-end">Stock</th><th class="text-end">Prix vente HT</th><th></th></tr></thead><tbody>
                <?php foreach ($articlesSansVente as $row): ?>
                    <tr><td><?= htmlspecialchars(trim(($row['reference'] ?? '') . ' — ' . ($row['designation'] ?? ''), ' —')) ?></td><td class="text-end"><?= $qty($row['stock_actuel'] ?? 0) ?></td><td class="text-end"><?= $fmt($row['prix_vente_ht'] ?? 0) ?></td><td class="text-end"><a class="btn btn-sm btn-outline-secondary" href="index.php?page=articles_achats&id=<?= (int)($row['id'] ?? 0) ?>">Prix</a></td></tr>
                <?php endforeach; ?>
                </tbody></table></div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="mt-4 text-muted small">Version <?= htmlspecialchars((string)($version ?? 'Phoenix P3.6.4.4')) ?></div>
