<?php
$isEdit = ($mode ?? 'create') === 'edit';
$action = $isEdit ? 'commandes_fournisseurs_update' : 'commandes_fournisseurs_store';
$formatLineValue = static fn($value): string => htmlspecialchars((string)$value);
$formatQtyInput = static fn($value): string => htmlspecialchars((string)(int)round((float)$value));
$lineRows = $lines ?? [];
if (empty($lineRows)) {
    $lineRows = [[
        'article_id' => '',
        'reference' => '',
        'designation' => '',
        'quantite' => 1,
        'prix_achat_ht' => 0,
        'taux_tva' => 20,
    ]];
}
function cf_error(array $errors, string $key): string {
    return isset($errors[$key]) ? '<div class="invalid-feedback d-block">' . htmlspecialchars($errors[$key]) . '</div>' : '';
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1"><?= $isEdit ? 'Modifier la commande fournisseur' : 'Nouvelle commande fournisseur' ?></h1>
        <p class="text-muted mb-0">Commande fournisseur — base du futur flux réception → stock.</p>
    </div>
    <a href="index.php?page=commandes_fournisseurs" class="btn btn-darlink-outline-secondary">← Retour à la liste</a>
</div>

<form method="post" action="index.php?page=<?= htmlspecialchars($action) ?>" class="darlink-card p-4" id="supplierOrderForm" novalidate>
    <?php if ($isEdit): ?>
        <input type="hidden" name="id" value="<?= (int)($commande['id'] ?? 0) ?>">
    <?php endif; ?>

    <div class="darlink-form-header mb-4">
        <div>
            <div class="text-muted small">Numéro de commande fournisseur</div>
            <div class="h4 mb-0"><?= htmlspecialchars((string)($commande['numero'] ?? '')) ?></div>
            <input type="hidden" name="numero" value="<?= htmlspecialchars((string)($commande['numero'] ?? '')) ?>">
        </div>
        <span class="badge-darlink badge-darlink-light">Phoenix P2.6.3b</span>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-md-5">
            <label class="form-label">Fournisseur *</label>
            <select name="fournisseur_id" id="supplierSelect" class="form-select form-darlink" required>
                <option value="">Sélectionner un fournisseur</option>
                <?php foreach ($fournisseurs as $fournisseur): ?>
                    <option value="<?= (int)$fournisseur['id'] ?>" <?= (int)($commande['fournisseur_id'] ?? 0) === (int)$fournisseur['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($fournisseur['code_fournisseur'] . ' — ' . $fournisseur['raison_sociale']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?= cf_error($errors, 'fournisseur_id') ?>
        </div>
        <div class="col-md-3">
            <label class="form-label">Date commande *</label>
            <input type="date" name="date_commande" class="form-control form-darlink" value="<?= htmlspecialchars((string)($commande['date_commande'] ?? date('Y-m-d'))) ?>" required>
            <?= cf_error($errors, 'date_commande') ?>
        </div>
        <div class="col-md-4">
            <label class="form-label">Livraison prévue</label>
            <input type="date" name="date_livraison_prevue" class="form-control form-darlink" value="<?= htmlspecialchars((string)($commande['date_livraison_prevue'] ?? '')) ?>">
        </div>
        <div class="col-md-5">
            <label class="form-label">Référence fournisseur</label>
            <input name="reference_fournisseur" class="form-control form-darlink" value="<?= htmlspecialchars((string)($commande['reference_fournisseur'] ?? '')) ?>" placeholder="N° devis fournisseur, référence interne...">
        </div>
        <div class="col-md-3">
            <label class="form-label">Statut</label>
            <select name="statut" class="form-select form-darlink">
                <?php foreach (['brouillon' => 'Brouillon', 'validée' => 'Validée', 'annulée' => 'Annulée'] as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= (string)($commande['statut'] ?? 'brouillon') === $value ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

    <div class="darlink-section-title">Articles commandés</div>
    <div class="table-responsive mb-3">
        <table class="table darlink-table align-middle" id="linesTable">
            <thead>
            <tr>
                <th style="width: 24%">Article</th>
                <th>Réf.</th>
                <th>Désignation</th>
                <th class="text-end">Qté.</th>
                <th class="text-end">Prix achat HT</th>
                <th class="text-end">TVA</th>
                <th class="text-end">Total HT</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($lineRows as $line): ?>
                <tr class="line-row">
                    <td>
                        <select name="article_id[]" class="form-select form-select-sm article-select">
                            <option value="">Article libre</option>
                            <?php foreach ($articles as $article): ?>
                                <option value="<?= (int)$article['id'] ?>"
                                        data-reference="<?= htmlspecialchars((string)$article['reference']) ?>"
                                        data-designation="<?= htmlspecialchars((string)$article['designation']) ?>"
                                        data-prix="<?= htmlspecialchars((string)($article['prix_achat_fournisseur_ht'] ?? $article['prix_achat_ht'])) ?>"
                                        data-tva="<?= htmlspecialchars((string)$article['taux_tva']) ?>"
                                        data-fournisseur="<?= (int)($article['fournisseur_principal_id'] ?? 0) ?>"
                                        data-ref-fournisseur="<?= htmlspecialchars((string)($article['reference_fournisseur'] ?? '')) ?>"
                                    <?= (int)($line['article_id'] ?? 0) === (int)$article['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($article['reference'] . ' — ' . $article['designation'] . (!empty($article['fournisseur_principal_nom']) ? ' (' . $article['fournisseur_principal_nom'] . ')' : '')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input name="reference[]" class="form-control form-control-sm reference-input" value="<?= $formatLineValue($line['reference'] ?? '') ?>"></td>
                    <td><input name="designation[]" class="form-control form-control-sm designation-input" value="<?= $formatLineValue($line['designation'] ?? '') ?>" required></td>
                    <td><input name="quantite[]" type="number" step="1" min="0" class="form-control form-control-sm text-end qty-input" value="<?= $formatQtyInput($line['quantite'] ?? 1) ?>"></td>
                    <td><input name="prix_achat_ht[]" type="number" step="0.01" min="0" class="form-control form-control-sm text-end price-input" value="<?= $formatLineValue($line['prix_achat_ht'] ?? 0) ?>"></td>
                    <td><input name="taux_tva[]" type="number" step="0.01" min="0" class="form-control form-control-sm text-end vat-input" value="<?= $formatLineValue($line['taux_tva'] ?? 20) ?>"></td>
                    <td class="text-end"><strong class="line-total">0,00 DH</strong></td>
                    <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger remove-line">×</button></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <button type="button" class="btn btn-outline-secondary mb-4" id="addLine">+ Ajouter une ligne</button>

    <div class="row g-3">
        <div class="col-md-8">
            <label class="form-label">Observations</label>
            <textarea name="observations" class="form-control form-darlink" rows="4" placeholder="Instructions de livraison, remarques fournisseur..."> <?= htmlspecialchars((string)($commande['observations'] ?? '')) ?></textarea>
        </div>
        <div class="col-md-4">
            <div class="darlink-card p-3 bg-light">
                <div class="d-flex justify-content-between mb-2"><span>Total HT</span><strong id="totalHt">0,00 DH</strong></div>
                <div class="d-flex justify-content-between mb-2"><span>TVA</span><strong id="totalTva">0,00 DH</strong></div>
                <hr>
                <div class="d-flex justify-content-between h5 mb-0"><span>Total TTC</span><strong id="totalTtc">0,00 DH</strong></div>
            </div>
        </div>
    </div>

    <div class="d-flex flex-column flex-md-row justify-content-end gap-2 mt-4">
        <a href="index.php?page=commandes_fournisseurs" class="btn btn-darlink-outline-secondary">Annuler</a>
        <button type="submit" class="btn darlink-btn-primary">Enregistrer</button>
    </div>
</form>

<script>
(function () {
    function money(value) {
        return new Intl.NumberFormat('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2}).format(value || 0) + ' DH';
    }
    function num(value) {
        return parseFloat(String(value || '0').replace(',', '.')) || 0;
    }
    function recalc() {
        let totalHt = 0;
        let totalTva = 0;
        document.querySelectorAll('#linesTable tbody tr').forEach(function (row) {
            const qty = num(row.querySelector('.qty-input').value);
            const price = num(row.querySelector('.price-input').value);
            const vat = num(row.querySelector('.vat-input').value);
            const ht = qty * price;
            const tva = ht * vat / 100;
            totalHt += ht;
            totalTva += tva;
            row.querySelector('.line-total').textContent = money(ht);
        });
        document.getElementById('totalHt').textContent = money(totalHt);
        document.getElementById('totalTva').textContent = money(totalTva);
        document.getElementById('totalTtc').textContent = money(totalHt + totalTva);
    }
    function selectedSupplierId() {
        const supplier = document.getElementById('supplierSelect');
        return supplier ? supplier.value : '';
    }
    function filterArticleOptions() {
        const supplierId = selectedSupplierId();
        const allSelects = document.querySelectorAll('.article-select');

        // Règle Phoenix P3.2.4 :
        // - si le fournisseur sélectionné possède au moins un article lié,
        //   on affiche uniquement ses articles ;
        // - sinon, on affiche tous les articles pour ne pas bloquer la saisie.
        let supplierHasLinkedArticles = false;
        if (supplierId) {
            allSelects.forEach(function (select) {
                Array.from(select.options).forEach(function (option) {
                    if (option.value && (option.dataset.fournisseur || '') === supplierId) {
                        supplierHasLinkedArticles = true;
                    }
                });
            });
        }

        allSelects.forEach(function (select) {
            Array.from(select.options).forEach(function (option) {
                if (!option.value) {
                    option.hidden = false;
                    return;
                }

                const optionSupplier = option.dataset.fournisseur || '';
                option.hidden = !!supplierId && supplierHasLinkedArticles && optionSupplier !== supplierId;
            });

            if (select.selectedOptions.length && select.selectedOptions[0].hidden) {
                select.value = '';
            }
        });
    }
    function bind(row) {
        row.querySelectorAll('input').forEach(function (input) { input.addEventListener('input', recalc); });
        row.querySelector('.article-select').addEventListener('change', function () {
            const option = this.options[this.selectedIndex];
            if (!this.value) { return; }
            row.querySelector('.reference-input').value = option.dataset.refFournisseur || option.dataset.reference || '';
            row.querySelector('.designation-input').value = option.dataset.designation || '';
            row.querySelector('.price-input').value = option.dataset.prix || '0';
            row.querySelector('.vat-input').value = option.dataset.tva || '20';
            filterArticleOptions();
            recalc();
        });
        row.querySelector('.remove-line').addEventListener('click', function () {
            if (document.querySelectorAll('#linesTable tbody tr').length > 1) {
                row.remove();
                filterArticleOptions();
            recalc();
            }
        });
    }
    document.querySelectorAll('#linesTable tbody tr').forEach(bind);
    const supplierSelect = document.getElementById('supplierSelect');
    if (supplierSelect) { supplierSelect.addEventListener('change', filterArticleOptions); }
    document.getElementById('addLine').addEventListener('click', function () {
        const tbody = document.querySelector('#linesTable tbody');
        const clone = tbody.querySelector('tr').cloneNode(true);
        clone.querySelectorAll('input').forEach(function (input) { input.value = input.classList.contains('qty-input') ? '1' : (input.classList.contains('vat-input') ? '20' : ''); });
        clone.querySelector('.article-select').value = '';
        clone.querySelector('.line-total').textContent = '0,00 DH';
        tbody.appendChild(clone);
        bind(clone);
        filterArticleOptions();
        recalc();
    });
    filterArticleOptions();
    recalc();
})();
</script>
