<?php
$base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
if ($base === '/') { $base = ''; }
?>

<form method="post" action="<?= htmlspecialchars($base) ?>/quotes/update?id=<?= (int)$quote['id'] ?>" id="quote-edit-form">
  <input type="hidden" name="id" value="<?= (int)$quote['id'] ?>">
  <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">
        <option value="">Sélectionner un client…</option>
        <?php foreach (($clients ?? []) as $cl): ?>
          <option value="<?= (int)$cl['id'] ?>" <?= $quote['client_name'] === $cl['name'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($cl['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
      <input type="hidden" name="client_name" value="<?= htmlspecialchars($quote['client_name'] ?? '') ?>">
    </div>
    <div class="col-6 col-md-2">
      <label class="form-label">Date</label>
      <input type="date" class="form-control" name="quote_date" value="<?= htmlspecialchars($quote['quote_date'] ?? 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($quote['currency'] ?? 'XOF') ?>">
    </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((float)($quote['total_ht'] > 0 ? ($quote['total_tva'] / $quote['total_ht'] * 100) : 18)) ?>">
    </div>
    <div class="col-6 col-md-2">
      <label class="form-label">Statut</label>
      <select class="custom-select" name="status">
        <option <?= ($quote['status'] ?? '') === 'En attente' ? 'selected' : '' ?>>En attente</option>
        <option <?= ($quote['status'] ?? '') === 'Validé' ? 'selected' : '' ?>>Validé</option>
        <option <?= ($quote['status'] ?? '') === 'Rejeté' ? 'selected' : '' ?>>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" id="related_type">
        <option value="">Aucun</option>
        <option value="incident" <?= ($quote['related_type'] ?? '') === 'incident' ? 'selected' : '' ?>>Incident</option>
        <option value="preventive" <?= ($quote['related_type'] ?? '') === 'preventive' ? 'selected' : '' ?>>Préventive</option>
      </select>
    </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" value="<?= htmlspecialchars($quote['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>
        <?php foreach (($quoteItems ?? []) as $item): ?>
          <tr>
            <td>
              <select class="form-control form-control-sm cat_select">
                <option value="">Catégorie…</option>
                <?php foreach (($categories ?? []) as $c): ?>
                  <option value="<?= (int)$c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </td>
            <td>
              <select class="form-control form-control-sm item_select" disabled>
                <option value="">Choisir…</option>
              </select>
              <input type="hidden" name="lines[][designation]" value="<?= htmlspecialchars($item['designation'] ?? '') ?>">
            </td>
            <td>
              <input class="form-control form-control-sm unit" value="<?= htmlspecialchars($item['unit'] ?? 'u') ?>">
              <input type="hidden" name="lines[][unit]">
            </td>
            <td>
              <input type="number" step="0.001" class="form-control form-control-sm quantity" value="<?= htmlspecialchars($item['quantity'] ?? 1) ?>">
              <input type="hidden" name="lines[][quantity]">
            </td>
            <td>
              <input type="number" step="0.01" class="form-control form-control-sm unit_price" value="<?= htmlspecialchars($item['unit_price'] ?? 0) ?>">
              <input type="hidden" name="lines[][unit_price]">
            </td>
            <td class="line-total"><?= number_format((float)($item['total_line'] ?? 0), 2, ',', ' ') ?></td>
            <td><button type="button" class="btn btn-sm btn-danger remove-line">×</button></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <button type="button" class="btn btn-outline-primary" id="add-line">Ajouter une ligne</button>

  <!-- Données JSON pour initialisation -->
  <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($quote['currency'] ?? 'XOF') ?></div>
    <div><strong>TVA:</strong> <span id="total-tva">0</span> <?= htmlspecialchars($quote['currency'] ?? 'XOF') ?></div>
    <div class="fs-5"><strong>Total TTC:</strong> <span id="total-ttc">0</span> <?= htmlspecialchars($quote['currency'] ?? 'XOF') ?></div>
  </div>

  <div class="text-end mt-3">
    <button class="btn btn-primary" type="submit">Enregistrer les modifications</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
  </div>
</form>

<script>
  // Initialiser les calculs pour les lignes existantes
  document.addEventListener('DOMContentLoaded', function() {
    // Recalculer les totaux au chargement
    document.querySelectorAll('#lines-table tbody tr').forEach(tr => {
      const qty = parseFloat(tr.querySelector('.quantity')?.value || 0);
      const price = parseFloat(tr.querySelector('.unit_price')?.value || 0);
      const totalCell = tr.querySelector('.line-total');
      if (totalCell) {
        totalCell.textContent = (qty * price).toLocaleString('fr-FR', { minimumFractionDigits: 2 });
      }
      
      // Ajouter les listeners
      tr.querySelector('.quantity')?.addEventListener('input', function() {
        const q = parseFloat(this.value || 0);
        const p = parseFloat(tr.querySelector('.unit_price').value || 0);
        tr.querySelector('.line-total').textContent = (q * p).toLocaleString('fr-FR', { minimumFractionDigits: 2 });
      });
      
      tr.querySelector('.unit_price')?.addEventListener('input', function() {
        const q = parseFloat(tr.querySelector('.quantity').value || 0);
        const p = parseFloat(this.value || 0);
        tr.querySelector('.line-total').textContent = (q * p).toLocaleString('fr-FR', { minimumFractionDigits: 2 });
      });
      
      tr.querySelector('.remove-line')?.addEventListener('click', function() {
        tr.remove();
      });
    });
  });
</script>
