<?php
$selectedArticleId = (int)($selectedArticleId ?? 0);
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Ajustement manuel de stock</h1>
        <p class="text-muted mb-0">Corrige ponctuellement un article sans lancer un inventaire complet.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=stock_inventory" class="btn btn-outline-primary">Inventaire complet</a>
        <a href="index.php?page=stock" class="btn btn-outline-secondary">Retour stock</a>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Usage conseillé</div>
            <div class="fw-semibold">Correction rapide d’un seul article</div>
            <div class="small text-muted mt-2">Exemple : casse, perte, erreur de saisie, recomptage ponctuel.</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Mouvement créé</div>
            <div class="fw-semibold">Type <span class="badge text-bg-warning">ADJ</span></div>
            <div class="small text-muted mt-2">L’écart est enregistré dans l’historique stock.</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="darlink-card p-3 h-100">
            <div class="text-muted small">Stock final</div>
            <div class="fw-semibold">La quantité saisie devient le nouveau stock réel</div>
            <div class="small text-muted mt-2">Darlink calcule automatiquement l’écart.</div>
        </div>
    </div>
</div>

<div class="darlink-card p-4">
    <form method="post" action="index.php?page=stock_store_adjust" id="adjustForm">
        <div class="row g-3">
            <div class="col-md-8">
                <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): ?>
                        <?php
                        $id = (int)$article['id'];
                        $qte = (float)($article['quantite'] ?? 0);
                        $unite = (string)($article['unite'] ?? '');
                        ?>
                        <option
                            value="<?= $id ?>"
                            data-stock="<?= htmlspecialchars((string)$qte) ?>"
                            data-unite="<?= htmlspecialchars($unite) ?>"
                            <?= $selectedArticleId === $id ? 'selected' : '' ?>
                        >
                            <?= htmlspecialchars(($article['reference'] ?? '') . ' — ' . ($article['designation'] ?? '') . ' | stock actuel : ' . number_format($qte, 2, ',', ' ') . ' ' . $unite) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Stock actuel</label>
                <input type="text" id="stockActuel" class="form-control" readonly value="—">
            </div>
            <div class="col-md-4">
                <label class="form-label">Nouveau stock réel</label>
                <input type="number" step="1" min="0" name="stock_reel" id="stockReel" class="form-control" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">Écart calculé</label>
                <input type="text" id="ecartCalcule" class="form-control fw-bold" readonly value="—">
            </div>
            <div class="col-md-4">
                <label class="form-label">Sens du mouvement</label>
                <input type="text" id="sensMouvement" class="form-control" readonly value="—">
            </div>
            <div class="col-md-12">
                <label class="form-label">Commentaire</label>
                <textarea name="commentaire" class="form-control" rows="3" placeholder="Exemple : casse, recomptage ponctuel, erreur de saisie, perte..."></textarea>
                <div class="form-text">Le commentaire sera visible dans l’historique des mouvements de stock.</div>
            </div>
        </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">Enregistrer l’ajustement</button>
        </div>
    </form>
</div>

<script>
(function () {
    const select = document.getElementById('articleSelect');
    const stockActuel = document.getElementById('stockActuel');
    const stockReel = document.getElementById('stockReel');
    const ecartCalcule = document.getElementById('ecartCalcule');
    const sensMouvement = document.getElementById('sensMouvement');

    function numberFr(value) {
        return Number(value || 0).toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 3 });
    }

    function refresh() {
        const option = select.options[select.selectedIndex];
        const current = Number(option?.dataset?.stock || 0);
        const unite = option?.dataset?.unite || '';
        stockActuel.value = select.value ? `${numberFr(current)} ${unite}` : '—';

        if (!select.value || stockReel.value === '') {
            ecartCalcule.value = '—';
            sensMouvement.value = '—';
            return;
        }

        const reel = Number(stockReel.value || 0);
        const ecart = reel - current;
        ecartCalcule.value = `${ecart >= 0 ? '+' : ''}${numberFr(ecart)} ${unite}`;
        sensMouvement.value = Math.abs(ecart) < 0.0001 ? 'Aucun écart' : (ecart > 0 ? 'Ajout au stock' : 'Retrait du stock');
    }

    select.addEventListener('change', function () {
        const option = select.options[select.selectedIndex];
        if (option && option.dataset.stock !== undefined && stockReel.value === '') {
            stockReel.value = option.dataset.stock;
        }
        refresh();
    });
    stockReel.addEventListener('input', refresh);

    if (select.value) {
        const option = select.options[select.selectedIndex];
        stockReel.value = option?.dataset?.stock || '';
    }
    refresh();
})();
</script>
