<?php
$r = $row;
$st = (string) $r['status'];
$sign = $sign ?? null;
$signSt = (string) ($sign['status'] ?? '');
$isSigned = $st === 'signed' || $signSt === 'signed';
$labels = [
    'draft' => 'Draft',
    'pending_approval' => 'Waiting',
    'approved' => 'Approved',
    'rejected' => 'Rejected',
    'sent' => 'Sent',
    'signed' => 'Document Signed',
    'void' => 'Void',
];
$chip = commerce_status_label($st, $labels[$st] ?? null);
$stLabel = $chip['text'];
$nextCopy = match ($st) {
    'draft' => ['Ready to send inside', 'Submit this quote so a manager can approve it.'],
    'pending_approval' => ['Waiting on a manager', 'A manager will approve or reject this quote.'],
    'approved' => ['Approved — share it', 'Send the PDF to the customer, or ask them to sign.'],
    'rejected' => ['Needs a fix', 'Update the paper if needed, then submit again.'],
    'sent' => ['With the customer', 'They can open it on the Customer Portal. Ask for a signature if you still need one.'],
    'signed' => ['Document signed', 'The customer uploaded a signed PDF. Open it below or from Documents.'],
    default => ['Quote', 'This quote is closed.'],
};
$steps = [
    ['key' => 'draft', 'label' => 'Draft'],
    ['key' => 'pending_approval', 'label' => 'Waiting'],
    ['key' => 'approved', 'label' => 'Approved'],
    ['key' => 'sent', 'label' => 'Sent'],
    ['key' => 'signed', 'label' => 'Document Signed'],
];
$stepOn = match ($st) {
    'rejected' => 'draft',
    'void' => 'sent',
    default => $st,
};
$doneKeys = ['draft' => 0, 'pending_approval' => 1, 'approved' => 2, 'sent' => 3, 'signed' => 4];
$currentIdx = $doneKeys[$stepOn] ?? 0;
$canEdit = can_edit('quotes');
$hasPdf = !empty($r['file_name']);
$hasSignedPdf = $isSigned && !empty($sign['signed_file_name']) && !empty($sign['document_id']);
$owner = trim((string) ($r['owner_name'] ?? ''));
$body = trim((string) ($r['body'] ?? ''));
?>
<div class="rec-page vis-page">
  <a class="rec-back" href="<?= e(url('quotes')) ?>"><i class="bi bi-arrow-left"></i> All quotes</a>

  <div class="rec-hero rec-tone-<?= e($chip['rec']) ?>">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar doc-hero-<?= e($chip['rec']) ?>"><i class="bi bi-file-earmark-richtext"></i></div>
      <div class="min-w-0">
        <p class="rec-kicker">Quote · <?= e((string) ($r['number'] ?? '')) ?></p>
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($r['title']) ?></h1>
          <span class="due-pill <?= e($chip['class']) ?>"><?= e($stLabel) ?></span>
        </div>
        <div class="rec-hero-sub">
          <a href="<?= e(url('accounts/' . $r['account_id'])) ?>"><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></a>
          <?php if ($owner !== ''): ?>
            <span class="task-owner-chip" title="<?= e($owner) ?>">
              <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
              <span class="task-owner text-truncate"><?= e($owner) ?></span>
            </span>
          <?php endif; ?>
          <span><i class="bi bi-calendar3"></i> <?= e(dt_fmt($r['created_at'])) ?></span>
        </div>
      </div>
    </div>
    <div class="rec-hero-actions">
      <div class="rec-hero-amt">
        <strong><?= e(money_fmt($r['amount'])) ?></strong>
        <span>Quote total</span>
      </div>
      <a class="btn btn-outline-primary" href="<?= e(url('accounts/' . $r['account_id'])) ?>"><i class="bi bi-buildings"></i> Customer</a>
    </div>
  </div>

  <ol class="quo-steps" style="grid-template-columns: repeat(5, minmax(0, 1fr))">
    <?php foreach ($steps as $i => $step):
        $state = $i < $currentIdx ? 'is-done' : ($i === $currentIdx ? 'is-now' : '');
    ?>
      <li class="quo-step <?= e($state) ?>">
        <span class="quo-step-dot"><?php if ($i < $currentIdx): ?><i class="bi bi-check"></i><?php else: ?><?= $i + 1 ?><?php endif; ?></span>
        <span><?= e($step['label']) ?></span>
      </li>
    <?php endforeach; ?>
  </ol>

  <?php if (!empty($r['reject_reason'])): ?>
    <div class="quo-reject"><i class="bi bi-exclamation-triangle-fill"></i> Rejected: <?= e($r['reject_reason']) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <div class="col-lg-7">
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-clipboard2-pulse',
            'title' => 'What’s included',
            'hint' => 'What this quote covers.',
        ]); ?>
        <?php if ($body !== ''): ?>
          <div class="vis-need-detail"><?= nl2br(e($body)) ?></div>
        <?php else: ?>
          <p class="rec-section-hint mb-0">No extra notes on this quote.</p>
        <?php endif; ?>
      </div>
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-file-earmark-pdf',
            'title' => 'Quote PDF',
            'hint' => $hasPdf ? (string) $r['file_name'] : 'No PDF attached.',
        ]); ?>
        <p class="rec-section-hint">
          <?php if ($isSigned): ?>
            Signed<?= !empty($sign['signer_name']) ? ' by ' . e($sign['signer_name']) : '' ?><?= !empty($sign['signed_at']) ? ' on ' . e(dt_fmt($sign['signed_at'])) : '' ?>.
          <?php elseif ($hasPdf): ?>
            Opens in a new tab for you and, after send, for the customer.
          <?php else: ?>
            Add a PDF when you send or ask for a signature.
          <?php endif; ?>
        </p>
        <div class="d-flex flex-wrap gap-2">
          <?php if ($hasPdf): ?>
            <a class="btn <?= $hasSignedPdf ? 'btn-outline-primary' : 'btn-primary' ?>" href="<?= e(url('quotes/' . $r['id'] . '/file')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-box-arrow-up-right"></i> Open PDF</a>
          <?php endif; ?>
          <?php if ($hasSignedPdf): ?>
            <a class="btn btn-primary" href="<?= e(url('documents/' . (int) $sign['document_id'] . '/signed')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-pen"></i> Signed PDF</a>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <div class="col-lg-5">
      <?php \App\Core\View::partial('record_facts', [
          'title' => 'About this quote',
          'hint' => 'Ticket facts.',
          'icon' => 'bi-info-circle',
          'facts' => [
              ['label' => 'Number', 'value' => (string) ($r['number'] ?? '')],
              ['label' => 'Customer', 'value' => (string) ($r['account_name'] ?? ''), 'href' => url('accounts/' . (int) $r['account_id'])],
              ['label' => 'Amount', 'value' => money_fmt($r['amount'])],
              ['label' => 'Status', 'value' => $stLabel],
              ['label' => 'Owner', 'value' => $owner !== '' ? $owner : 'Unassigned'],
          ],
      ]); ?>
      <section class="svc-req quo-next">
        <div class="svc-req-head">
          <span class="svc-req-icon"><i class="bi bi-lightning-charge"></i></span>
          <div>
            <div class="svc-req-kicker">Next step</div>
            <h2><?= e($nextCopy[0]) ?></h2>
            <p><?= e($nextCopy[1]) ?></p>
          </div>
        </div>
        <div class="svc-req-body">
          <?php if ($canEdit && in_array($st, ['draft', 'rejected'], true)): ?>
            <form class="ajax-form" action="<?= e(url('quotes/' . $r['id'] . '/submit')) ?>" method="post">
              <?= csrf_field() ?>
              <button class="btn btn-primary w-100" type="submit">Submit for approval</button>
            </form>
          <?php elseif ($st === 'pending_approval'): ?>
            <p class="quo-wait mb-0">No action for you until a manager reviews it.</p>
          <?php elseif ($canEdit && $st === 'approved'): ?>
            <form class="ajax-form quo-action" action="<?= e(url('quotes/' . $r['id'] . '/send')) ?>" method="post" enctype="multipart/form-data">
              <?= csrf_field() ?>
              <label class="form-label"><?= $hasPdf ? 'Replace PDF (optional)' : 'PDF (optional)' ?></label>
              <input class="form-control mb-2" type="file" name="pdf" accept="application/pdf,.pdf">
              <button class="btn btn-primary w-100" type="submit">Send to customer</button>
            </form>
            <form class="ajax-form quo-action" action="<?= e(url('quotes/' . $r['id'] . '/esign')) ?>" method="post" enctype="multipart/form-data">
              <?= csrf_field() ?>
              <label class="form-label"><?= $hasPdf ? 'Replace PDF (optional)' : 'PDF (optional)' ?></label>
              <input class="form-control mb-2" type="file" name="pdf" accept="application/pdf,.pdf">
              <button class="btn btn-outline-primary w-100" type="submit">Ask for signature</button>
            </form>
          <?php elseif ($canEdit && $st === 'sent'): ?>
            <form class="ajax-form" action="<?= e(url('quotes/' . $r['id'] . '/esign')) ?>" method="post" enctype="multipart/form-data">
              <?= csrf_field() ?>
              <label class="form-label"><?= $hasPdf ? 'Replace PDF (optional)' : 'PDF (optional)' ?></label>
              <input class="form-control mb-2" type="file" name="pdf" accept="application/pdf,.pdf">
              <button class="btn btn-outline-primary w-100" type="submit">Ask for signature</button>
            </form>
          <?php elseif ($st === 'signed'): ?>
            <p class="quo-wait mb-2">The customer already signed this quote.</p>
            <?php if ($hasSignedPdf): ?>
              <a class="btn btn-primary w-100" href="<?= e(url('documents/' . (int) $sign['document_id'] . '/signed')) ?>" target="_blank" rel="noopener noreferrer">Open signed PDF</a>
            <?php endif; ?>
          <?php else: ?>
            <p class="quo-wait mb-0">You can view this quote. Ask a salesperson or manager to move it forward.</p>
          <?php endif; ?>
        </div>
      </section>
    </div>
  </div>
</div>
