<?php
$rows = $rows ?? [];
$nActive = 0;
$nSoon = 0;
$nEnded = 0;
$today = new DateTimeImmutable('today');
$soonCut = $today->modify('+60 days');
foreach ($rows as $r) {
    $st = (string) $r['status'];
    if ($st === 'expired' || $st === 'cancelled') {
        $nEnded++;
        continue;
    }
    $nActive++;
    $rd = (string) ($r['renewal_date'] ?? '');
    if ($rd !== '') {
        $d = DateTimeImmutable::createFromFormat('Y-m-d', substr($rd, 0, 10)) ?: new DateTimeImmutable($rd);
        if ($d <= $soonCut) {
            $nSoon++;
        }
    }
}
?>
<div class="cpt-head">
  <div>
    <h1 class="cpt-title">My contract / renewal</h1>
    <p class="cpt-lead mb-0">Dates for your agreement. Talk to your account owner before a renewal date if you want to change anything.</p>
  </div>
</div>
<?php if ($rows): ?>
<div class="cpt-kpis">
  <div class="cpt-kpi" style="--kpi-accent:#16a34a;--kpi-tint:#f0fdf4">
    <span class="cpt-kpi-ico"><i class="bi bi-check-circle-fill"></i></span>
    <span><span class="cpt-kpi-n"><?= (int) $nActive ?></span><span class="cpt-kpi-l d-block">Active</span></span>
  </div>
  <div class="cpt-kpi" style="--kpi-accent:#ea580c;--kpi-tint:#fff7ed">
    <span class="cpt-kpi-ico"><i class="bi bi-hourglass-split"></i></span>
    <span><span class="cpt-kpi-n"><?= (int) $nSoon ?></span><span class="cpt-kpi-l d-block">Renewing soon</span></span>
  </div>
  <div class="cpt-kpi" style="--kpi-accent:#6b7280;--kpi-tint:#f3f4f6">
    <span class="cpt-kpi-ico"><i class="bi bi-x-circle-fill"></i></span>
    <span><span class="cpt-kpi-n"><?= (int) $nEnded ?></span><span class="cpt-kpi-l d-block">Ended</span></span>
  </div>
  <div class="cpt-kpi" style="--kpi-accent:#2563eb;--kpi-tint:#eff6ff">
    <span class="cpt-kpi-ico"><i class="bi bi-file-earmark-ruled"></i></span>
    <span><span class="cpt-kpi-n"><?= count($rows) ?></span><span class="cpt-kpi-l d-block">All</span></span>
  </div>
</div>
<?php endif; ?>
<?php if (empty($rows)): ?>
  <div class="cpt-empty"><i class="bi bi-file-earmark-ruled"></i><h2>No contract on file</h2><p class="mb-0">When a contract is shared, the dates show here.</p></div>
<?php else: foreach ($rows as $i => $r):
    $stCode = (string) $r['status'];
    $st = cpt_status_label($stCode);
    $rd = (string) ($r['renewal_date'] ?? '');
    $days = null;
    $soon = false;
    $overdue = false;
    $isRenewal = !empty($r['renewed_from_id']) || str_starts_with((string) $r['title'], 'Renewal: ');
    $isCurrent = $i === 0;
    if ($rd !== '' && $stCode !== 'expired' && $stCode !== 'cancelled') {
        $d = DateTimeImmutable::createFromFormat('Y-m-d', substr($rd, 0, 10)) ?: new DateTimeImmutable($rd);
        $d = $d->setTime(0, 0);
        $days = (int) $today->diff($d)->format('%r%a');
        $overdue = $days < 0;
        $soon = $days <= 60;
    }
    $tone = $overdue ? 'alert' : ($soon ? 'progress' : $st['tone']);
    $whenLabel = '';
    if ($overdue) {
        $whenLabel = abs((int) $days) === 1 ? '1 day late' : abs((int) $days) . ' days late';
    } elseif ($soon && $days !== null) {
        $whenLabel = $days === 0 ? 'Today' : ($days === 1 ? 'Tomorrow' : 'In ' . $days . ' days');
    }
?>
  <div class="cpt-item cpt-tone-<?= e($tone) ?>">
    <div class="cpt-item-main">
      <div class="cpt-item-ico"><i class="bi bi-arrow-repeat"></i></div>
      <div class="min-w-0 flex-grow-1">
        <div class="cpt-item-name">
          <?= e($r['title']) ?>
          <?php if ($isCurrent): ?> <span class="cpt-pill is-paid">Current</span><?php endif; ?>
        </div>
        <div class="cpt-item-sub">
          <span><i class="bi bi-hash"></i> <?= e($r['number']) ?></span>
          <?php if ($isRenewal): ?><span>Renewal</span><?php endif; ?>
          <span><i class="bi bi-calendar3"></i> Start <?= e(dt_fmt($r['start_date'])) ?></span>
          <span>End <?= e(dt_fmt($r['end_date'])) ?></span>
          <span>Renews <?= e(dt_fmt($r['renewal_date'])) ?></span>
        </div>
      </div>
      <div class="cpt-item-amt">
        <strong><?= e(money_fmt($r['amount'])) ?></strong>
        <span><?= $whenLabel !== '' ? e($whenLabel) : 'Contract' ?></span>
      </div>
      <span class="<?= e($st['pill']) ?>"><?= e($st['text']) ?></span>
    </div>
    <?php if (!empty($r['file_name'])): ?>
      <div class="cpt-item-actions">
        <a class="btn btn-sm btn-outline-primary" href="<?= e(url('contract/' . $r['id'] . '/file')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-file-earmark-pdf"></i> Open PDF</a>
      </div>
    <?php endif; ?>
  </div>
<?php endforeach; endif; ?>
