<?php
function stock_alert_state(float $qte, float $mini): array {
    if ($qte <= 0) return ['Rupture', 'text-bg-danger'];
    if ($mini > 0 && $qte <= $mini) return ['Stock bas', 'text-bg-warning'];
    return ['OK', 'text-bg-success'];
}
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Stock minimum / alertes</h1>
        <p class="text-muted mb-0">Définis les seuils minimums et repère les articles à réassortir.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=stock" class="btn btn-outline-secondary">Retour stock</a>
        <a href="index.php?page=stock_adjust" class="btn btn-outline-primary">Ajustement</a>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-4"><div class="darlink-card p-3"><div class="text-muted">Articles suivis</div><div class="h4 mb-0"><?= (int)($summary['total_articles'] ?? 0) ?></div></div></div>
    <div class="col-md-4"><div class="darlink-card p-3"><div class="text-muted">Ruptures</div><div class="h4 mb-0 text-danger"><?= (int)($summary['ruptures'] ?? 0) ?></div></div></div>
    <div class="col-md-4"><div class="darlink-card p-3"><div class="text-muted">Alertes stock bas</div><div class="h4 mb-0 text-warning"><?= (int)($summary['alertes'] ?? 0) ?></div></div></div>
</div>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="darlink-card p-4">
            <h5 class="mb-3">Définir un stock minimum</h5>
            <form method="post" action="index.php?page=stock_minimum_store">
                <div class="mb-3">
                    <label class="form-label">Article</label>
                    <select name="article_id" id="articleSelect" class="form-select" required>
                        <option value="">Sélectionner un article</option>
                        <?php foreach ($articles as $article): ?>
                            <option value="<?= (int)$article['id'] ?>"
                                data-stock="<?= htmlspecialchars((string)$article['quantite']) ?>"
                                data-minimum="<?= htmlspecialchars((string)$article['stock_minimum']) ?>"
                                <?= ((int)$selectedArticleId === (int)$article['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($article['reference'] . ' — ' . $article['designation']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label">Stock actuel</label>
                        <input type="text" id="currentStock" class="form-control" readonly>
                    </div>
                    <div class="col-6">
                        <label class="form-label">Stock minimum</label>
                        <input type="number" step="1" min="0" name="stock_minimum" id="minimumStock" class="form-control" required>
                    </div>
                </div>
                <button class="btn darlink-btn-primary w-100" type="submit">Enregistrer le seuil</button>
            </form>
            <div class="alert alert-info small mt-3 mb-0">
                Une alerte apparaît quand le stock est inférieur ou égal au minimum. Une rupture apparaît quand le stock est à zéro ou négatif.
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="darlink-card p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Articles en alerte</h5>
                <span class="badge text-bg-warning"><?= count($alerts) ?> alerte(s)</span>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle darlink-table">
                    <thead>
                    <tr>
                        <th>Référence</th>
                        <th>Désignation</th>
                        <th class="text-end">Stock</th>
                        <th class="text-end">Mini</th>
                        <th class="text-end">Besoin</th>
                        <th>État</th>
                        <th class="text-end">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (empty($alerts)): ?>
                        <tr><td colspan="7" class="text-center text-muted py-4">Aucune alerte stock pour le moment.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($alerts as $row): ?>
                        <?php [$label, $class] = stock_alert_state((float)$row['quantite'], (float)$row['stock_minimum']); ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($row['reference']) ?></strong></td>
                            <td><?= htmlspecialchars($row['designation']) ?></td>
                            <td class="text-end fw-bold"><?= number_format((float)$row['quantite'], 0, ',', ' ') ?> <?= htmlspecialchars($row['unite'] ?? '') ?></td>
                            <td class="text-end"><?= number_format((float)$row['stock_minimum'], 0, ',', ' ') ?></td>
                            <td class="text-end"><?= number_format((float)$row['besoin_reassort'], 0, ',', ' ') ?></td>
                            <td><span class="badge <?= $class ?>"><?= $label ?></span></td>
                            <td class="text-end">
                                <div class="btn-group btn-group-sm">
                                    <a href="index.php?page=stock_alerts&id=<?= (int)$row['article_id'] ?>" class="btn btn-outline-secondary">Modifier mini</a>
                                    <a href="index.php?page=stock_adjust&id=<?= (int)$row['article_id'] ?>" class="btn btn-outline-warning">Ajuster</a>
                                    <a href="index.php?page=stock_show&id=<?= (int)$row['article_id'] ?>" class="btn btn-outline-primary">Historique</a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const select = document.getElementById('articleSelect');
    const current = document.getElementById('currentStock');
    const minimum = document.getElementById('minimumStock');
    function refresh() {
        const option = select.options[select.selectedIndex];
        if (!option || !option.value) {
            current.value = '';
            minimum.value = '';
            return;
        }
        current.value = Number(option.dataset.stock || 0).toLocaleString('fr-FR', {maximumFractionDigits: 0});
        minimum.value = Math.round(Number(option.dataset.minimum || 0));
    }
    select.addEventListener('change', refresh);
    refresh();
})();
</script>
