<?php
$format = static fn($value): string => htmlspecialchars((string)($value ?? ''));

$analytics = $analytics ?? [
    'ca' => 0,
    'quantite_vendue' => 0,
    'nb_factures' => 0,
    'derniere_vente' => null,
    'prix_moyen_vente' => 0,
    'marge_totale' => 0,
];

$prixAchat = (float)($article['prix_achat_ht'] ?? 0);
$prixVente = (float)($article['prix_vente_ht'] ?? 0);
$tva = (float)($article['taux_tva'] ?? 0);
$prixTtc = (float)($article['prix_vente_ttc'] ?? ($prixVente * (1 + $tva / 100)));
$margeDh = (float)($article['marge_dh'] ?? ($prixVente - $prixAchat));
$margePct = (float)($article['marge_pourcentage'] ?? ($prixVente > 0 ? ($margeDh / $prixVente) * 100 : 0));
$stock = (float)($article['quantite'] ?? 0);
$stockMini = (float)($article['stock_minimum'] ?? 0);
$valeurStock = (float)($article['valeur_stock'] ?? ($stock * $prixAchat));

$etatLabel = 'OK';
$etatClass = 'darlink-badge-success';

if ($stock <= 0) {
    $etatLabel = 'Rupture';
    $etatClass = 'darlink-badge-danger';
} elseif ($stockMini > 0 && $stock <= $stockMini) {
    $etatLabel = 'Alerte';
    $etatClass = 'darlink-badge-warning';
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1"><i class="bi bi-box-seam me-2"></i>Article 360°</h1>
        <p class="text-muted mb-0"><?= htmlspecialchars($article['reference'] . ' — ' . $article['designation']) ?></p>
    </div>

    <div class="d-flex gap-2 flex-wrap">
        <a href="index.php?page=commandes_fournisseurs_historique&article_id=<?= (int)$article['id'] ?>" class="btn btn-outline-primary"><i class="bi bi-clock-history me-1"></i> Historique achats</a>
        <a href="index.php?page=stock_show&id=<?= (int)$article['id'] ?>" class="btn btn-outline-success"><i class="bi bi-boxes me-1"></i> Stock</a>
        <a href="index.php?page=articles_edit&id=<?= (int)$article['id'] ?>" class="btn darlink-btn-primary me-2"><i class="bi bi-pencil me-1"></i> Modifier</a>
    <a href="index.php?page=articles" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> Retour</a>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3"><div class="darlink-stat"><span>Prix achat HT</span><strong><?= number_format($prixAchat, 2, ',', ' ') ?> MAD</strong></div></div>
    <div class="col-md-3"><div class="darlink-stat"><span>Prix vente HT</span><strong><?= number_format($prixVente, 2, ',', ' ') ?> MAD</strong></div></div>
    <div class="col-md-3"><div class="darlink-stat"><span>Marge</span><strong><?= number_format($margePct, 2, ',', ' ') ?> %</strong></div></div>
    <div class="col-md-3"><div class="darlink-stat"><span>Stock</span><strong><?= number_format($stock, 0, ',', ' ') ?> <span class="darlink-badge <?= $etatClass ?> ms-2"><?= $etatLabel ?></span></strong></div></div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-2"><div class="darlink-stat"><span>CA généré</span><strong><?= number_format((float)$analytics['ca'], 2, ',', ' ') ?> MAD</strong></div></div>
    <div class="col-md-2"><div class="darlink-stat"><span>Qté vendue</span><strong><?= number_format((float)$analytics['quantite_vendue'], 0, ',', ' ') ?></strong></div></div>
    <div class="col-md-2"><div class="darlink-stat"><span>Factures</span><strong><?= (int)$analytics['nb_factures'] ?></strong></div></div>
    <div class="col-md-2"><div class="darlink-stat"><span>Dernière vente</span><strong><?= $analytics['derniere_vente'] ?: '-' ?></strong></div></div>
    <div class="col-md-2"><div class="darlink-stat"><span>Prix moyen</span><strong><?= number_format((float)$analytics['prix_moyen_vente'], 2, ',', ' ') ?> MAD</strong></div></div>
    <div class="col-md-2"><div class="darlink-stat"><span>Marge totale</span><strong><?= number_format((float)$analytics['marge_totale'], 2, ',', ' ') ?> MAD</strong></div></div>
</div>

<div class="darlink-card darlink-card-body mb-4">
    <h2 class="h5 mb-4"><i class="bi bi-info-circle me-2"></i>Informations article</h2>
    <div class="row">
        <div class="col-lg-6">
            <table class="table table-borderless mb-0">
                <tr><th width="42%">Référence</th><td><?= htmlspecialchars($article['reference']) ?></td></tr>
                <tr><th>Désignation</th><td><?= htmlspecialchars($article['designation']) ?></td></tr>
                <tr><th>Unité</th><td><?= htmlspecialchars($article['unite'] ?? '-') ?></td></tr>
                <tr><th>Référence fournisseur</th><td><?= htmlspecialchars($article['reference_fournisseur'] ?? '-') ?></td></tr>
                <tr><th>Dernier achat</th><td><?= htmlspecialchars($article['date_dernier_achat'] ?? '-') ?></td></tr>
            </table>
        </div>
        <div class="col-lg-6">
            <table class="table table-borderless mb-0">
                <tr><th width="42%">Prix achat HT</th><td><?= number_format($prixAchat, 2, ',', ' ') ?> MAD</td></tr>
                <tr><th>Coefficient</th><td><?= number_format((float)($article['coefficient'] ?? 0), 3, ',', ' ') ?></td></tr>
                <tr><th>Prix vente HT</th><td><?= number_format($prixVente, 2, ',', ' ') ?> MAD</td></tr>
                <tr><th>Prix vente TTC</th><td><?= number_format($prixTtc, 2, ',', ' ') ?> MAD</td></tr>
                <tr><th>Marge</th><td><span class="fw-semibold"><?= number_format($margeDh, 2, ',', ' ') ?> MAD</span><span class="darlink-badge darlink-badge-light ms-2"><?= number_format($margePct, 2, ',', ' ') ?> %</span></td></tr>
            </table>
        </div>
    </div>
</div>

<div class="darlink-card darlink-card-body mb-4">
    <h2 class="h5 mb-4"><i class="bi bi-boxes me-2"></i>Stock et valorisation</h2>
    <div class="row">
        <div class="col-lg-6">
            <table class="table table-borderless mb-0">
                <tr><th width="42%">Stock actuel</th><td class="fw-semibold"><?= number_format($stock, 0, ',', ' ') ?> <?= htmlspecialchars($article['unite'] ?? '') ?></td></tr>
                <tr><th>Stock minimum</th><td><?= number_format($stockMini, 0, ',', ' ') ?></td></tr>
                <tr><th>État</th><td><span class="darlink-badge <?= $etatClass ?>"><?= $etatLabel ?></span></td></tr>
            </table>
        </div>
        <div class="col-lg-6">
            <table class="table table-borderless mb-0">
                <tr><th width="42%">Valeur du stock</th><td class="fw-bold text-success"><?= number_format($valeurStock, 2, ',', ' ') ?> MAD</td></tr>
                <tr><th>Dernier prix achat</th><td><?= number_format((float)($article['dernier_prix_achat_ht'] ?? 0), 2, ',', ' ') ?> MAD</td></tr>
                <tr><th>Prix fournisseur</th><td><?= number_format((float)($article['prix_achat_fournisseur_ht'] ?? 0), 2, ',', ' ') ?> MAD</td></tr>
            </table>
        </div>
    </div>
</div>

<form method="post" action="index.php?page=articles_achats_update" class="darlink-form-card">
    <input type="hidden" name="id" value="<?= (int)$article['id'] ?>">

    <div class="darlink-form-header d-flex justify-content-between align-items-center">
        <div><div class="text-muted small">Mise à jour achats</div><div class="h4 mb-0"><?= htmlspecialchars($article['reference']) ?></div></div>
        <span class="darlink-badge darlink-badge-primary">Article 360°</span>
    </div>

    <div class="darlink-form-body">
        <div class="darlink-section-title">Approvisionnement</div>
        <div class="row g-3">
            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">Fournisseur principal</label>
                <select name="fournisseur_principal_id" class="darlink-select">
                    <option value="">Aucun fournisseur lié</option>
                    <?php foreach ($fournisseurs as $fournisseur): ?>
                        <option value="<?= (int)$fournisseur['id'] ?>" <?= (int)($article['fournisseur_principal_id'] ?? 0) === (int)$fournisseur['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($fournisseur['code_fournisseur'] . ' — ' . $fournisseur['raison_sociale']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-6 darlink-form-group">
                <label class="darlink-label">Référence fournisseur</label>
                <input name="reference_fournisseur" class="darlink-input" value="<?= $format($article['reference_fournisseur'] ?? '') ?>" placeholder="Référence utilisée par le fournisseur">
            </div>
        </div>

        <div class="darlink-section-title mt-4">Prix et marge</div>
        <div class="row g-3">
            <div class="col-md-4 darlink-form-group">
                <label class="darlink-label">Nouveau prix d’achat HT</label>
                <input type="number" step="0.01" min="0" id="prix_achat_ht" name="prix_achat_ht" class="darlink-input text-end" value="<?= $format($article['prix_achat_ht'] ?? $article['prix_achat_fournisseur_ht'] ?? '') ?>">
                <div class="form-text">Remplace le prix d’achat de l’article et sert aux commandes fournisseurs.</div>
            </div>
            <div class="col-md-4 darlink-form-group">
                <label class="darlink-label">Coefficient</label>
                <input type="number" step="0.001" min="0" id="coefficient" name="coefficient" class="darlink-input text-end" value="<?= $format($article['coefficient'] ?? '') ?>">
                <div class="form-text">Prix vente HT = achat HT × coefficient.</div>
            </div>
            <div class="col-md-4 darlink-form-group">
                <label class="darlink-label">Prix de vente HT</label>
                <input type="number" step="0.01" min="0" id="prix_vente_ht" name="prix_vente_ht" class="darlink-input text-end" value="<?= $format($article['prix_vente_ht'] ?? '') ?>">
                <div class="form-text">Si tu modifies ce prix, le coefficient se recalcule.</div>
            </div>
            <div class="col-md-4 darlink-form-group">
                <label class="darlink-label">TVA %</label>
                <input type="number" step="0.01" min="0" id="taux_tva" name="taux_tva" class="darlink-input text-end" value="<?= $format($article['taux_tva'] ?? 20) ?>">
            </div>
            <div class="col-md-4 darlink-form-group">
                <label class="darlink-label">Prix de vente TTC indicatif</label>
                <input type="text" id="prix_vente_ttc_preview" class="darlink-input text-end" value="" readonly>
            </div>
            <div class="col-md-4 darlink-form-group">
                <label class="darlink-label">Date dernier achat</label>
                <input type="date" name="date_dernier_achat" class="darlink-input" value="<?= $format($article['date_dernier_achat'] ?? '') ?>">
            </div>
        </div>

        <div class="alert alert-info mt-4 mb-0">Une commande fournisseur proposera en priorité les articles liés au fournisseur choisi. Le nouveau prix d’achat met aussi à jour la fiche article.</div>
    </div>

    <div class="darlink-form-actions">
        <a href="index.php?page=articles" class="btn btn-outline-secondary">Annuler</a>
        <button type="submit" class="btn darlink-btn-primary"><i class="bi bi-check-lg me-1"></i> Enregistrer</button>
    </div>
</form>

<script>
(function () {
    const achat = document.getElementById('prix_achat_ht');
    const coef = document.getElementById('coefficient');
    const vente = document.getElementById('prix_vente_ht');
    const tva = document.getElementById('taux_tva');
    const ttc = document.getElementById('prix_vente_ttc_preview');

    function number(input) {
        if (!input) return 0;
        return parseFloat(String(input.value || '').replace(',', '.')) || 0;
    }

    function setValue(input, value, digits) {
        if (!input || !isFinite(value)) return;
        input.value = value > 0 ? value.toFixed(digits) : '';
    }

    function refreshTtc() {
        const pv = number(vente);
        const taux = number(tva) || 0;
        const value = pv * (1 + taux / 100);
        if (ttc) ttc.value = value > 0 ? value.toFixed(2) : '';
    }

    function recalcVente() {
        const pa = number(achat);
        const c = number(coef);
        if (pa > 0 && c > 0) setValue(vente, pa * c, 2);
        refreshTtc();
    }

    function recalcCoef() {
        const pa = number(achat);
        const pv = number(vente);
        if (pa > 0 && pv > 0) setValue(coef, pv / pa, 3);
        refreshTtc();
    }

    if (achat) achat.addEventListener('input', recalcVente);
    if (coef) coef.addEventListener('input', recalcVente);
    if (vente) vente.addEventListener('input', recalcCoef);
    if (tva) tva.addEventListener('input', refreshTtc);

    refreshTtc();
})();
</script>
