<?php
$r = $row ?? [];
$notes = $notes ?? [];
$assignees = $assignees ?? [];
$st = job_status_label((string) ($r['status'] ?? 'open'));
$tone = $st['tone'];
$heroTone = match ($tone) {
    'done' => 'won',
    'cancelled' => 'cancelled',
    'progress' => 'progress',
    default => 'open',
};
$subject = trim((string) ($r['subject'] ?? ''));
if ($subject === '') {
    $subject = (string) ($r['number'] ?? 'Job');
}
$account = trim((string) ($r['account_name'] ?? ''));
$assignee = trim((string) ($r['assignee_name'] ?? ''));
$body = trim((string) ($r['body'] ?? ''));
$source = match ((string) ($r['source'] ?? '')) {
    'customer' => 'Customer Portal',
    'deal_won' => 'Won deal',
    default => 'Staff',
};
$visitWhen = !empty($r['visit_at']) ? dt_fmt($r['visit_at'], 'M j, Y g:i A') : '';
$jobIcon = match ($tone) {
    'progress' => 'bi-arrow-repeat',
    'done' => 'bi-check2-circle',
    'cancelled' => 'bi-x-circle',
    default => 'bi-clipboard2-check',
};
?>
<div class="rec-page vis-page vis-tone-<?= e($tone) ?>">
  <a class="rec-back" href="<?= e(url('jobs')) ?>"><i class="bi bi-arrow-left"></i> All jobs</a>

  <div class="rec-hero rec-tone-<?= e($heroTone) ?>">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar job-hero-<?= e($tone) ?>"><i class="bi <?= e($jobIcon) ?>"></i></div>
      <div class="min-w-0">
        <p class="rec-kicker">Service job · <?= e((string) ($r['number'] ?? '')) ?></p>
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($subject) ?></h1>
          <span class="due-pill <?= e($st['class']) ?>"><?= e($st['text']) ?></span>
        </div>
        <div class="rec-hero-sub">
          <?php if ($account !== ''): ?>
            <a href="<?= e(url('accounts/' . (int) $r['account_id'])) ?>"><i class="bi bi-buildings"></i> <?= e($account) ?></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; ?>
          <span><i class="bi bi-box-arrow-in-right"></i> <?= e($source) ?></span>
        </div>
        <?php if ($visitWhen !== '' && $visitWhen !== '—'): ?>
        <div class="rec-hero-contact">
          <span><i class="bi bi-calendar3"></i> <?= e($visitWhen) ?></span>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <div class="rec-hero-actions">
      <p class="rec-action-hint"><?= $tone === 'done' ? 'This job is done.' : ($tone === 'cancelled' ? 'This job was cancelled.' : 'Update status when work starts or finishes.') ?></p>
      <a class="btn btn-outline-primary" href="<?= e(url('accounts/' . (int) $r['account_id'])) ?>"><i class="bi bi-buildings"></i> Customer</a>
    </div>
  </div>

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

      <?php if (can_edit('service_jobs')): ?>
      <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' => 'What was done on this job.',
        ]); ?>
        <form class="ajax-form" action="<?= e(url('jobs/' . (int) $r['id'] . '/notes')) ?>" method="post">
          <?= csrf_field() ?>
          <label class="form-label" for="job-notes">Note</label>
          <textarea class="form-control mb-3" id="job-notes" name="body" rows="3" required placeholder="Parts used, time on site, 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' => 'Job notes',
            'hint' => 'Earlier notes on this ticket.',
        ]); ?>
        <?php if (!$notes): ?>
          <p class="rec-section-hint mb-0">No job notes yet. Add the first one above.</p>
        <?php else: ?>
          <div class="rec-status-tl">
            <?php foreach ($notes as $i => $n):
                $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(trim((string) ($n['author_name'] ?? '')) ?: 'Note') ?></strong>
                    <?php if ($isNow): ?><span class="rec-status-tl-now">Latest</span><?php endif; ?>
                  </div>
                  <?php if (!empty($n['body'])): ?><div class="small"><?= nl2br(e((string) $n['body'])) ?></div><?php endif; ?>
                  <div class="small text-muted"><?= e(dt_fmt($n['created_at'] ?? null, 'M j, Y g:i A')) ?></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 job',
          'hint' => 'Ticket facts.',
          'icon' => 'bi-clipboard2-check',
          'facts' => [
              ['label' => 'Job number', 'value' => (string) ($r['number'] ?? '')],
              ['label' => 'Customer', 'value' => $account, 'href' => url('accounts/' . (int) ($r['account_id'] ?? 0))],
              ['label' => 'Subject', 'value' => $subject],
              ['label' => 'Visit date', 'value' => $visitWhen],
              ['label' => 'Assigned', 'value' => $assignee !== '' ? $assignee : 'Unassigned'],
              ['label' => 'Status', 'value' => $st['text']],
              ['label' => 'Source', 'value' => $source],
          ],
      ]); ?>

      <?php if (can_edit('service_jobs')): ?>
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-sliders',
            'title' => 'Update',
            'hint' => 'Status and who owns the ticket.',
        ]); ?>
        <form class="ajax-form" action="<?= e(url('jobs/' . (int) $r['id'])) ?>" method="post">
          <?= csrf_field() ?>
          <label class="form-label" for="job-status">Status</label>
          <select class="form-select mb-2" id="job-status" name="status">
            <?php foreach (['open' => 'Open', 'in_progress' => 'In progress', 'done' => 'Done', 'cancelled' => 'Cancelled'] as $k => $lab): ?>
              <option value="<?= e($k) ?>" <?= ($r['status'] ?? '') === $k ? 'selected' : '' ?>><?= e($lab) ?></option>
            <?php endforeach; ?>
          </select>
          <label class="form-label" for="job-assignee">Assigned person</label>
          <select class="form-select mb-3" id="job-assignee" name="assignee_id">
            <option value="">—</option>
            <?php foreach ($assignees as $sp): ?>
              <option value="<?= (int) $sp['id'] ?>" <?= (int) ($r['assignee_id'] ?? 0) === (int) $sp['id'] ? 'selected' : '' ?>><?= e(trim($sp['first_name'] . ' ' . $sp['last_name'])) ?></option>
            <?php endforeach; ?>
          </select>
          <button class="btn btn-outline-primary" type="submit"><i class="bi bi-check2"></i> Save</button>
        </form>
      </div>
      <?php endif; ?>

      <?php \App\Core\View::partial('related_task_box', [
          'relatedType' => 'account',
          'relatedId' => (int) ($r['account_id'] ?? 0),
          'tasks' => $tasks ?? [],
          'ownerId' => (int) ($r['assignee_id'] ?? 0),
          'empty' => 'No tasks for this customer yet.',
          'boxId' => 'job-tasks',
          'hint' => 'Follow-ups after this job.',
      ]); ?>
    </div>
  </div>
</div>
