<?php $title = 'Nouveau devis'; $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/'); if ($base === '/') { $base = ''; } ?>
<div class="card shadow-sm">
  <div class="card-body">
    <form method="post" action="<?= htmlspecialchars($base) ?>/quotes/store" id="quote-form">
      <div class="row g-3">
        <div class="col-12 col-md-4">
          <label class="form-label">Client</label>
          <select class="custom-select" name="client_id" required>
            <option value="">Sélectionner un client…</option>
            <?php foreach (($clients ?? []) as $cl): ?>
              <option value="<?= (int)$cl['id'] ?>"><?= htmlspecialchars($cl['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-6 col-md-2">
          <label class="form-label">Date</label>
          <input type="date" class="form-control" name="quote_date" value="<?= date('Y-m-d') ?>">
        </div>
        <div class="col-6 col-md-2">
          <label class="form-label">Devise</label>
          <input class="form-control" name="currency" value="<?= htmlspecialchars($currency) ?>">
        </div>
        <div class="col-6 col-md-2">
          <label class="form-label">TVA (%)</label>
          <input type="number" step="0.01" class="form-control" name="vat_rate" value="<?= htmlspecialchars($vat) ?>">
        </div>
        <div class="col-6 col-md-2">
          <label class="form-label">Statut</label>
          <select class="custom-select" name="status">
            <option>En attente</option>
            <option>Validé</option>
            <option>Rejeté</option>
          </select>
        </div>
      </div>

      <hr>
      <h6>Liens (facultatifs)</h6>
      <div class="row g-3">
        <div class="col-6 col-md-3">
          <label class="form-label">Type</label>
          <select class="custom-select" name="related_type_display" id="related_type" >
            <option value="">Aucun</option>
            <option value="incident">Incident</option>
            <option value="preventive">Préventive</option>
          </select>
          <input type="hidden" name="related_type" id="related_type_hidden">
        </div>
        <div class="col-6 col-md-3">
          <label class="form-label">Référence</label>
          <input class="form-control" name="related_ref" id="related_ref" placeholder="ex: INC-2025-00123">
        </div>
      </div>

      <hr>
      <h6>Lignes du devis</h6>
      <div class="table-responsive">
        <table class="table align-middle" id="lines-table">
          <thead>
            <tr>
              <th style="width:20%">Catégorie</th>
              <th style="width:30%">Article</th>
              <th>Unité</th>
              <th style="width:140px">Quantité</th>
              <th style="width:160px">PU</th>
              <th>Total</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>
      <button type="button" class="btn btn-outline-primary" id="add-line">Ajouter une ligne</button>

      <!-- Données JSON pour initialisation côté parent (modal) -->
      <input type="hidden" id="quote-items-json" value='<?= htmlspecialchars(json_encode($items, JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_AMP), ENT_QUOTES) ?>'>
      <input type="hidden" id="quote-categories-json" value='<?= htmlspecialchars(json_encode($categories ?? [], JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_AMP), ENT_QUOTES) ?>'>

      <div class="mt-4 text-end">
        <div><strong>Total HT:</strong> <span id="total-ht">0</span> <?= htmlspecialchars($currency) ?></div>
        <div><strong>TVA:</strong> <span id="total-tva">0</span> <?= htmlspecialchars($currency) ?></div>
        <div class="fs-5"><strong>Total TTC:</strong> <span id="total-ttc">0</span> <?= htmlspecialchars($currency) ?></div>
      </div>

      <div class="text-end mt-3">
        <button class="btn btn-primary" type="submit">Enregistrer le devis</button>
          <a class="btn btn-secondary" href="<?= htmlspecialchars($base) ?>/quotes" data-dismiss="modal">Annuler</a>
      </div>
    </form>
  </div>
</div>

<script>
  // Ce script est conservé pour rendu non-modal; en modal, l'initialisation est refaite côté parent.
  try {
    const items = <?= json_encode($items, JSON_UNESCAPED_UNICODE) ?>;
    const categories = <?= json_encode($categories ?? [], JSON_UNESCAPED_UNICODE) ?>;
    const currency = <?= json_encode($currency) ?>;
    function addLineRow(prefill) {
      const tbody = document.querySelector('#lines-table tbody');
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td>
          <select class="form-select form-select-sm cat_select">
            <option value="">Catégorie…</option>
            ${categories.map(c => `<option value="${c.id}">${c.name}</option>`).join('')}
          </select>
        </td>
        <td>
          <select class="form-select form-select-sm item_select" disabled>
            <option value="">Choisir…</option>
          </select>
          <input type="hidden" name="lines[][designation]">
        </td>
        <td><input class="form-control form-control-sm unit" value="u"><input type="hidden" name="lines[][unit]"></td>
        <td><input type="number" step="0.001" class="form-control form-control-sm quantity" value="1"><input type="hidden" name="lines[][quantity]"></td>
        <td><input type="number" step="0.01" class="form-control form-control-sm unit_price" value="0"><input type="hidden" name="lines[][unit_price]"></td>
        <td class="line-total">0</td>
        <td><button type="button" class="btn btn-sm btn-outline-danger remove">X</button></td>`;
      tbody.appendChild(tr);

      const catSel = tr.querySelector('.cat_select');
      const itemSel = tr.querySelector('.item_select');
      const unit = tr.querySelector('.unit');
      const qty = tr.querySelector('.quantity');
      const price = tr.querySelector('.unit_price');
      const totalCell = tr.querySelector('.line-total');
      const hiddenDes = tr.querySelector('input[name="lines[][designation]"]');

      const byCat = items.reduce((acc, it) => { (acc[it.category_id] ||= []).push(it); return acc; }, {});

      function rebuildItems() {
        const cat = parseInt(catSel.value||'0',10)||0;
        itemSel.innerHTML = '<option value="">Choisir…</option>';
        itemSel.disabled = !cat;
        if (!cat) return;
        (byCat[cat]||[]).forEach(i => {
          const opt = document.createElement('option');
          opt.value = i.id; opt.textContent = i.designation; opt.dataset.unit = i.unit; opt.dataset.price = i.unit_price;
          itemSel.appendChild(opt);
        });
      }
      function recalc() {
        const q = parseFloat(qty.value || '0');
        const p = parseFloat(price.value || '0');
        totalCell.textContent = (q * p).toLocaleString('fr-FR', {minimumFractionDigits: 2});
        totals();
      }
      catSel.addEventListener('change', () => { rebuildItems(); hiddenDes.value=''; });
      itemSel.addEventListener('change', () => {
        const opt = itemSel.selectedOptions[0];
        if (opt && opt.value) {
          unit.value = opt.dataset.unit || 'u';
          price.value = opt.dataset.price || 0;
          hiddenDes.value = opt.textContent || '';
          recalc();
        }
      });
      qty.addEventListener('input', recalc);
      price.addEventListener('input', recalc);
      tr.querySelector('.remove').addEventListener('click', () => { tr.remove(); totals(); });

      if (prefill) {
        // Optionnel: préremplissage si fourni
        qty.value = prefill.quantity || 1;
        price.value = prefill.unit_price || 0;
        unit.value = prefill.unit || 'u';
        hiddenDes.value = prefill.designation || '';
        recalc();
      }
    }
    function totals() {
      let ht = 0;
      document.querySelectorAll('#lines-table tbody tr').forEach(tr => {
        const q = parseFloat(tr.querySelector('.quantity').value || '0');
        const p = parseFloat(tr.querySelector('.unit_price').value || '0');
        ht += q * p;
      });
      const vat = parseFloat(document.querySelector('input[name="vat_rate"]').value || '0');
      const tva = ht * (vat/100);
      const ttc = ht + tva;
      document.getElementById('total-ht').textContent = ht.toLocaleString('fr-FR', {minimumFractionDigits: 2});
      document.getElementById('total-tva').textContent = tva.toLocaleString('fr-FR', {minimumFractionDigits: 2});
      document.getElementById('total-ttc').textContent = ttc.toLocaleString('fr-FR', {minimumFractionDigits: 2});
    }
    document.getElementById('add-line')?.addEventListener('click', () => addLineRow());
    addLineRow();
    document.getElementById('quote-form')?.addEventListener('submit', (e) => {
      document.querySelectorAll('#lines-table tbody tr').forEach(tr => {
        tr.querySelector('input[name="lines[][unit]"]').value = tr.querySelector('.unit').value;
        tr.querySelector('input[name="lines[][quantity]"]').value = tr.querySelector('.quantity').value;
        tr.querySelector('input[name="lines[][unit_price]"]').value = tr.querySelector('.unit_price').value;
      });
    });
    document.querySelector('input[name="vat_rate"]').addEventListener('input', totals);
  } catch(e) { /* ignore lors du rendu modal */ }
</script>
<script>
  // Pré-remplissage Type/Référence en fonction du client sélectionné
  (function(){
    const base = <?= json_encode($base ?? '') ?>;
    const selClient = document.querySelector('select[name="client_id"]');
    const selType = document.getElementById('related_type');
    const hidType = document.getElementById('related_type_hidden');
    const refInput = document.getElementById('related_ref');
    function setGrey(el, on) {
      if (!el) return;
      if (on) { el.classList.add('bg-light','text-muted'); } else { el.classList.remove('bg-light','text-muted'); }
    }
    function lockType(val) {
      if (!selType || !hidType) return;
      selType.value = val || '';
      hidType.value = val || '';
      // désactiver le select visible pour le griser, mais soumettre via hidden
      selType.disabled = !!val;
      setGrey(selType, !!val);
    }
    function lockRef(val) {
      if (!refInput) return;
      refInput.value = val || '';
      const lock = !!val;
      refInput.readOnly = lock;
      setGrey(refInput, lock);
    }
    async function refreshHints() {
      const id = parseInt(selClient?.value || '0', 10) || 0;
      if (!id) { lockType(''); lockRef(''); return; }
      try {
        const res = await fetch(base + '/quotes/client-hints?client_id=' + id, { credentials: 'same-origin' });
        if (!res.ok) throw new Error('fetch');
        const j = await res.json();
        if (j && j.related_ref) {
          lockType(j.related_type || '');
          lockRef(j.related_ref || '');
        } else {
          // aucun incident récent → laisser éditable
          lockType('');
          lockRef('');
        }
      } catch(e) {
        lockType(''); lockRef('');
      }
    }
    selClient?.addEventListener('change', refreshHints);
    // premier remplissage si déjà sélectionné
    refreshHints();
  })();
</script>
