<?php
include __DIR__ . '/../../config/db.php';

$receptionId = $_GET['reception_id'] ?? null;
$produitsReception = [];

if ($receptionId) {
    $stmt = $conn->prepare("
        SELECT r.produit_id, p.nom, p.reference, r.quantite_recue, p.prix_achat
        FROM reception_lignes r
        INNER JOIN produits p ON p.id = r.produit_id
        WHERE r.reception_id = :rid
        ORDER BY p.nom ASC
    ");
    $stmt->execute([':rid' => $receptionId]);
    $produitsReception = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Depots et devises
$depots   = $conn->query("SELECT id, nom FROM depots ORDER BY nom ASC")->fetchAll(PDO::FETCH_ASSOC);
$devises  = $conn->query("SELECT id, code, symbole, taux_par_defaut FROM devises WHERE actif=1 ORDER BY code ASC")->fetchAll(PDO::FETCH_ASSOC);

$depotsOptionsHtml = '';
foreach ($depots as $d) {
    $depotsOptionsHtml .= '<option value="'.htmlspecialchars($d['id'], ENT_QUOTES, 'UTF-8').'">'.htmlspecialchars($d['nom'], ENT_QUOTES, 'UTF-8').'</option>';
}

$devisesOptionsHtml = '';
foreach ($devises as $dev) {
    $devisesOptionsHtml .= '<option value="'.htmlspecialchars($dev['id'], ENT_QUOTES, 'UTF-8').'" 
                              data-taux="'.htmlspecialchars($dev['taux_par_defaut'], ENT_QUOTES, 'UTF-8').'" 
                              data-code="'.htmlspecialchars($dev['code'], ENT_QUOTES, 'UTF-8').'" 
                              data-symbole="'.htmlspecialchars($dev['symbole'], ENT_QUOTES, 'UTF-8').'">'
                            .$dev['code'].' ('.$dev['symbole'].')</option>';
}
?>

<!-- Modal Ajouter Réception -->
<div class="modal fade" id="ajouterReceptionModal" tabindex="-1" aria-labelledby="ajouterReceptionLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <form id="formAjouterAchat" method="POST" action="/eaglesuite/api/achats/ajouter.php">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title" id="ajouterReceptionLabel">Ajouter un achat depuis réception</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <input type="hidden" name="commande_id">
        <input type="hidden" name="reception_id" value="<?= htmlspecialchars($receptionId) ?>">

        <div class="modal-body">
          <!-- Fournisseur / Date / Devise -->
          <div class="row g-3 mb-3">
            <div class="col-md-3">
              <label class="form-label">Fournisseur</label>
              <select name="fournisseur_id" class="form-control" required>
                <option value="">-- Sélectionner --</option>
                <?php
                  $fournisseurs = $conn->query("SELECT id, nom, exonere FROM fournisseurs ORDER BY nom ASC")->fetchAll(PDO::FETCH_ASSOC);
                  foreach ($fournisseurs as $f) {
                      echo '<option value="'.htmlspecialchars($f['id'], ENT_QUOTES, 'UTF-8').'" data-exonere="'.htmlspecialchars($f['exonere'], ENT_QUOTES, 'UTF-8').'">'
                          .htmlspecialchars($f['nom'], ENT_QUOTES, 'UTF-8').'</option>';
                  }
                ?>
              </select>
            </div>

            <div class="col-md-3">
              <label class="form-label">Date</label>
              <input type="datetime-local" name="date_achat" class="form-control" value="<?= date('Y-m-d\TH:i') ?>" required>
            </div>

            <div class="col-md-3">
              <label class="form-label">Devise</label>
              <select name="devise_id" id="deviseSelect" class="form-control" required>
                <?= $devisesOptionsHtml ?>
              </select>
            </div>

            <div class="col-md-3">
              <label class="form-label">Taux de change</label>
              <input type="number" step="0.0001" name="taux_change" id="tauxChange" class="form-control" readonly>
            </div>
          </div>

          <!-- Lignes produits préchargées depuis réception -->
          <div id="produitsContainer">
            <?php foreach($produitsReception as $index => $p): ?>
            <div class="row mb-2 align-items-center" id="ligneProduit<?= $index ?>">
              <div class="col-md-3">
                <input type="text" class="form-control" value="<?= htmlspecialchars($p['nom'] . ($p['reference'] ? ' (' . $p['reference'] . ')' : '')) ?>" readonly>
                <input type="hidden" name="produits[<?= $index ?>][id]" value="<?= $p['produit_id'] ?>">
              </div>
              <div class="col-md-2">
                <select name="produits[<?= $index ?>][depot_id]" class="form-control depotSelect">
                  <?= $depotsOptionsHtml ?>
                </select>
              </div>
              <div class="col-md-1">
                <input type="number" name="produits[<?= $index ?>][quantite]" class="form-control quantiteInput" value="<?= $p['quantite_recue'] ?>" readonly>
              </div>
              <div class="col-md-2">
                <input type="number" name="produits[<?= $index ?>][prix_unitaire]" class="form-control prixInput" value="<?= $p['prix_achat'] ?>" readonly>
              </div>
              <div class="col-md-2">
                <input type="text" class="form-control sousTotal" value="<?= $p['quantite_recue'] * $p['prix_achat'] ?>" readonly>
              </div>
              <div class="col-auto">
                <span class="badge bg-info">Stock : -</span>
              </div>
            </div>
            <?php endforeach; ?>
          </div>

          <!-- Totaux -->
          <div class="row g-3 align-items-end mt-3">
            <div class="col-md-3">
              <label>Total HT</label>
              <input type="text" id="totalBrutInput" class="form-control" readonly value="0">
            </div>
            <div class="col-md-3">
              <label>Taxe</label>
              <input type="text" id="taxe" name="taxe" class="form-control" readonly>
            </div>
            <div class="col-md-3">
              <label>Remise (%)</label>
              <input type="number" id="remise" name="remise" class="form-control" value="0" min="0" step="0.01" oninput="calculerTotal()">
            </div>
            <div class="col-md-3">
              <label>Total TTC</label>
              <input type="text" id="totalTTCNetInput" class="form-control" readonly value="0">
              <input type="hidden" id="hiddenTotalDevise" name="total_devise" value="0">
              <input type="hidden" id="hiddenTotalCFA" name="total_cfa" value="0">
            </div>
          </div>

          <!-- Paiement -->
          <div class="row g-3 align-items-end mt-3">
            <div class="col-md-3">
              <label>Montant versé</label>
              <input type="number" id="montantVerse" name="montant_verse" class="form-control" value="0" min="0" step="0.01" oninput="calculerReste()">
            </div>
            <div class="col-md-3">
              <label>Reste à payer</label>
              <input type="text" id="resteAPayer" class="form-control is-invalid" readonly value="0">
            </div>
            <div class="col-md-3">
              <label>Mode Paiement</label>
              <select name="mode_paiement" class="form-control" required>
                <option value="">-- Sélectionner --</option>
                <?php
                  $mode_paiement = $conn->query("SELECT id, code, libelle FROM modes_paiement ORDER BY libelle ASC")->fetchAll(PDO::FETCH_ASSOC);
                  foreach ($mode_paiement as $mp) {
                      echo '<option value="'.htmlspecialchars($mp['id'], ENT_QUOTES, 'UTF-8').'">' .htmlspecialchars($mp['libelle'], ENT_QUOTES, 'UTF-8').'</option>';
                  }
                ?>
              </select>
            </div>
          </div>

          <input type="hidden" name="statut" id="statutAchat" value="Payé">
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Enregistrer</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php include __DIR__ . "/../../includes/layout_end.php"; ?>

<script>
function ouvrirModalAchat(receptionId, commandeId) {

    const modalEl = document.getElementById('ajouterReceptionModal');
    if (!modalEl) {
        console.error("Modal introuvable");
        return;
    }

    // Injecter les IDs
    modalEl.querySelector('input[name="reception_id"]').value = receptionId;
    modalEl.querySelector('input[name="commande_id"]').value = commandeId;

    // Ouvrir modal Bootstrap
    const modal = new bootstrap.Modal(modalEl, {
        backdrop: 'static',
        keyboard: false
    });
    modal.show();

    // Recalculer les totaux
    document.querySelectorAll('.sousTotal').forEach((_, i) => calculerLigne(i));
    calculerTotal();
}

// -------- Calcul lignes / totaux / reste --------
function calculerLigne(index){
    const ligne = document.getElementById('ligneProduit'+index);
    if(!ligne) return;
    const q = parseFloat(ligne.querySelector('.quantiteInput')?.value||0);
    const prix = parseFloat(ligne.querySelector('.prixInput')?.value||0);
    const st = ligne.querySelector('.sousTotal');
    if(st) st.value = (q*prix).toFixed(2);
    calculerTotal();
}

function calculerTotal(){
    let totalDevise = 0;
    document.querySelectorAll('.sousTotal').forEach(st => totalDevise += parseFloat(st.value||0));

    const remisePct = parseFloat(document.getElementById('remise')?.value||0);
    const fournisseurSel = document.querySelector('select[name="fournisseur_id"]');
    const exonere = fournisseurSel?.options[fournisseurSel.selectedIndex]?.dataset?.exonere ?? "1";
    const taxeRate = (exonere==="0")?0.18:0; 
    const taxeDevise = totalDevise*taxeRate;

    let totalTTC = totalDevise + taxeDevise;
    totalTTC = totalTTC - (totalTTC*(remisePct/100));

    const deviseTaux = parseFloat(document.getElementById('tauxChange')?.value||1);

    document.getElementById('totalBrutInput').value = totalDevise.toFixed(2);
    document.getElementById('taxe').value = taxeDevise.toFixed(2);
    document.getElementById('totalTTCNetInput').value = totalTTC.toFixed(2);
    document.getElementById('hiddenTotalDevise').value = totalTTC.toFixed(2);
    document.getElementById('hiddenTotalCFA').value = (totalTTC*deviseTaux).toFixed(2);

    calculerReste();
}

function calculerReste(){
    const total = parseFloat(document.getElementById('totalTTCNetInput')?.value||0);
    const verse = parseFloat(document.getElementById('montantVerse')?.value||0);
    const reste = total - verse;
    const field = document.getElementById('resteAPayer');
    if(field){
        field.value = reste.toFixed(2);
        field.classList.toggle("is-invalid", reste>0);
        field.classList.toggle("is-valid", reste<=0);
        document.getElementById('statutAchat').value = (reste>0)?"Impayé":"Payé";
    }
}

// -------- Init modal au chargement --------
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.sousTotal').forEach((_,i)=> calculerLigne(i));
    calculerTotal();

    const deviseSelect = document.getElementById('deviseSelect');
    if(deviseSelect){
        deviseSelect.addEventListener('change', ()=>{
            const opt = deviseSelect.options[deviseSelect.selectedIndex];
            document.getElementById('tauxChange').value = parseFloat(opt.dataset.taux||1);
            calculerTotal();
        });
    }

    const fournisseurSelect = document.querySelector('select[name="fournisseur_id"]');
    if(fournisseurSelect) fournisseurSelect.addEventListener('change', calculerTotal);
});
</script>
