<?php
$rows = $rows ?? [];
$when = $when ?? 'all';
$bucketOf = static function (?string $date): array {
    if (!$date) {
        return ['key' => 'later', 'days' => null, 'label' => 'No date'];
    }
    $today = new DateTimeImmutable('today');
    $raw = DateTimeImmutable::createFromFormat('Y-m-d', substr($date, 0, 10));
    $d = $raw ?: new DateTimeImmutable($date);
    $d = $d->setTime(0, 0);
    $days = (int) $today->diff($d)->format('%r%a');
    if ($days < 0) {
        $n = abs($days);
        return ['key' => 'overdue', 'days' => $days, 'label' => $n === 1 ? '1 day late' : $n . ' days late'];
    }
    if ($days === 0) {
        return ['key' => 'week', 'days' => 0, 'label' => 'Today'];
    }
    if ($days === 1) {
        return ['key' => 'week', 'days' => 1, 'label' => 'Tomorrow'];
    }
    if ($days <= 7) {
        return ['key' => 'week', 'days' => $days, 'label' => 'In ' . $days . ' days'];
    }
    return ['key' => 'later', 'days' => $days, 'label' => 'In ' . $days . ' days'];
};
$nOverdue = 0;
$nWeek = 0;
$nLater = 0;
$atRisk = 0.0;
$prepared = [];
foreach ($rows as $r) {
    $b = $bucketOf($r['renewal_date'] ?? null);
    $r['_bucket'] = $b;
    $atRisk += (float) $r['amount'];
    if ($b['key'] === 'overdue') {
        $nOverdue++;
    } elseif ($b['key'] === 'week') {
        $nWeek++;
    } else {
        $nLater++;
    }
    $prepared[] = $r;
}
$shown = $when === 'all' ? $prepared : array_values(array_filter($prepared, static fn($r) => ($r['_bucket']['key'] ?? '') === $when));
$pill = ['overdue' => 'due-overdue', 'week' => 'due-later', 'later' => 'due-window'];
$tone = ['overdue' => 'late', 'week' => 'progress', 'later' => 'open'];
?>
<div class="svc-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Renewals</h1>
      <p class="page-sub mb-0">Contracts due to renew in the next 60 days. Send a renewal contract to start a new term with the same customer and amount.</p>
    </div>
  </div>
  <div class="task-summary mb-3">
    <?php foreach ([
        ['Overdue', $nOverdue, 'bi-exclamation-circle-fill', '#ef4444', '#fef2f2'],
        ['This week', $nWeek, 'bi-hourglass-split', '#ea580c', '#fff7ed'],
        ['Later', $nLater, 'bi-calendar-event', '#2563eb', '#eff6ff'],
        ['At risk', money_fmt($atRisk), 'bi-cash-stack', '#7c3aed', '#f5f3ff'],
    ] as $s): ?>
      <div class="task-summary-card" style="--task-accent: <?= e($s[3]) ?>; --task-tint: <?= e($s[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($s[2]) ?>"></i></div>
        <div><div class="task-summary-n"><?= is_int($s[1]) ? (int) $s[1] : e((string) $s[1]) ?></div><div class="task-summary-l"><?= e($s[0]) ?></div></div>
      </div>
    <?php endforeach; ?>
  </div>
  <form class="task-filters opp-filters card-soft p-3 mb-3" method="get">
    <div>
      <label class="form-label" for="ren-when">When</label>
      <select class="form-select" id="ren-when" name="when">
        <option value="all" <?= $when === 'all' ? 'selected' : '' ?>>All</option>
        <option value="overdue" <?= $when === 'overdue' ? 'selected' : '' ?>>Overdue</option>
        <option value="week" <?= $when === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="later" <?= $when === 'later' ? 'selected' : '' ?>>Later</option>
      </select>
    </div>
    <div class="task-filter-go">
      <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i> Search</button>
    </div>
  </form>
  <?php if (!$prepared): ?>
    <div class="card-soft task-empty"><div class="task-empty-icon"><i class="bi bi-arrow-repeat"></i></div><h2>Nothing due soon</h2><p>When a contract has a renewal date in the next 60 days, it shows here.</p></div>
  <?php elseif (!$shown): ?>
    <div class="card-soft task-empty"><div class="task-empty-icon"><i class="bi bi-funnel"></i></div><h2>Nothing in this view</h2><p>Try another filter.</p></div>
  <?php else: foreach ($shown as $r):
      $b = $r['_bucket'];
      $key = (string) $b['key'];
  ?>
    <div class="svc-visit svc-tone-<?= e($tone[$key] ?? 'open') ?>">
      <a class="svc-visit-main" href="<?= e(url('contracts/' . (int) $r['id'])) ?>">
        <div class="svc-visit-icon"><i class="bi bi-arrow-repeat"></i></div>
        <div class="min-w-0 flex-grow-1">
          <div class="svc-visit-name"><?= e($r['title']) ?></div>
          <div class="svc-visit-sub">
            <span><i class="bi bi-hash"></i> <?= e($r['number']) ?></span>
            <?php if (!empty($r['account_name'])): ?><span><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></span><?php endif; ?>
            <?php if (!empty($r['owner_name'])): ?><span><i class="bi bi-person"></i> <?= e($r['owner_name']) ?></span><?php endif; ?>
            <?php if (!empty($r['renewal_date'])): ?><span><i class="bi bi-calendar3"></i> Renews <?= e(dt_fmt($r['renewal_date'])) ?></span><?php endif; ?>
          </div>
        </div>
        <div class="task-meta">
          <div class="svc-visit-amt"><strong><?= e(money_fmt($r['amount'])) ?></strong><span><?= e($b['label']) ?></span></div>
          <span class="due-pill <?= e($pill[$key] ?? 'due-later') ?>"><?= e($b['label']) ?></span>
        </div>
      </a>
      <?php if (can_edit('contracts')): ?>
        <a class="btn btn-sm btn-primary svc-attend" href="<?= e(url('contracts') . '?' . http_build_query(['renew_from' => (int) $r['id']]) . '#contract-form') ?>"><i class="bi bi-send"></i> Send renewal</a>
      <?php endif; ?>
    </div>
  <?php endforeach; endif; ?>
</div>
