<?php
$rows = $rows ?? [];
$kpiRows = $kpiRows ?? $rows;
$accounts = $accounts ?? [];
$assignees = $assignees ?? [];
$isServiceSetup = !empty($isServiceSetup);
$canRequest = can_edit('service_visits') && $isServiceSetup && $accounts !== [];
$meId = (int) (current_user()['id'] ?? 0);
$visitAtDefault = date('Y-m-d\TH:i');
$q = $q ?? '';
$when = $when ?? 'all';
$week = $week ?? 'all';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$today = $late = $soon = $done = 0;
foreach ($kpiRows as $r) {
    if (visit_attended($r)) {
        $done++;
        continue;
    }
    $due = due_label($r['next_visit_at'] ?? null);
    if (($due['class'] ?? '') === 'due-today') {
        $today++;
    } elseif (($due['class'] ?? '') === 'due-overdue') {
        $late++;
    } else {
        $soon++;
    }
}
$summaries = [
    ['Today', $today, 'bi-geo-alt-fill', '#16a34a', '#f0fdf4'],
    ['Late', $late, 'bi-exclamation-circle-fill', '#ef4444', '#fef2f2'],
    ['Coming up', $soon, 'bi-clock-fill', '#ea580c', '#fff7ed'],
    ['Attended', $done, 'bi-check2-circle', '#0f766e', '#f0fdfa'],
];
?>
<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">Service visits</h1>
      <p class="page-sub mb-0">Log a visit note and see who is assigned. Full tickets live under Service jobs.</p>
    </div>
    <?php if ($canRequest): ?>
      <a class="btn btn-primary" href="#svc-request"><i class="bi bi-plus-lg"></i> New request</a>
    <?php endif; ?>
  </div>

  <?php if ($isServiceSetup): ?>
  <div class="task-summary mb-3">
    <?php foreach ($summaries 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"><?= (int) $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 class="task-filter-search">
      <label class="form-label" for="svc-q">Search</label>
          <input class="form-control" id="svc-q" name="q" value="<?= e($q) ?>" placeholder="Search site, subject, or phone" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="svc-assigned">Assigned to</label>
      <select class="form-select" id="svc-assigned" name="assigned">
        <option value="0" <?= $assigned === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($assignees as $o): ?>
          <option value="<?= (int) $o['id'] ?>" <?= $assigned === (int) $o['id'] ? 'selected' : '' ?>><?= e(trim($o['first_name'] . ' ' . $o['last_name'])) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php endif; ?>
    <div>
      <label class="form-label" for="svc-when">When</label>
      <select class="form-select" id="svc-when" name="when">
        <option value="all" <?= $when === 'all' ? 'selected' : '' ?>>All</option>
        <option value="today" <?= $when === 'today' ? 'selected' : '' ?>>Today</option>
        <option value="late" <?= $when === 'late' ? 'selected' : '' ?>>Late</option>
        <option value="soon" <?= $when === 'soon' ? 'selected' : '' ?>>Coming up</option>
        <option value="attended" <?= $when === 'attended' ? 'selected' : '' ?>>Attended</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="svc-week">This week</label>
      <select class="form-select" id="svc-week" name="week">
        <option value="all" <?= $week === 'all' ? 'selected' : '' ?>>All</option>
        <option value="this" <?= $week === 'this' ? 'selected' : '' ?>>This week</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 endif; ?>

  <div class="row g-3">
    <div class="<?= $canRequest ? 'col-lg-7' : 'col-12' ?>">
      <?php if (!$isServiceSetup): ?>
        <div class="card-soft task-empty svc-wait">
          <div class="task-empty-icon"><i class="bi bi-tools"></i></div>
          <h2>Visit board waits on setup D</h2>
          <p>Ask an admin to pick industry setup <strong>D. Service</strong> in Settings. Then assigned person and late sites show here.</p>
          <div class="svc-wait-chips">
            <span class="lst-chip">Assigned technician / consultant</span>
            <span class="lst-chip">Notes on the customer</span>
          </div>
        </div>
      <?php elseif (!$rows): ?>
        <div class="card-soft task-empty">
          <div class="task-empty-icon"><i class="bi bi-geo-alt"></i></div>
          <h2>No visits on the list</h2>
          <p>Add a request with a visit date to see it here.</p>
        </div>
      <?php else: ?>
        <?php foreach ($rows as $r):
            $attended = visit_attended($r);
            $status = visit_status_label($r);
            $tone = $status['tone'];
            $owner = trim((string) ($r['assignee_name'] ?? ''));
            $last = dt_fmt($r['last_visit_at'] ?? null, 'M j');
            $pill = $status['text'];
            $subject = visit_subject($r);
            $site = trim((string) ($r['name'] ?? ''));
            $need = trim((string) ($r['visit_detail'] ?? ''));
            $visitWhen = !empty($r['next_visit_at']) ? dt_fmt($r['next_visit_at'], 'M j, Y g:i A') : '';
        ?>
          <div class="svc-visit svc-tone-<?= e($tone) ?>">
            <a class="svc-visit-main" href="<?= e(url('service/' . (int) $r['id'])) ?>">
              <div class="svc-visit-icon"><i class="bi <?= $attended ? 'bi-check2-circle' : 'bi-geo-alt-fill' ?>"></i></div>
              <div class="min-w-0 flex-grow-1">
                <div class="svc-visit-name"><?= e($subject) ?></div>
                <div class="svc-visit-sub">
                  <?php if ($site !== '' && $site !== $subject): ?><span><i class="bi bi-buildings"></i> <?= e($site) ?></span><?php endif; ?>
                  <?php if ($owner !== ''): ?><span><i class="bi bi-person"></i> <?= e($owner) ?></span><?php endif; ?>
                  <?php if ($visitWhen !== '' && $visitWhen !== '—'): ?>
                    <span><i class="bi bi-calendar3"></i> <?= e($visitWhen) ?></span>
                  <?php elseif ($last !== '' && $last !== '—'): ?>
                    <span>Last <?= e($last) ?></span>
                  <?php endif; ?>
                </div>
                <?php if ($need !== ''): ?>
                  <div class="svc-visit-need"><?= e($need) ?></div>
                <?php endif; ?>
              </div>
              <div class="task-meta">
                <span class="due-pill <?= e($status['class']) ?>"><?= e($pill) ?></span>
              </div>
            </a>
            <?php if (!$attended && can_edit('service_visits')): ?>
              <form class="ajax-form svc-attend" action="<?= e(url('service/' . (int) $r['id'] . '/attend')) ?>" method="post">
                <?= csrf_field() ?>
                <button class="btn btn-sm btn-outline-success" type="submit"><i class="bi bi-check2-circle"></i> Attended</button>
              </form>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <?php if ($canRequest): ?>
    <div class="col-lg-5" id="svc-request">
      <form class="svc-req ajax-form" action="<?= e(url('service/request')) ?>" method="post">
        <?= csrf_field() ?>
        <div class="svc-req-head">
          <span class="svc-req-icon"><i class="bi bi-clipboard2-plus"></i></span>
          <div>
            <div class="svc-req-kicker">Service request</div>
            <h2>Add a visit to the list</h2>
            <p>Pick the site, the date, and what is needed. It shows on Service visits.</p>
          </div>
        </div>
        <div class="svc-req-body">
          <?php if (show_field('service_request', 'account_id')): ?>
          <label class="form-label"><?= e(noun('account', 'Account')) ?> *</label>
          <select class="form-select mb-2" name="account_id" required>
            <option value="">Select a site</option>
            <?php foreach ($accounts as $acc): ?><option value="<?= (int) $acc['id'] ?>"><?= e($acc['name']) ?></option><?php endforeach; ?>
          </select>
          <?php endif; ?>
          <label class="form-label" for="svc-subject">Subject *</label>
          <input class="form-control mb-2" id="svc-subject" name="subject" maxlength="180" required placeholder="Paper jam, toner, install…">
          <label class="form-label" for="svc-visit-at">Visit date *</label>
          <input class="form-control mb-2" id="svc-visit-at" type="datetime-local" name="visit_at" value="<?= e($visitAtDefault) ?>" required>
          <?php if ($showAssigned && show_field('service_request', 'service_assignee_id')): ?>
          <label class="form-label" for="svc-req-assigned">Assigned to</label>
          <select class="form-select mb-2" id="svc-req-assigned" name="service_assignee_id">
            <?php foreach ($assignees as $o): ?>
              <option value="<?= (int) $o['id'] ?>" <?= (int) $o['id'] === $meId ? 'selected' : '' ?>><?= e(trim($o['first_name'] . ' ' . $o['last_name'])) ?></option>
            <?php endforeach; ?>
          </select>
          <?php endif; ?>
          <label class="form-label" for="svc-body">Details *</label>
          <textarea class="form-control mb-2" id="svc-body" name="body" rows="4" required placeholder="What is wrong and what should happen next."></textarea>
          <?php \App\Core\View::partial('industry_fields', ['fields' => entity_fields('service'), 'values' => [], 'form' => 'service_request']); ?>
          <div class="svc-req-foot">
            <div class="svc-wait-chips">
              <span class="lst-chip">On this list</span>
              <span class="lst-chip">Not a job ticket</span>
            </div>
            <button class="btn btn-primary" type="submit"><i class="bi bi-check2"></i> Add visit</button>
          </div>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>
