<?php
$r = $row;
$st = (string) $r['status'];
$sign = $sign ?? null;
$signSt = (string) ($sign['status'] ?? '');
$labels = [
    'draft' => 'Draft',
    'active' => 'Active',
    'expired' => 'Expired',
    'cancelled' => 'Cancelled',
];
$chip = commerce_status_label($signSt === 'signed' ? 'signed' : $st, $signSt === 'signed' ? 'Document Signed' : ($labels[$st] ?? null));
$stLabel = $labels[$st] ?? str_replace('_', ' ', $st);
$due = due_label($r['renewal_date'] ?? null, $st === 'cancelled' ? 'cancelled' : 'open');
$renewTs = $r['renewal_date'] ? strtotime((string) $r['renewal_date']) : false;
$renewing = $st === 'active' && $renewTs && $renewTs <= strtotime('+60 days');
$nextCopy = match (true) {
    $st === 'draft' => ['Ready to use', 'This contract is still a draft. Ask the customer to sign when it is ready.'],
    $signSt === 'signed' => ['Signed', 'The customer uploaded a signed PDF. Open it from Documents if you need a copy.'],
    $signSt === 'pending' => ['Waiting on a signature', 'The customer still needs to sign on the Customer Portal. You can replace the PDF and send again.'],
    $st === 'expired' => ['Ended', 'This contract is expired. Create a new one if they renew.'],
    $st === 'cancelled' => ['Cancelled', 'This contract is cancelled.'],
    default => ['Share with the customer', 'Ask them to sign the contract PDF on the Customer Portal.'],
};
$steps = [
    ['label' => 'Draft'],
    ['label' => 'Active'],
    ['label' => 'Renewal'],
    ['label' => 'Ended'],
];
$currentIdx = match (true) {
    $st === 'draft' => 0,
    $st === 'expired' || $st === 'cancelled' => 3,
    $renewing => 2,
    default => 1,
};
$canEdit = can_edit('contracts');
$hasPdf = !empty($r['file_name']);
$isSigned = $signSt === 'signed';
$owner = trim((string) ($r['owner_name'] ?? ''));
$recTone = $renewing && !$isSigned ? 'progress' : $chip['rec'];
?>
<div class="rec-page vis-page">
  <a class="rec-back" href="<?= e(url('contracts')) ?>"><i class="bi bi-arrow-left"></i> All contracts</a>

  <div class="rec-hero rec-tone-<?= e($recTone) ?>">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar doc-hero-<?= e($recTone) ?>"><i class="bi bi-file-earmark-ruled"></i></div>
      <div class="min-w-0">
        <p class="rec-kicker">Contract · <?= 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>
          <?php if ($isSigned): ?><span class="due-pill due-done">Signed</span><?php endif; ?>
          <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>Contract value</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">
    <?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>

  <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-calendar3',
            'title' => 'Dates',
            'hint' => 'Start, end, and renewal.',
        ]); ?>
        <p class="mb-0">Starts <?= e(dt_fmt($r['start_date'])) ?> · Ends <?= e(dt_fmt($r['end_date'])) ?> · Renews <?= e(dt_fmt($r['renewal_date'])) ?></p>
        <?php if ($renewing && !empty($due['text'])): ?><p class="mt-2 mb-0"><span class="due-pill <?= e($due['class']) ?>"><?= e($due['text']) ?></span></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' => 'Contract 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. After you ask for a signature, the customer sees it too.
          <?php else: ?>
            Add a PDF when you ask for a signature.
          <?php endif; ?>
        </p>
        <div class="d-flex flex-wrap gap-2">
          <?php if ($hasPdf): ?>
            <a class="btn btn-outline-primary" href="<?= e(url('contracts/' . $r['id'] . '/file')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-box-arrow-up-right"></i> Open PDF</a>
          <?php endif; ?>
          <?php if ($isSigned && !empty($sign['signed_file_name'])): ?>
            <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 contract',
          'hint' => 'Term and customer.',
          'icon' => 'bi-file-earmark-ruled',
          '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' => 'Start', 'value' => dt_fmt($r['start_date'])],
              ['label' => 'End', 'value' => dt_fmt($r['end_date'])],
              ['label' => 'Renewal', 'value' => dt_fmt($r['renewal_date'])],
              ['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 ($isSigned): ?>
            <p class="quo-wait mb-2">This contract is already signed. There is nothing left to ask.</p>
            <?php if (!empty($sign['signed_file_name'])): ?>
              <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 elseif ($canEdit && $st !== 'cancelled'): ?>
            <form class="ajax-form" action="<?= e(url('contracts/' . $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-primary w-100" type="submit"><?= $signSt === 'pending' ? 'Update and ask again' : 'Ask to sign' ?></button>
            </form>
          <?php else: ?>
            <p class="quo-wait mb-0">You can view this contract. Ask a salesperson or manager to move it forward.</p>
          <?php endif; ?>
        </div>
      </section>
    </div>
  </div>
</div>
