<?php
$editing=!empty($facture['id']); $lines=$lignes??[];
if (!$lines) $lines=[['article_id'=>0,'type_ligne'=>'article','reference'=>'','designation'=>'','quantite'=>1,'prix_achat_ht'=>0,'taux_tva'=>20]];
?>
<div class="d-flex justify-content-between align-items-center mb-4"><div><h1 class="darlink-title mb-1"><?= $editing ? 'Modifier la facture fournisseur' : 'Enregistrement d’une facture fournisseur reçue' ?></h1><p class="text-muted mb-0"><?php if (!$editing && !empty($commande)): ?>Facture issue de la commande <strong><?= htmlspecialchars((string)$commande['numero']) ?></strong> — fournisseur et lignes réceptionnées préremplis.<?php else: ?>Saisie des articles, frais et justificatif fournisseur.<?php endif; ?></p></div><a href="index.php?page=<?= !empty($commande) ? 'commandes_fournisseurs_finalisation' : 'factures_fournisseurs' ?>" class="btn btn-outline-secondary">← Retour</a></div>
<form method="post" enctype="multipart/form-data" action="index.php?page=<?= $editing?'factures_fournisseurs_update':'factures_fournisseurs_store' ?>" class="darlink-card p-4">
<?php if($editing): ?><input type="hidden" name="id" value="<?= (int)$facture['id'] ?>"><?php endif; ?>
<input type="hidden" name="commande_fournisseur_id" value="<?= (int)($facture['commande_fournisseur_id']??0) ?>">
<div class="row g-3">
<div class="col-md-4"><label class="form-label">Numéro interne</label><input class="form-control" value="<?= htmlspecialchars($facture['numero_interne']) ?>" readonly></div>
<div class="col-md-4"><label class="form-label">Fournisseur *</label><select name="fournisseur_id" class="form-select" required><option value="">Sélectionner…</option><?php foreach($fournisseurs as $f): ?><option value="<?= (int)$f['id'] ?>" <?= (int)$facture['fournisseur_id']===(int)$f['id']?'selected':'' ?>><?= htmlspecialchars($f['raison_sociale']) ?></option><?php endforeach; ?></select></div>
<div class="col-md-4"><label class="form-label">N° facture fournisseur *</label><input name="numero_facture_fournisseur" class="form-control" value="<?= htmlspecialchars($facture['numero_facture_fournisseur']) ?>" required></div>
<div class="col-md-3"><label class="form-label">Date facture *</label><input type="date" name="date_facture" class="form-control" value="<?= htmlspecialchars($facture['date_facture']) ?>" required></div>
<div class="col-md-3"><label class="form-label">Échéance</label><input type="date" name="date_echeance" class="form-control" value="<?= htmlspecialchars($facture['date_echeance']??'') ?>"></div>
<div class="col-md-6"><label class="form-label">Justificatif (PDF, JPG, PNG — 10 Mo max.)</label><input type="file" name="justificatif" class="form-control" accept=".pdf,.jpg,.jpeg,.png"><?php if(!empty($facture['justificatif_nom'])):?><div class="form-text">Actuel : <?= htmlspecialchars($facture['justificatif_nom']) ?></div><?php endif;?></div>
</div><hr class="my-4">
<div class="d-flex justify-content-between align-items-center mb-2"><h5 class="mb-0">Articles et frais</h5><button type="button" id="add-line" class="btn btn-sm btn-outline-primary">+ Ajouter une ligne</button></div>
<div class="table-responsive"><table class="table align-middle" id="lines"><thead><tr><th>Type</th><th>Article / désignation</th><th>Référence</th><th>Qté</th><th>Prix HT</th><th>TVA %</th><th class="text-end">Total TTC</th><th></th></tr></thead><tbody>
<?php foreach($lines as $line): ?><tr><td><select name="ligne_type[]" class="form-select line-type"><option value="article" <?= ($line['type_ligne']??'')==='article'?'selected':'' ?>>Article</option><option value="frais" <?= ($line['type_ligne']??'')==='frais'?'selected':'' ?>>Frais</option></select></td><td><input type="hidden" name="ligne_article_id[]" value="<?= (int)($line['article_id']??0) ?>"><input name="ligne_designation[]" class="form-control" value="<?= htmlspecialchars($line['designation']??'') ?>" required></td><td><input name="ligne_reference[]" class="form-control" value="<?= htmlspecialchars($line['reference']??'') ?>"></td><td><input type="number" step="0.001" min="0.001" name="ligne_quantite[]" class="form-control calc" value="<?= htmlspecialchars((string)($line['quantite']??1)) ?>"></td><td><input type="number" step="0.01" min="0" name="ligne_prix_ht[]" class="form-control calc" value="<?= htmlspecialchars((string)($line['prix_achat_ht']??0)) ?>"></td><td><input type="number" step="0.01" min="0" name="ligne_tva[]" class="form-control calc" value="<?= htmlspecialchars((string)($line['taux_tva']??20)) ?>"></td><td class="text-end fw-bold line-total">0,00</td><td><button type="button" class="btn btn-sm btn-outline-danger remove-line">×</button></td></tr><?php endforeach; ?>
</tbody></table></div>
<div class="row justify-content-end"><div class="col-md-4"><div class="d-flex justify-content-between"><span>Total HT</span><strong id="total-ht">0,00</strong></div><div class="d-flex justify-content-between"><span>TVA</span><strong id="total-tva">0,00</strong></div><div class="d-flex justify-content-between h5 mt-2"><span>Total TTC</span><strong id="total-ttc">0,00</strong></div></div></div>
<div class="mt-3"><label class="form-label">Observations</label><textarea name="observations" class="form-control" rows="3"><?= htmlspecialchars($facture['observations']??'') ?></textarea></div>
<div class="d-flex justify-content-end gap-2 mt-4"><a href="index.php?page=factures_fournisseurs" class="btn btn-outline-secondary">Annuler</a><button type="submit" class="btn darlink-btn-primary"><?= $editing?'Enregistrer les modifications':'Enregistrer la facture fournisseur reçue' ?></button></div>
</form>
<script>
(()=>{const body=document.querySelector('#lines tbody');function calc(){let h=0,v=0;body.querySelectorAll('tr').forEach(r=>{const x=r.querySelectorAll('.calc'),q=+x[0].value||0,p=+x[1].value||0,t=+x[2].value||0,ht=q*p,tv=ht*t/100;h+=ht;v+=tv;r.querySelector('.line-total').textContent=(ht+tv).toFixed(2).replace('.',',')});document.querySelector('#total-ht').textContent=h.toFixed(2).replace('.',',');document.querySelector('#total-tva').textContent=v.toFixed(2).replace('.',',');document.querySelector('#total-ttc').textContent=(h+v).toFixed(2).replace('.',',')}body.addEventListener('input',calc);body.addEventListener('click',e=>{if(e.target.classList.contains('remove-line')&&body.rows.length>1){e.target.closest('tr').remove();calc()}});document.querySelector('#add-line').onclick=()=>{const r=body.rows[0].cloneNode(true);r.querySelectorAll('input').forEach(i=>i.value=i.type==='hidden'?'0':(i.name.includes('quantite')?'1':i.name.includes('tva')?'20':''));r.querySelector('.line-total').textContent='0,00';body.appendChild(r)};calc()})();
</script>
