<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Inventaire stock</h1>
        <p class="text-muted mb-0">Saisis le stock réel constaté. Darlink calcule l’écart et ajuste le stock.</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_history&type=INV" class="btn btn-outline-primary">Mouvements inventaire</a>
    </div>
</div>

<div class="darlink-card p-4 mb-4">
    <form method="post" action="index.php?page=stock_inventory_store">
        <div class="row g-3 mb-3">
            <div class="col-md-8">
                <label class="form-label">Commentaire</label>
                <input type="text" name="commentaire" class="form-control" placeholder="Exemple : inventaire mensuel, inventaire annuel...">
            </div>
            <div class="col-md-4 d-flex align-items-end justify-content-md-end">
                <button type="submit" class="btn darlink-btn-primary w-100">Valider l’inventaire</button>
            </div>
        </div>

        <div class="alert alert-info py-2">
            Astuce : le champ <strong>stock réel</strong> est pré-rempli avec le stock théorique. Modifie uniquement les articles où il y a un écart.
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle darlink-table" id="inventoryTable">
                <thead>
                    <tr>
                        <th>Référence</th>
                        <th>Désignation</th>
                        <th class="text-end">Théorique</th>
                        <th class="text-end">Stock réel</th>
                        <th class="text-end">Écart</th>
                        <th class="text-end">Achat HT</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-5">Aucun article actif à inventorier.</td></tr>
                <?php endif; ?>
                <?php foreach ($rows as $row): ?>
                    <?php $qte = (float) ($row['stock_theorique'] ?? 0); ?>
                    <tr data-theorique="<?= htmlspecialchars((string)(int)round($qte)) ?>">
                        <td><strong><?= htmlspecialchars($row['reference'] ?? '') ?></strong></td>
                        <td><?= htmlspecialchars($row['designation'] ?? '') ?><br><span class="text-muted small"><?= htmlspecialchars($row['unite'] ?? '') ?></span></td>
                        <td class="text-end stock-theorique"><?= number_format($qte, 0, ',', ' ') ?></td>
                        <td class="text-end" style="width:160px">
                            <input type="number" step="1" min="0" name="stock_reel[<?= (int)$row['article_id'] ?>]" class="form-control text-end inv-real" value="<?= htmlspecialchars((string)(int)round($qte)) ?>">
                        </td>
                        <td class="text-end inv-ecart">0</td>
                        <td class="text-end"><?= number_format((float)($row['prix_achat_ht'] ?? 0), 2, ',', ' ') ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="mt-4 d-flex justify-content-end gap-2">
            <a href="index.php?page=stock" class="btn btn-outline-secondary">Annuler</a>
            <button type="submit" class="btn darlink-btn-primary">Valider l’inventaire</button>
        </div>
    </form>
</div>

<div class="darlink-card p-4">
    <h2 class="h5 mb-3">Derniers inventaires</h2>
    <div class="table-responsive">
        <table class="table table-hover align-middle darlink-table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Commentaire</th>
                    <th class="text-end">Articles</th>
                    <th class="text-end">Écarts</th>
                    <th class="text-end">Valeur écart HT</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($inventories)): ?>
                <tr><td colspan="6" class="text-center text-muted py-4">Aucun inventaire enregistré.</td></tr>
            <?php endif; ?>
            <?php foreach ($inventories as $inv): ?>
                <tr>
                    <td><?= htmlspecialchars($inv['date_inventaire']) ?></td>
                    <td><?= htmlspecialchars($inv['commentaire'] ?? '-') ?></td>
                    <td class="text-end"><?= (int)$inv['nb_articles'] ?></td>
                    <td class="text-end fw-bold"><?= (int)$inv['nb_ecarts'] ?></td>
                    <td class="text-end <?= (float)$inv['valeur_ecart_ht'] < 0 ? 'text-danger' : 'text-success' ?>"><?= number_format((float)$inv['valeur_ecart_ht'], 2, ',', ' ') ?></td>
                    <td class="text-end"><a href="index.php?page=stock_inventory_show&id=<?= (int)$inv['id'] ?>" class="btn btn-sm btn-outline-primary">Voir</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.querySelectorAll('.inv-real').forEach(function(input) {
    function refresh() {
        const tr = input.closest('tr');
        const theorique = parseFloat(tr.dataset.theorique || '0');
        const reel = parseFloat((input.value || '0').replace(',', '.')) || 0;
        const ecart = reel - theorique;
        const cell = tr.querySelector('.inv-ecart');
        cell.textContent = ecart.toLocaleString('fr-FR', {maximumFractionDigits: 0});
        cell.classList.toggle('text-danger', ecart < 0);
        cell.classList.toggle('text-success', ecart > 0);
        cell.classList.toggle('fw-bold', Math.abs(ecart) > 0.0001);
    }
    input.addEventListener('input', refresh);
    refresh();
});
</script>
