<?php
$weekDelta = $createdThisWeek - $createdPriorWeek;
$weekDeltaClass = $weekDelta > 0 ? 'is-flat' : ($weekDelta < 0 ? 'is-good' : 'is-flat');
$weekDeltaArrow = $weekDelta > 0 ? '↑' : ($weekDelta < 0 ? '↓' : '→');

$resolvedDelta = $resolvedMtd - $resolvedSamePaceLastMonth;
$resolvedDeltaClass = $resolvedDelta > 0 ? 'is-good' : ($resolvedDelta < 0 ? 'is-bad' : 'is-flat');
$resolvedDeltaArrow = $resolvedDelta > 0 ? '↑' : ($resolvedDelta < 0 ? '↓' : '→');

$csatBand = $csatAvg === null ? 'slate' : ($csatAvg >= 4.5 ? 'green' : ($csatAvg >= 3.5 ? 'amber' : 'red'));
?>
<h1 style="font-size:19px;margin-bottom:2px"><?= e($greeting) ?> 👋</h1>
<p class="text-faint" style="margin-bottom:20px">
  <?php if ($breached > 0) : ?>
    <strong style="color:var(--red)"><?= $breached ?></strong> ticket<?= $breached === 1 ? '' : 's' ?> breached and <strong><?= $dueSoon ?></strong> due within 4 hours — that's where to start.
  <?php elseif ($dueSoon > 0) : ?>
    Nothing breached right now. <strong><?= $dueSoon ?></strong> ticket<?= $dueSoon === 1 ? '' : 's' ?> due within 4 hours.
  <?php else : ?>
    No breaches and nothing due imminently — the queue is under control.
  <?php endif; ?>
</p>

<div class="stat-grid">
  <div class="stat-card stat-card-hover">
    <div class="stat-card-head">
      <span class="stat-label">Open Tickets</span>
      <span class="stat-icon stat-icon-blue">📥</span>
    </div>
    <div class="stat-value"><?= $openTickets ?></div>
    <div class="stat-sub">of <?= $totalTickets ?> total</div>
    <div class="stat-delta <?= $weekDeltaClass ?>"><?= $weekDeltaArrow ?> <?= abs($weekDelta) ?> vs last week's <?= $createdPriorWeek ?> created</div>
  </div>

  <div class="stat-card stat-card-hover">
    <div class="stat-card-head">
      <span class="stat-label">SLA Breached</span>
      <span class="stat-icon stat-icon-red">⚠️</span>
    </div>
    <div class="stat-value stat-red"><?= $breached ?></div>
    <div class="stat-sub"><?= $openTickets ? round(($breached / $openTickets) * 100) : 0 ?>% of open tickets</div>
  </div>

  <div class="stat-card stat-card-hover">
    <div class="stat-card-head">
      <span class="stat-label">Due in 4 Hrs</span>
      <span class="stat-icon stat-icon-amber">⏰</span>
    </div>
    <div class="stat-value stat-amber"><?= $dueSoon ?></div>
    <div class="stat-sub">at-risk queue</div>
  </div>

  <div class="stat-card stat-card-hover">
    <div class="stat-card-head">
      <span class="stat-label">Resolved (MTD)</span>
      <span class="stat-icon stat-icon-green">✅</span>
    </div>
    <div class="stat-value stat-green"><?= $resolvedMtd ?></div>
    <div class="stat-sub">FCR <?= $fcr !== null ? $fcr . '%' : '—' ?></div>
    <div class="stat-delta <?= $resolvedDeltaClass ?>"><?= $resolvedDeltaArrow ?> <?= abs($resolvedDelta) ?> vs same pace last month</div>
  </div>

  <div class="stat-card stat-card-hover">
    <div class="stat-card-head">
      <span class="stat-label">CSAT (90d)</span>
      <span class="stat-icon stat-icon-<?= $csatBand ?>">⭐</span>
    </div>
    <div class="stat-value"><?= $csatAvg ?? '—' ?><span style="font-size:14px;color:var(--ink-faint)"> / 5</span></div>
    <div class="stat-sub"><?= $csatCount ?> response<?= $csatCount === 1 ? '' : 's' ?></div>
  </div>
</div>

<div class="ticket-grid" style="grid-template-columns: 1fr 320px;">
  <div class="card">
    <div class="card-header">
      <h3>Tickets requiring attention</h3>
      <a href="<?= url('/tickets') ?>" class="text-sm">View all →</a>
    </div>
    <div class="table-wrap">
      <table class="table">
        <thead><tr><th>Ticket No.</th><th>Customer</th><th>Subject</th><th>Pri</th><th>Assignee</th><th>SLA due</th><th>Status</th></tr></thead>
        <tbody>
        <?php if (empty($attention)) : ?>
          <tr><td colspan="7"><div class="empty-state"><div class="icon">✅</div>Nothing needs attention right now.</div></td></tr>
        <?php endif; ?>
        <?php foreach ($attention as $t) : ?>
          <tr>
            <td><a class="row-link mono" href="<?= url('/tickets/' . $t['id']) ?>"><?= e($t['ticket_no']) ?></a></td>
            <td><?= e($t['customer_name']) ?></td>
            <td style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= e($t['subject']) ?></td>
            <td><?= priority_badge(['code' => $t['p_code'], 'color' => $t['p_color']]) ?></td>
            <td><?= e($t['assignee_name'] ?? 'Unassigned') ?></td>
            <td>
              <?php if ($t['is_resolution_breached']) : ?><span class="badge badge-breach">BREACHED</span>
              <?php else : ?><span class="text-sm"><?= fmt_remaining($t['resolution_due_at'], false) ?></span><?php endif; ?>
            </td>
            <td><span class="<?= status_badge_class($t['status']) ?>"><?= status_label($t['status']) ?></span></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="side-panel">
    <div class="card">
      <div class="card-header"><h3>Volume by day</h3><span class="text-faint text-sm">last 7 days</span></div>
      <div class="card-body">
        <?php
          $max = max(1, ...array_map(fn($r) => (int)$r['c'], $volumeByDay) ?: [1]);
          $today = date('Y-m-d');
        ?>
        <div class="vol-chart">
          <?php for ($i = 6; $i >= 0; $i--) :
              $d = date('Y-m-d', strtotime("-$i day"));
              $row = current(array_filter($volumeByDay, fn($r) => $r['d'] === $d));
              $c = $row ? (int)$row['c'] : 0;
              $h = max(3, (int)round(($c / $max) * 80));
              $isToday = $d === $today;
          ?>
            <div class="vol-bar-col <?= $isToday ? 'is-today' : '' ?>" title="<?= e(date('D d M', strtotime($d))) ?>: <?= $c ?> ticket<?= $c === 1 ? '' : 's' ?>">
              <div class="vol-bar-value"><?= $c > 0 ? $c : '' ?></div>
              <div class="vol-bar" style="height:<?= $h ?>px"></div>
              <div class="vol-bar-day"><?= e(date('D', strtotime($d))[0]) ?></div>
            </div>
          <?php endfor; ?>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><h3>SLA compliance — MTD</h3></div>
      <div class="card-body">
        <?php
          $meters = [
            ['label' => 'First response', 'pct' => $firstRespPct, 'target' => 95],
            ['label' => 'Resolution', 'pct' => $resPct, 'target' => 90],
            ['label' => 'P1 resolution', 'pct' => $p1ResPct, 'target' => 95],
          ];
        ?>
        <?php foreach ($meters as $i => $m) :
          $pct = $m['pct'] ?? 0;
          $onTarget = $pct >= $m['target'];
          $tone = $onTarget ? 'green' : ($pct >= $m['target'] - 15 ? 'amber' : 'red');
        ?>
          <div class="<?= $i > 0 ? 'mt-3' : '' ?>">
            <div class="flex justify-between">
              <span class="text-sm text-faint"><?= e($m['label']) ?></span>
              <strong class="text-sm"><?= $m['pct'] ?? '—' ?>%</strong>
            </div>
            <div class="progress" style="background:var(--<?= $tone ?>-bg);position:relative">
              <div class="progress-bar" style="width:<?= min(100, $pct) ?>%;background:var(--<?= $tone ?>)"></div>
              <div style="position:absolute;top:-2px;bottom:-2px;left:<?= min(100, $m['target']) ?>%;width:2px;background:var(--ink-faint);opacity:.4" title="Target <?= $m['target'] ?>%"></div>
            </div>
          </div>
        <?php endforeach; ?>
        <div class="text-faint text-sm mt-3">Target: 95% response / 90% resolution · tick mark shows the target</div>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><h3>By category</h3></div>
      <div class="card-body">
        <?php $catMax = max(1, ...array_map(fn($r) => (int)$r['c'], $byCategory) ?: [1]); ?>
        <?php foreach ($byCategory as $cat) : ?>
          <div class="mini-bar-row">
            <span class="mini-bar-label" title="<?= e($cat['name']) ?>"><?= e($cat['name']) ?></span>
            <span class="mini-bar-track"><span class="mini-bar-fill" style="width:<?= round(($cat['c'] / $catMax) * 100) ?>%"></span></span>
            <span class="mini-bar-value"><?= $cat['c'] ?></span>
          </div>
        <?php endforeach; ?>
        <?php if (empty($byCategory)) : ?><div class="text-faint text-sm">No open tickets yet.</div><?php endif; ?>
      </div>
    </div>
  </div>
</div>
