<?php
$d = $data;
$hour = (int) date('G');
$hi = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
$visits = $d['visits'] ?? [];
$summaries = [
    ['Today', (int) ($d['today'] ?? 0), 'bi-geo-alt-fill', '#16a34a', '#f0fdf4', url('service') . '?when=today'],
    ['Late', (int) ($d['late'] ?? 0), 'bi-exclamation-circle-fill', '#ef4444', '#fef2f2', url('service') . '?when=late'],
    ['Coming up', (int) ($d['upcoming'] ?? 0), 'bi-clock-fill', '#ea580c', '#fff7ed', url('service') . '?when=soon'],
    ['Open work', (int) ($d['tasks_open'] ?? 0), 'bi-check2-square', '#2563eb', '#eff6ff', url('tasks')],
];
?>
<div class="svc-page">
  <div class="d-flex justify-content-between align-items-start dash-head">
    <div>
      <h1 class="page-title"><?= e($hi) ?>, <?= e(current_user()['first_name']) ?></h1>
      <p class="page-sub mb-0">Your sites, visits, and follow-up for today.</p>
    </div>
    <div class="d-flex flex-wrap align-items-center gap-2">
      <?php \App\Core\View::partial('smart_tips_jump', ['tips' => $tips ?? []]); ?>
      <div class="dash-date"><i class="bi bi-calendar3"></i> <?= date('M j, Y') ?></div>
    </div>
  </div>

  <?php if (dash_on('kpis')): ?>
  <div class="task-summary mb-3">
    <?php foreach ($summaries as $s): ?>
      <a class="task-summary-card" href="<?= e($s[5]) ?>" 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"><?= (int) $s[1] ?></div>
          <div class="task-summary-l"><?= e($s[0]) ?></div>
        </div>
      </a>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <div class="row g-3 mb-3">
    <?php if (dash_on('visits')): ?>
    <div class="col-lg-6">
      <div class="card-soft mv-card h-100">
        <div class="mv-head">
          <div class="mv-head-icon"><i class="bi bi-geo-alt-fill"></i></div>
          <div class="min-w-0 flex-grow-1">
            <h2>My visits</h2>
            <p><?= $visits ? count($visits) . ' sites on your list' : 'When you are assigned to a site, it shows here.' ?></p>
          </div>
          <a href="<?= e(url('service')) ?>">View all</a>
        </div>
        <?php if ($visits): ?>
          <div class="mv-pills">
            <?php if ((int) ($d['today'] ?? 0)): ?>
              <span class="mv-pill is-today"><i class="bi bi-sun"></i> <?= (int) $d['today'] ?> today</span>
            <?php endif; ?>
            <?php if ((int) ($d['late'] ?? 0)): ?>
              <span class="mv-pill is-late"><i class="bi bi-exclamation-circle"></i> <?= (int) $d['late'] ?> late</span>
            <?php endif; ?>
            <?php if ((int) ($d['upcoming'] ?? 0)): ?>
              <span class="mv-pill is-soon"><i class="bi bi-clock"></i> <?= (int) $d['upcoming'] ?> coming up</span>
            <?php endif; ?>
            <?php
              $doneN = 0;
              foreach ($visits as $visitRow) {
                  if (visit_attended($visitRow)) {
                      $doneN++;
                  }
              }
            ?>
            <?php if ($doneN): ?>
              <span class="mv-pill is-done"><i class="bi bi-check2-circle"></i> <?= $doneN ?> attended</span>
            <?php endif; ?>
          </div>
          <div class="mv-list">
            <?php foreach ($visits as $v):
                $attended = visit_attended($v);
                $status = visit_status_label($v);
                $tone = $status['tone'];
                $addr = trim((string) ($v['address_line'] ?? ''));
                $city = trim((string) ($v['city'] ?? ''));
                $state = trim((string) ($v['state'] ?? ''));
                $loc = trim($addr . (($addr !== '' && $city !== '') ? ' · ' : '') . $city . ($state !== '' ? ', ' . $state : ''));
                $phone = trim((string) ($v['phone'] ?? ''));
                $pill = $status['text'];
                $subject = visit_subject($v);
                $site = trim((string) ($v['name'] ?? ''));
                $visitWhen = !empty($v['next_visit_at']) ? dt_fmt($v['next_visit_at'], 'M j, Y g:i A') : '';
            ?>
              <div class="mv-item is-<?= e($tone) ?>">
                <a class="mv-item-main" href="<?= e(url('service/' . (int) $v['id'])) ?>">
                  <span class="mv-mark"><i class="bi <?= $attended ? 'bi-check2-circle' : 'bi-geo-alt-fill' ?>"></i></span>
                  <span class="min-w-0 flex-grow-1">
                    <span class="mv-name"><?= e($subject) ?></span>
                    <span class="mv-meta">
                      <?php if ($site !== '' && $site !== $subject): ?><span class="mv-loc text-truncate"><?= e($site) ?></span><?php endif; ?>
                      <?php if ($visitWhen !== '' && $visitWhen !== '—'): ?><span><i class="bi bi-calendar3"></i> <?= e($visitWhen) ?></span><?php endif; ?>
                      <?php if ($loc !== ''): ?><span class="mv-loc text-truncate"><?= e($loc) ?></span><?php endif; ?>
                      <?php if ($phone !== ''): ?><span><i class="bi bi-telephone"></i> <?= e($phone) ?></span><?php endif; ?>
                      <?php if ($visitWhen === '' && !empty($v['last_visit_at'])): ?><span>Last <?= e(dt_fmt($v['last_visit_at'], 'M j')) ?></span><?php endif; ?>
                    </span>
                  </span>
                  <span class="due-pill <?= e($status['class']) ?>"><?= e($pill) ?></span>
                </a>
                <?php if (!$attended && can_edit('service_visits')): ?>
                  <form class="ajax-form mv-attend" action="<?= e(url('service/' . (int) $v['id'] . '/attend')) ?>" method="post">
                    <?= csrf_field() ?>
                    <button class="btn btn-sm btn-outline-success" type="submit" title="Mark as attended"><i class="bi bi-check2-circle"></i> Attended</button>
                  </form>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <div class="mv-empty">
            <i class="bi bi-geo-alt"></i>
            <strong>No visits on your list</strong>
            <span>When you are assigned to a site, it shows here.</span>
          </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>
    <?php if (dash_on('tasks')): ?>
    <div class="col-lg-6">
      <?php \App\Core\View::partial('home_tasks', ['tasks' => $d['tasks'] ?? []]); ?>
    </div>
    <?php endif; ?>
  </div>

  <div class="row g-3 mb-3">
    <?php if (dash_on('upcoming') || dash_on('tasks')): ?>
    <div class="col-lg-6">
      <?php \App\Core\View::partial('home_upcoming', ['meetings' => $d['meetings'] ?? []]); ?>
    </div>
    <?php endif; ?>
    <?php if (dash_on('tasks')): ?>
    <div class="col-lg-6">
      <?php \App\Core\View::partial('home_recent', [
          'recent' => $d['recent'] ?? [],
          'title' => 'Recent notes',
          'emptyTitle' => 'No notes yet',
          'emptyHint' => 'Visit notes and follow-up will show up here.',
          'moreHref' => url('service'),
          'moreLabel' => 'Visits',
          'pillMap' => [
              'visit' => 'bi-geo-alt',
              'note' => 'bi-sticky',
              'call' => 'bi-telephone',
              'meeting' => 'bi-calendar-event',
          ],
      ]); ?>
    </div>
    <?php endif; ?>
  </div>
  <?php \App\Core\View::partial('smart_tips', ['tips' => $tips ?? [], 'kind' => 'service']); ?>
</div>
