<?php
$isEdit = ($mode ?? 'create') === 'edit';
$isDuplicate = ($mode ?? '') === 'duplicate';
$action = $isEdit ? 'articles_update' : 'articles_store';
function article_value(array $article, string $key, string $default = ''): string { return htmlspecialchars((string)($article[$key] ?? $default)); }
function article_invalid(array $errors, string $key): string { return isset($errors[$key]) ? ' is-invalid' : ''; }
function article_error(array $errors, string $key): string { return isset($errors[$key]) ? '<div class="invalid-feedback d-block">'.htmlspecialchars((string)$errors[$key]).'</div>' : ''; }
?>
<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><?= $isEdit ? 'Modifier l’article' : ($isDuplicate ? 'Dupliquer l’article' : 'Nouvel article') ?></h1>
        <p class="text-muted mb-0">Création et gestion manuelle d’un article.</p>
    </div>
    <a href="index.php?page=articles" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> Retour</a>
</div>
<form method="post" action="index.php?page=<?= $action ?>" class="darlink-form-card" id="article-form" novalidate>
    <?php if ($isEdit): ?><input type="hidden" name="id" value="<?= (int)($article['id'] ?? 0) ?>"><?php endif; ?>
    <div class="darlink-form-header d-flex justify-content-between align-items-center">
        <div><div class="text-muted small">Référence article</div><div class="h4 mb-0"><?= article_value($article, 'reference', 'Nouvelle référence') ?: 'Nouvelle référence' ?></div></div>
        <span class="darlink-badge darlink-badge-primary"><?= $isDuplicate ? 'Duplication' : 'Article' ?></span>
    </div>
    <div class="darlink-form-body">
        <?php if ($isDuplicate): ?><div class="alert alert-info">Saisissez une nouvelle référence unique avant d’enregistrer la copie.</div><?php endif; ?>
        <div class="darlink-section-title">Informations générales</div>
        <div class="row g-3">
            <div class="col-md-4 darlink-form-group"><label class="darlink-label">Référence *</label><input name="reference" maxlength="50" class="darlink-input<?= article_invalid($errors,'reference') ?>" value="<?= article_value($article,'reference') ?>" required autofocus><?= article_error($errors,'reference') ?></div>
            <div class="col-md-8 darlink-form-group"><label class="darlink-label">Désignation *</label><input name="designation" maxlength="255" class="darlink-input<?= article_invalid($errors,'designation') ?>" value="<?= article_value($article,'designation') ?>" required><?= article_error($errors,'designation') ?></div>
            <div class="col-md-4 darlink-form-group"><label class="darlink-label">Famille</label><select name="famille_id" class="darlink-select"><option value="">Aucune</option><?php foreach($familles as $item): ?><option value="<?= (int)$item['id'] ?>" <?= (string)($article['famille_id']??'')===(string)$item['id']?'selected':'' ?>><?= htmlspecialchars($item['libelle']) ?><?= empty($item['actif'])?' (inactive)':'' ?></option><?php endforeach; ?></select></div>
            <div class="col-md-4 darlink-form-group"><label class="darlink-label">Marque</label><select name="marque_id" class="darlink-select"><option value="">Aucune</option><?php foreach($marques as $item): ?><option value="<?= (int)$item['id'] ?>" <?= (string)($article['marque_id']??'')===(string)$item['id']?'selected':'' ?>><?= htmlspecialchars($item['libelle']) ?><?= empty($item['actif'])?' (inactive)':'' ?></option><?php endforeach; ?></select></div>
            <div class="col-md-4 darlink-form-group"><label class="darlink-label">Unité</label><select name="unite" class="darlink-select"><option value="<?= article_value($article,'unite','unité') ?>"><?= article_value($article,'unite','unité') ?></option><?php foreach($unites as $item): if((string)$item['libelle']===(string)($article['unite']??'unité')) continue; ?><option value="<?= htmlspecialchars($item['libelle']) ?>"><?= htmlspecialchars($item['libelle']) ?></option><?php endforeach; ?></select></div>
            <div class="col-md-6 darlink-form-group"><label class="darlink-label">Conditionnement</label><input name="conditionnement" maxlength="100" class="darlink-input" value="<?= article_value($article,'conditionnement') ?>" placeholder="Carton de 12, bidon 5 L..."></div>
            <div class="col-md-6 darlink-form-group"><label class="darlink-label">Statut</label><div class="form-check form-switch mt-2"><input class="form-check-input" type="checkbox" name="actif" value="1" id="actif" <?= !isset($article['actif']) || !empty($article['actif'])?'checked':'' ?>><label class="form-check-label" for="actif">Article actif</label></div></div>
        </div>
        <div class="darlink-section-title mt-4">Tarification</div>
        <div class="row g-3">
            <div class="col-md-3 darlink-form-group"><label class="darlink-label">Prix d’achat HT</label><input type="number" min="0" step="0.01" id="prix_achat_ht" name="prix_achat_ht" class="darlink-input text-end<?= article_invalid($errors,'prix_achat_ht') ?>" value="<?= article_value($article,'prix_achat_ht','0.00') ?>"><?= article_error($errors,'prix_achat_ht') ?></div>
            <div class="col-md-2 darlink-form-group"><label class="darlink-label">Coefficient</label><input type="number" min="0" step="0.001" id="coefficient" name="coefficient" class="darlink-input text-end<?= article_invalid($errors,'coefficient') ?>" value="<?= article_value($article,'coefficient','1.000') ?>"><?= article_error($errors,'coefficient') ?></div>
            <div class="col-md-3 darlink-form-group"><label class="darlink-label">Prix de vente HT</label><input type="number" min="0" step="0.01" id="prix_vente_ht" name="prix_vente_ht" class="darlink-input text-end<?= article_invalid($errors,'prix_vente_ht') ?>" value="<?= article_value($article,'prix_vente_ht','0.00') ?>"><?= article_error($errors,'prix_vente_ht') ?></div>
            <div class="col-md-2 darlink-form-group"><label class="darlink-label">TVA %</label><input type="number" min="0" max="100" step="0.01" id="taux_tva" name="taux_tva" class="darlink-input text-end<?= article_invalid($errors,'taux_tva') ?>" value="<?= article_value($article,'taux_tva','20.00') ?>"><?= article_error($errors,'taux_tva') ?></div>
            <div class="col-md-2 darlink-form-group"><label class="darlink-label">Vente TTC</label><input id="prix_vente_ttc_preview" class="darlink-input text-end" readonly></div>
            <div class="col-md-3 darlink-form-group"><label class="darlink-label">Marge € / DH</label><input id="marge_preview" class="darlink-input text-end" readonly></div>
            <div class="col-md-3 darlink-form-group"><label class="darlink-label">Marge %</label><input id="marge_pct_preview" class="darlink-input text-end" readonly></div>
            <div class="col-md-3 darlink-form-group"><label class="darlink-label">Stock minimum</label><input type="number" min="0" step="0.01" name="stock_minimum" class="darlink-input text-end<?= article_invalid($errors,'stock_minimum') ?>" value="<?= article_value($article,'stock_minimum','0.00') ?>"><?= article_error($errors,'stock_minimum') ?></div>
        </div>
        <div class="darlink-section-title mt-4">Fournisseur principal</div>
        <div class="row g-3">
            <div class="col-md-6 darlink-form-group"><label class="darlink-label">Fournisseur</label><select name="fournisseur_principal_id" class="darlink-select"><option value="">Aucun</option><?php foreach($fournisseurs as $f): ?><option value="<?= (int)$f['id'] ?>" <?= (string)($article['fournisseur_principal_id']??'')===(string)$f['id']?'selected':'' ?>><?= htmlspecialchars(($f['code_fournisseur']??'').' — '.($f['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" maxlength="100" class="darlink-input" value="<?= article_value($article,'reference_fournisseur') ?>"></div>
        </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 pa=document.getElementById('prix_achat_ht'),coef=document.getElementById('coefficient'),pv=document.getElementById('prix_vente_ht'),tva=document.getElementById('taux_tva'),ttc=document.getElementById('prix_vente_ttc_preview'),m=document.getElementById('marge_preview'),mp=document.getElementById('marge_pct_preview');function n(x){return parseFloat(String(x?.value||'').replace(',','.'))||0}function refresh(){const a=n(pa),v=n(pv),t=n(tva),margin=v-a;ttc.value=(v*(1+t/100)).toFixed(2);m.value=margin.toFixed(2);mp.value=(v>0?margin/v*100:0).toFixed(2)}function vente(){const a=n(pa),c=n(coef);if(a>0&&c>0)pv.value=(a*c).toFixed(2);refresh()}function coefficient(){const a=n(pa),v=n(pv);if(a>0&&v>0)coef.value=(v/a).toFixed(3);refresh()}pa.addEventListener('input',vente);coef.addEventListener('input',vente);pv.addEventListener('input',coefficient);tva.addEventListener('input',refresh);document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();document.getElementById('article-form').requestSubmit()}});refresh()})();
</script>
