<?php
$v = $visit ?? [];
$name = trim((string) ($v['name'] ?? ''));
if ($name === '') {
    $name = 'Visit';
}
$status = visit_status_label($v);
$attended = $status['tone'] === 'done';
$tone = $status['tone'];
$pillText = $status['text'];
$pillClass = $status['class'];
$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'] ?? ''));
$assignee = trim((string) ($v['assignee_name'] ?? ''));
$visitFeed = $visitFeed ?? [];
$subject = trim((string) ($v['visit_subject'] ?? ''));
$detail = trim((string) ($v['visit_detail'] ?? ''));
$title = visit_subject($v);
?>
<div class="rec-page vis-page vis-tone-<?= e($tone) ?>">
  <a class="rec-back" href="<?= e(url('service')) ?>"><i class="bi bi-arrow-left"></i> All visits</a>

  <div class="rec-hero rec-tone-open">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar vis-hero-<?= e($tone) ?>"><i class="bi bi-geo-alt-fill"></i></div>
      <div class="min-w-0">
        <p class="rec-kicker">Service visit<?= $name !== '' && $name !== $title ? ' · ' . $name : ' · site work' ?></p>
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($title) ?></h1>
          <span class="due-pill <?= e($pillClass) ?>"><?= e($pillText) ?></span>
        </div>
        <div class="rec-hero-sub">
          <?php if ($loc !== ''): ?>
            <span><i class="bi bi-geo"></i> <?= e($loc) ?></span>
          <?php endif; ?>
          <?php if ($phone !== ''): ?>
            <a href="tel:<?= e(preg_replace('/\s+/', '', $phone)) ?>"><i class="bi bi-telephone"></i> <?= e($phone) ?></a>
          <?php endif; ?>
          <?php if ($assignee !== ''): ?>
            <span class="task-owner-chip" title="<?= e($assignee) ?>">
              <span class="task-avatar"><?= e(name_initials($assignee)) ?></span>
              <span class="task-owner text-truncate"><?= e($assignee) ?></span>
            </span>
          <?php endif; ?>
        </div>
        <?php if (!empty($v['next_visit_at']) || !empty($v['last_visit_at'])): ?>
        <div class="rec-hero-contact">
          <?php if (!empty($v['next_visit_at'])): ?>
            <span><i class="bi bi-calendar3"></i> <?= e(dt_fmt($v['next_visit_at'], 'M j, Y g:i A')) ?></span>
          <?php endif; ?>
          <?php if (!empty($v['last_visit_at'])): ?>
            <span><i class="bi bi-clock-history"></i> Last <?= e(dt_fmt($v['last_visit_at'], 'M j, Y')) ?></span>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <div class="rec-hero-actions">
      <p class="rec-action-hint"><?= $attended ? 'This visit is done.' : 'Mark attended when you have been on site.' ?></p>
      <?php if (!$attended && can_edit('service_visits')): ?>
        <form class="ajax-form" action="<?= e(url('service/' . (int) $v['id'] . '/attend')) ?>" method="post">
          <?= csrf_field() ?>
          <button class="btn btn-primary" type="submit"><i class="bi bi-check2-circle"></i> Mark as attended</button>
        </form>
      <?php endif; ?>
      <a class="btn btn-outline-primary" href="<?= e(url('accounts/' . (int) $v['id'])) ?>"><i class="bi bi-buildings"></i> Customer</a>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-lg-8">
      <?php if ($subject !== '' || $detail !== ''): ?>
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-clipboard2-pulse',
            'title' => 'Subject and details',
            'hint' => 'From this visit request.',
        ]); ?>
        <?php if ($subject !== ''): ?>
          <div class="vis-need-subject"><?= e($subject) ?></div>
        <?php endif; ?>
        <?php if ($detail !== ''): ?>
          <div class="vis-need-detail"><?= nl2br(e($detail)) ?></div>
        <?php else: ?>
          <p class="rec-section-hint mb-0">No extra notes on this request.</p>
        <?php endif; ?>
      </div>
      <?php endif; ?>

      <?php if (can_edit('service_visits')): ?>
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-journal-text',
            'title' => 'Add a note',
            'hint' => 'This stays on the visit. It does not mark it attended.',
        ]); ?>
        <form class="ajax-form" action="<?= e(url('service/notes')) ?>" method="post">
          <?= csrf_field() ?>
          <input type="hidden" name="account_id" value="<?= (int) $v['id'] ?>">
          <label class="form-label" for="vis-notes">Note</label>
          <textarea class="form-control mb-3" id="vis-notes" name="body" rows="3" required placeholder="What was done on site, parts used, or what the customer said."></textarea>
          <button class="btn btn-outline-primary" type="submit"><i class="bi bi-journal-text"></i> Save note</button>
        </form>
      </div>
      <?php endif; ?>

      <div class="card-soft rec-card p-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-clock-history',
            'title' => 'Visit notes',
            'hint' => 'Earlier notes from this site.',
        ]); ?>
        <?php if (!$visitFeed): ?>
          <p class="rec-section-hint mb-0">No visit notes yet. Add the first one above.</p>
        <?php else: ?>
          <div class="rec-status-tl">
            <?php foreach ($visitFeed as $i => $h):
                $isNow = $i === 0;
            ?>
              <div class="rec-status-tl-item <?= $isNow ? 'is-current' : '' ?>">
                <span class="rec-status-tl-dot"></span>
                <div class="min-w-0">
                  <div class="d-flex flex-wrap align-items-center gap-2">
                    <strong><?= e($h['subject'] ?: 'Visit notes') ?></strong>
                    <?php if ($isNow): ?><span class="rec-status-tl-now">Latest</span><?php endif; ?>
                  </div>
                  <?php if (!empty($h['body'])): ?><div class="small"><?= nl2br(e((string) $h['body'])) ?></div><?php endif; ?>
                  <div class="small text-muted">
                    <?= e($h['owner_name'] ?: 'Someone') ?>
                    · <?= e(dt_fmt($h['activity_at'] ?? null, 'M j, Y g:i A')) ?>
                    · <?= e(relative_when($h['activity_at'] ?? null)) ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="col-lg-4">
      <?php \App\Core\View::partial('record_facts', [
          'title' => 'About this visit',
          'hint' => 'Where to go.',
          'icon' => 'bi-geo-alt',
          'facts' => [
              ['label' => 'Customer', 'value' => $name, 'href' => url('accounts/' . (int) $v['id'])],
              ['label' => 'Subject', 'value' => $subject],
              ['label' => 'Visit date', 'value' => !empty($v['next_visit_at']) ? dt_fmt($v['next_visit_at'], 'M j, Y g:i A') : ''],
              ['label' => 'Address', 'value' => $loc],
              ['label' => 'Phone', 'value' => $phone],
              ['label' => 'Assigned', 'value' => $assignee !== '' ? $assignee : 'Unassigned'],
              ['label' => 'Status', 'value' => $pillText],
              ['label' => 'Last visit', 'value' => !empty($v['last_visit_at']) ? dt_fmt($v['last_visit_at'], 'M j, Y') : ''],
          ],
      ]); ?>
      <?php \App\Core\View::partial('related_task_box', [
          'relatedType' => 'account',
          'relatedId' => (int) $v['id'],
          'tasks' => $tasks ?? [],
          'ownerId' => (int) ($v['service_assignee_id'] ?: ($v['owner_id'] ?? 0)),
          'empty' => 'No tasks for this visit yet.',
          'boxId' => 'visit-tasks',
          'hint' => 'Follow-ups after this site visit.',
      ]); ?>
    </div>
  </div>
</div>
