<?php
$base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/'); if ($base === '/') { $base = ''; }
$qno = htmlspecialchars($quote['quote_no'] ?? ('DEV-' . (int)$quote['id']));
$curr = htmlspecialchars($quote['currency'] ?? 'XOF');
$status = trim($quote['status'] ?? 'En attente');
$badge = 'badge-secondary';
if ($status === 'Validé') $badge = 'badge-success';
elseif ($status === 'Rejeté') $badge = 'badge-danger';
elseif ($status === 'En attente') $badge = 'badge-info';
$ht = (float)($quote['total_ht'] ?? 0);
$tva = (float)($quote['total_tva'] ?? 0);
$ttc = (float)($quote['total_ttc'] ?? 0);
$vatRate = $ht > 0 ? round(($tva / $ht) * 100, 2) : null;
$sumLines = 0.0; foreach (($items ?? []) as $it) { $sumLines += (float)($it['total_line'] ?? 0); }
?>

<div class="mb-3 d-flex align-items-center justify-content-between">
  <div>
    <h5 class="mb-1">Devis <?= $qno ?></h5>
    <div class="text-muted">
      <i class="far fa-calendar-alt"></i> <?= !empty($quote['quote_date']) ? date('d/m/Y', strtotime($quote['quote_date'])) : '—' ?>
      <span class="ml-2"><i class="far fa-user"></i> <?= htmlspecialchars($quote['client_name'] ?? '') ?></span>
    </div>
  </div>
  <span class="badge <?= $badge ?> px-3 py-2"><?= htmlspecialchars($status) ?></span>
  
</div>

<?php if ($status === 'Rejeté' && !empty($quote['reject_reason'])): ?>
  <div class="alert alert-warning">
    <strong>Motif du rejet :</strong>
    <div class="mt-1"><?= nl2br(htmlspecialchars($quote['reject_reason'])) ?></div>
  </div>
<?php endif; ?>

<!-- Barre d'actions rapide -->
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
  <button class="btn btn-primary btn-sm" onclick="editQuote(<?= (int)$quote['id'] ?>)"><i class="fas fa-edit me-1"></i>Modifier</button>
  <button class="btn btn-outline-secondary btn-sm" onclick="exportQuotePdf(<?= (int)$quote['id'] ?>)"><i class="fas fa-file-pdf me-1"></i>PDF</button>
  <button class="btn btn-outline-secondary btn-sm" onclick="exportQuotePdfWithHistory(<?= (int)$quote['id'] ?>)"><i class="fas fa-file-pdf me-1"></i>PDF (historique)</button>
  <button class="btn btn-outline-info btn-sm" onclick="duplicateQuote(<?= (int)$quote['id'] ?>)"><i class="fas fa-clone me-1"></i>Dupliquer</button>
  <button class="btn btn-outline-dark btn-sm" onclick="openEmailQuote(<?= (int)$quote['id'] ?>, '<?= $qno ?>')"><i class="fas fa-envelope me-1"></i>Email</button>
  <div class="dropdown ms-auto">
    <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
      Changer le statut
    </button>
    <ul class="dropdown-menu dropdown-menu-end">
      <li><a class="dropdown-item" href="#" onclick="changeQuoteStatus(<?= (int)$quote['id'] ?>,'En attente'); return false;">En attente</a></li>
      <li><a class="dropdown-item" href="#" onclick="changeQuoteStatus(<?= (int)$quote['id'] ?>,'Validé'); return false;">Validé</a></li>
      <li><a class="dropdown-item" href="#" onclick="changeQuoteStatus(<?= (int)$quote['id'] ?>,'Rejeté'); return false;">Rejeté</a></li>
      <li><hr class="dropdown-divider"></li>
      <li><a class="dropdown-item text-danger" href="#" onclick="confirmDeleteQuote(<?= (int)$quote['id'] ?>,'<?= $qno ?>'); return false;">Supprimer</a></li>
    </ul>
  </div>
 </div>

<div class="row">
  <div class="col-lg-8">

<?php if (!empty($quote['related_type']) || !empty($quote['related_ref'])): ?>
  <div class="alert alert-light py-2 border mb-3">
    <div class="d-flex align-items-center">
      <i class="fas fa-link mr-2"></i>
      <div>
        <?php if (!empty($quote['related_type'])): ?>
          <span class="mr-3"><strong>Type lié:</strong> <?= htmlspecialchars($quote['related_type']) ?></span>
        <?php endif; ?>
        <?php if (!empty($quote['related_ref'])): ?>
          <span><strong>Référence:</strong> <?= htmlspecialchars($quote['related_ref']) ?></span>
        <?php endif; ?>
      </div>
    </div>
  </div>
<?php endif; ?>

<div class="row">
  <div class="col-md-4 mb-3">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="text-muted">Total HT</div>
        <div class="h4 mb-0"><?= number_format($ht, 2, ',', ' ') ?> <?= $curr ?></div>
      </div>
    </div>
  </div>
  <div class="col-md-4 mb-3">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-center">
          <div>
            <div class="text-muted">TVA<?= $vatRate !== null ? ' ('.$vatRate.'%)' : '' ?></div>
            <div class="h5 mb-0"><?= number_format($tva, 2, ',', ' ') ?> <?= $curr ?></div>
          </div>
          <i class="fas fa-receipt text-secondary"></i>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-4 mb-3">
    <div class="card border-primary shadow-sm">
      <div class="card-body">
        <div class="text-muted">Total TTC</div>
        <div class="h4 mb-0 text-primary"><strong><?= number_format($ttc, 2, ',', ' ') ?> <?= $curr ?></strong></div>
      </div>
    </div>
  </div>
</div>

<div class="d-flex align-items-center justify-content-between mb-2">
  <h6 class="mb-0 text-muted">Lignes du devis</h6>
</div>

<div class="table-responsive">
  <table class="table table-sm table-striped table-bordered">
    <thead class="bg-light">
      <tr>
        <th>Désignation</th>
        <th class="text-center" style="width:90px">Unité</th>
        <th class="text-right" style="width:110px">Quantité</th>
        <th class="text-right" style="width:140px">Prix unitaire</th>
        <th class="text-right" style="width:140px">Total</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($items)): ?>
        <tr><td colspan="5" class="text-center text-muted">Aucune ligne</td></tr>
      <?php else: ?>
        <?php foreach ($items as $item): ?>
          <tr>
            <td><?= htmlspecialchars($item['designation'] ?? '') ?></td>
            <td class="text-center"><?= htmlspecialchars($item['unit'] ?? 'u') ?></td>
            <td class="text-right"><?= number_format((float)($item['quantity'] ?? 0), 3, ',', ' ') ?></td>
            <td class="text-right"><?= number_format((float)($item['unit_price'] ?? 0), 2, ',', ' ') ?> <?= $curr ?></td>
            <td class="text-right"><strong><?= number_format((float)($item['total_line'] ?? 0), 2, ',', ' ') ?> <?= $curr ?></strong></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
    <tfoot>
      <tr>
        <th colspan="4" class="text-right">Total lignes</th>
        <th class="text-right"><?= number_format($sumLines, 2, ',', ' ') ?> <?= $curr ?></th>
      </tr>
    </tfoot>
  </table>
  <div class="text-muted small">Note: le total lignes peut différer du total TTC selon l'arrondi et la TVA appliquée.</div>
</div>

<?php if (!empty($history)): ?>
  <hr>
  <h6 class="mb-3 text-muted">Historique des mouvements</h6>
  <div class="table-responsive">
    <table class="table table-sm table-hover">
      <thead class="bg-light">
        <tr>
          <th style="width:170px">Date</th>
          <th style="width:200px">Par</th>
          <th>Changement</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($history as $h): ?>
          <?php 
            $from = trim((string)($h['from_status'] ?? ''));
            $to   = trim((string)($h['to_status'] ?? ''));
            $reason = trim((string)($h['reason'] ?? ''));
            $badgeFrom = 'badge-secondary';
            if ($from === 'Validé') $badgeFrom = 'badge-success';
            elseif ($from === 'Rejeté') $badgeFrom = 'badge-danger';
            elseif ($from === 'En attente') $badgeFrom = 'badge-info';
            $badgeTo = 'badge-secondary';
            if ($to === 'Validé') $badgeTo = 'badge-success';
            elseif ($to === 'Rejeté') $badgeTo = 'badge-danger';
            elseif ($to === 'En attente') $badgeTo = 'badge-info';
          ?>
          <tr>
            <td><?= !empty($h['created_at']) ? date('d/m/Y H:i', strtotime($h['created_at'])) : '—' ?></td>
            <td>
              <?php if (!empty($h['user_name'])): ?>
                <?= htmlspecialchars($h['user_name']) ?>
              <?php elseif (!empty($h['user_email'])): ?>
                <?= htmlspecialchars($h['user_email']) ?>
              <?php else: ?>
                <span class="text-muted">Système</span>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($from !== ''): ?>
                <span class="badge <?= $badgeFrom ?> mr-1"><?= htmlspecialchars($from) ?></span>
                <i class="fas fa-arrow-right mx-1"></i>
              <?php else: ?>
                <span class="text-muted mr-1">Création</span>
                <i class="fas fa-arrow-right mx-1"></i>
              <?php endif; ?>
              <span class="badge <?= $badgeTo ?> mr-2"><?= htmlspecialchars($to) ?></span>
              <?php if ($to === 'Rejeté' && $reason !== ''): ?>
                <div class="small text-muted mt-1"><strong>Motif:</strong> <?= nl2br(htmlspecialchars($reason)) ?></div>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>
  </div>
  <div class="col-lg-4">
    <div class="card mb-3">
      <div class="card-header">Infos client</div>
      <div class="card-body">
        <div class="mb-2"><i class="far fa-user me-2"></i><strong>Client:</strong> <?= htmlspecialchars($quote['client_name'] ?? '') ?></div>
        <?php if (!empty($quote['related_type']) || !empty($quote['related_ref'])): ?>
          <div class="mb-2"><i class="fas fa-link me-2"></i><strong>Référence liée:</strong> <?= htmlspecialchars(($quote['related_type'] ? $quote['related_type'].': ' : '').($quote['related_ref'] ?? '')) ?></div>
        <?php endif; ?>
        <div class="text-muted small">N° Devis: <?= $qno ?></div>
      </div>
    </div>
    <div class="card mb-3">
      <div class="card-header">Métadonnées</div>
      <div class="card-body small text-muted">
        <div><i class="far fa-calendar-alt me-2"></i>Date devis: <?= !empty($quote['quote_date']) ? date('d/m/Y', strtotime($quote['quote_date'])) : '—' ?></div>
        <div><i class="far fa-calendar-plus me-2"></i>Créé le: <?= !empty($quote['created_at']) ? date('d/m/Y H:i', strtotime($quote['created_at'])) : '—' ?></div>
        <div><i class="far fa-calendar-check me-2"></i>Modifié le: <?= !empty($quote['updated_at']) ? date('d/m/Y H:i', strtotime($quote['updated_at'])) : '—' ?></div>
        <?php if (!empty($quote['status_changed_at'])): ?>
          <div><i class="far fa-clock me-2"></i>Statut maj: <?= date('d/m/Y H:i', strtotime($quote['status_changed_at'])) ?></div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<?php if (!empty($quote['created_at']) || !empty($quote['updated_at'])): ?>
  <hr>
  <div class="row">
    <div class="col-md-6">
      <small class="text-muted">
        <i class="far fa-calendar-plus"></i> Créé le : <?= !empty($quote['created_at']) ? date('d/m/Y H:i', strtotime($quote['created_at'])) : '—' ?>
      </small>
    </div>
    <div class="col-md-6 text-right">
      <small class="text-muted">
        <i class="far fa-calendar-check"></i> Modifié le : <?= !empty($quote['updated_at']) ? date('d/m/Y H:i', strtotime($quote['updated_at'])) : '—' ?>
      </small>
    </div>
  </div>
<?php endif; ?>

<!-- Modale Bootstrap 5: Motif de rejet -->
<div class="modal fade" id="rejectReasonModal" tabindex="-1" aria-labelledby="rejectReasonModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-warning">
        <h5 class="modal-title" id="rejectReasonModalLabel">Motif du rejet</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="rejectQuoteId" value="<?= (int)$quote['id'] ?>">
        <div class="mb-3">
          <label for="rejectReason" class="form-label">Veuillez préciser le motif</label>
          <textarea id="rejectReason" class="form-control" rows="4" placeholder="Ex: Prix non conforme, informations manquantes, etc." required></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-warning" id="confirmRejectBtn">Rejeter le devis</button>
      </div>
    </div>
  </div>
</div>

<!-- Modale Bootstrap 5: Envoyer par email -->
<div class="modal fade" id="quoteEmailModal" tabindex="-1" aria-labelledby="quoteEmailModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="quoteEmailModalLabel">Envoyer le devis <?= $qno ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
        <form id="quoteEmailForm">
          <input type="hidden" name="quote_id" value="<?= (int)$quote['id'] ?>">
          <div class="mb-3">
            <label class="form-label">Destinataire</label>
            <input type="email" class="form-control" name="to" placeholder="client@example.com" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Objet</label>
            <input type="text" class="form-control" name="subject" value="Votre devis <?= $qno ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Message</label>
            <textarea class="form-control" name="message" rows="4" placeholder="Bonjour, veuillez trouver ci-joint votre devis."></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-primary" id="sendQuoteEmailBtn">Envoyer</button>
      </div>
    </div>
  </div>
</div>

<script>
  // Fonctions utilitaires compatibles Bootstrap 5
  function bsModal(id){
    if (window.bootstrap && document.getElementById(id)) {
      return new bootstrap.Modal(document.getElementById(id));
    }
    return null;
  }

  function exportQuotePdf(id){ window.open('<?= $base ?>/quotes/pdf?id=' + id, '_blank'); }
  function exportQuotePdfWithHistory(id){ window.open('<?= $base ?>/quotes/pdf?id=' + id + '&history=1', '_blank'); }

  function openEmailQuote(id, qno){
    var m = bsModal('quoteEmailModal');
    if (m) { m.show(); } else { alert('Module modal indisponible.'); }
  }

  function duplicateQuote(id){
    if(!confirm('Dupliquer ce devis ?')) return;
    fetch('<?= $base ?>/quotes/duplicate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With':'XMLHttpRequest' },
      body: 'id=' + encodeURIComponent(id)
    }).then(function(r){ if(!r.ok) throw new Error('Duplication échouée'); return r.json(); })
    .then(function(){ location.reload(); })
    .catch(function(e){ alert('Erreur: ' + e.message); });
  }

  document.getElementById('sendQuoteEmailBtn')?.addEventListener('click', function(){
    var fd = new URLSearchParams(new FormData(document.getElementById('quoteEmailForm'))).toString();
    fetch('<?= $base ?>/quotes/send', { method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest' }, body: fd })
      .then(function(r){ if(!r.ok) throw new Error('Envoi échoué'); return r.json(); })
      .then(function(){ bsModal('quoteEmailModal')?.hide(); alert('Email envoyé.'); })
      .catch(function(e){ alert('Erreur: ' + e.message); });
  });

  function changeQuoteStatus(id, status){
    if (status === 'Rejeté') {
      var m = bsModal('rejectReasonModal');
      if (m) { m.show(); }
      return;
    }
    fetch('<?= $base ?>/quotes/status', {
      method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded', 'X-Requested-With':'XMLHttpRequest' },
      body: 'id=' + encodeURIComponent(id) + '&status=' + encodeURIComponent(status)
    }).then(function(r){ if(!r.ok) throw new Error('Changement de statut échoué'); return r.json(); })
      .then(function(){ location.reload(); })
      .catch(function(e){ alert('Erreur: ' + e.message); });
  }

  document.getElementById('confirmRejectBtn')?.addEventListener('click', function(){
    var id = document.getElementById('rejectQuoteId').value;
    var reason = (document.getElementById('rejectReason').value || '').trim();
    if (!reason) { alert('Veuillez saisir un motif.'); return; }
    fetch('<?= $base ?>/quotes/status', {
      method:'POST', headers:{ 'Content-Type':'application/x-www-form-urlencoded', 'X-Requested-With':'XMLHttpRequest' },
      body: 'id=' + encodeURIComponent(id) + '&status=' + encodeURIComponent('Rejeté') + '&reason=' + encodeURIComponent(reason)
    }).then(function(r){ if(!r.ok) throw new Error('Changement de statut échoué'); return r.json(); })
      .then(function(){ bsModal('rejectReasonModal')?.hide(); location.reload(); })
      .catch(function(e){ alert('Erreur: ' + e.message); });
  });

  function confirmDeleteQuote(quoteId, quoteNo){
    if (!confirm('Supprimer le devis ' + quoteNo + ' ?')) return;
    fetch('<?= $base ?>/quotes/destroy?id=' + quoteId, { method:'POST', headers:{ 'X-Requested-With':'XMLHttpRequest' } })
      .then(function(r){ if(!r.ok) throw new Error('Suppression échouée'); location.href='<?= $base ?>/quotes'; })
      .catch(function(e){ alert('Erreur: ' + e.message); });
  }
</script>
