<?php
$formatMoney = static fn($value): string => number_format((float)$value, 2, ',', ' ') . ' DH';
$formatQty = static fn($value): string => number_format((float)$value, 0, ',', ' ');
$canReceive = in_array((string)($commande['statut'] ?? ''), ['validée', 'partiellement_reçue'], true);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">Réception fournisseur</h1>
        <p class="text-muted mb-0">Commande <?= htmlspecialchars($commande['numero']) ?> — <?= htmlspecialchars($commande['fournisseur_nom']) ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$commande['id'] ?>" class="btn btn-darlink-outline-secondary">← Retour commande</a>
    </div>
</div>

<div class="darlink-card p-4 mb-4">
    <div class="row g-3">
        <div class="col-md-3"><strong>Date commande</strong><br><?= htmlspecialchars(date('d/m/Y', strtotime((string)$commande['date_commande']))) ?></div>
        <div class="col-md-3"><strong>Statut actuel</strong><br><?= htmlspecialchars((string)($commande['statut'] ?? 'brouillon')) ?></div>
        <div class="col-md-3"><strong>Total HT</strong><br><?= $formatMoney($commande['total_ht']) ?></div>
        <div class="col-md-3"><strong>Total TTC</strong><br><?= $formatMoney($commande['total_ttc']) ?></div>
    </div>
</div>

<?php if (!$canReceive): ?>
    <div class="alert alert-info">Cette commande est déjà totalement réceptionnée ou ne peut pas être réceptionnée.</div>
<?php endif; ?>

<form method="post" action="index.php?page=commandes_fournisseurs_receive_store" class="darlink-card p-4" onsubmit="return confirm('Enregistrer la réception et mettre à jour le stock ?');">
    <input type="hidden" name="id" value="<?= (int)$commande['id'] ?>">

    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <label class="form-label">N° de réception</label>
            <input class="form-control" name="numero" value="<?= htmlspecialchars((string)$receptionNumber) ?>" readonly>
        </div>
        <div class="col-md-3">
            <label class="form-label">Date de réception *</label>
            <input type="date" class="form-control" name="date_reception" value="<?= date('Y-m-d') ?>" required>
        </div>
        <div class="col-md-3">
            <label class="form-label">Référence bon de livraison</label>
            <input class="form-control" name="reference_bl" maxlength="100">
        </div>
        <div class="col-md-3">
            <label class="form-label">Observations</label>
            <input class="form-control" name="observations" maxlength="500">
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h5 class="mb-1">Articles à réceptionner</h5>
            <p class="text-muted mb-0">Saisissez uniquement la quantité livrée aujourd’hui. Chaque livraison sera conservée séparément.</p>
        </div>
        <button type="button" class="btn btn-outline-secondary btn-sm" id="fillAll" <?= !$canReceive ? 'disabled' : '' ?>>Tout recevoir</button>
    </div>

    <div class="table-responsive">
        <table class="table darlink-table align-middle" id="receiveTable">
            <thead>
            <tr>
                <th>Réf.</th>
                <th>Désignation</th>
                <th class="text-end">Commandé</th>
                <th class="text-end">Déjà reçu</th>
                <th class="text-end">Livrée aujourd’hui</th>
                <th class="text-end">Reste</th>
                <th>Stock</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($lines as $line): ?>
                <?php
                $ordered = (float)($line['quantite'] ?? 0);
                $received = (float)($line['quantite_recue'] ?? 0);
                $remaining = max(0, $ordered - $received);
                $hasArticle = !empty($line['article_id']);
                ?>
                <tr>
                    <td><?= htmlspecialchars($line['reference'] ?: '-') ?></td>
                    <td><?= htmlspecialchars($line['designation']) ?></td>
                    <td class="text-end ordered" data-ordered="<?= htmlspecialchars((string)(int)round($ordered)) ?>"><?= $formatQty($ordered) ?></td>
                    <td class="text-end already" data-already="<?= htmlspecialchars((string)(int)round($received)) ?>"><?= $formatQty($received) ?></td>
                    <td style="width: 160px;">
                        <input type="number"
                               step="1"
                               min="0"
                               max="<?= htmlspecialchars((string)(int)round($remaining)) ?>"
                               name="quantite_reception[<?= (int)$line['id'] ?>]"
                               class="form-control form-control-sm text-end received-input"
                               value="0"
                               <?= !$canReceive ? 'disabled' : '' ?>>
                    </td>
                    <td class="text-end remaining"><?= $formatQty($remaining) ?></td>
                    <td>
                        <?php if ($hasArticle): ?>
                            <span class="badge bg-success">Stock mis à jour</span>
                        <?php else: ?>
                            <span class="badge bg-warning text-dark">Article libre — pas de stock</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="alert alert-light border mt-3 mb-0">
        Une ligne sans article lié peut être réceptionnée administrativement, mais elle ne modifiera pas le stock.
    </div>

    <div class="d-flex justify-content-end gap-2 mt-4">
        <a href="index.php?page=commandes_fournisseurs_show&id=<?= (int)$commande['id'] ?>" class="btn btn-darlink-outline-secondary">Annuler</a>
        <button type="submit" class="btn darlink-btn-primary" <?= !$canReceive ? 'disabled' : '' ?>>Enregistrer la réception</button>
    </div>
</form>

<script>
(function () {
    function num(value) { return parseFloat(String(value || '0').replace(',', '.')) || 0; }
    function fmt(value) { return new Intl.NumberFormat('fr-FR', {maximumFractionDigits: 3}).format(value || 0); }
    function recalcRow(row) {
        const ordered = num(row.querySelector('.ordered').dataset.ordered);
        const already = num(row.querySelector('.already').dataset.already);
        const delivered = num(row.querySelector('.received-input').value);
        row.querySelector('.remaining').textContent = fmt(Math.max(0, ordered - already - delivered));
    }
    document.querySelectorAll('#receiveTable tbody tr').forEach(function (row) {
        const input = row.querySelector('.received-input');
        if (input) { input.addEventListener('input', function () { recalcRow(row); }); }
    });
    const fillAll = document.getElementById('fillAll');
    if (fillAll) {
        fillAll.addEventListener('click', function () {
            document.querySelectorAll('#receiveTable tbody tr').forEach(function (row) {
                const input = row.querySelector('.received-input');
                if (!input || input.disabled) { return; }
                const ordered = num(row.querySelector('.ordered').dataset.ordered);
                const already = num(row.querySelector('.already').dataset.already);
                input.value = Math.max(0, ordered - already);
                recalcRow(row);
            });
        });
    }
})();
</script>
