<?php
$rows = $rows ?? [];
$counts = $counts ?? [];
$q = $q ?? '';
$status = $status ?? 'open';
$source = $source ?? 'all';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$accounts = $accounts ?? [];
$assignees = $assignees ?? [];
$page = (int) ($page ?? 1);
$pages = (int) ($pages ?? 1);
$canEdit = can_edit('service_jobs');
$summaries = [
    ['Open', $counts['open'] ?? 0, 'bi-circle', '#2563eb', '#eff6ff'],
    ['In progress', $counts['in_progress'] ?? 0, 'bi-arrow-repeat', '#ea580c', '#fff7ed'],
    ['Done', $counts['done'] ?? 0, 'bi-check-circle-fill', '#16a34a', '#f0fdf4'],
    ['All', $counts['all'] ?? 0, 'bi-clipboard2-check', '#0f766e', '#f0fdfa'],
];
$jobIcon = static function (string $tone): string {
    return match ($tone) {
        'progress' => 'bi-arrow-repeat',
        'done' => 'bi-check2-circle',
        'cancelled' => 'bi-x-circle',
        default => 'bi-clipboard2-check',
    };
};
$sourceLabel = static function (string $src): string {
    return match ($src) {
        'customer' => 'Customer Portal',
        'deal_won' => 'Won deal',
        default => '',
    };
};
?>
<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 jobs</h1>
      <p class="page-sub mb-0">Work orders with a job number, the problem, who is assigned, and status.</p>
    </div>
    <?php if ($canEdit && $accounts !== []): ?>
      <a class="btn btn-primary" href="#job-create"><i class="bi bi-plus-lg"></i> New job</a>
    <?php endif; ?>
  </div>

  <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="job-q">Search</label>
      <input class="form-control" id="job-q" name="q" value="<?= e($q) ?>" placeholder="Search subject, job number, or account" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="job-assigned">Assigned to</label>
      <select class="form-select" id="job-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="job-status">Status</label>
      <select class="form-select" id="job-status" name="status">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All</option>
        <option value="open" <?= $status === 'open' ? 'selected' : '' ?>>Open</option>
        <option value="in_progress" <?= $status === 'in_progress' ? 'selected' : '' ?>>In progress</option>
        <option value="done" <?= $status === 'done' ? 'selected' : '' ?>>Done</option>
        <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="job-source">Source</label>
      <select class="form-select" id="job-source" name="source">
        <option value="all" <?= $source === 'all' ? 'selected' : '' ?>>All</option>
        <option value="staff" <?= $source === 'staff' ? 'selected' : '' ?>>Staff</option>
        <option value="customer" <?= $source === 'customer' ? 'selected' : '' ?>>Customer Portal</option>
        <option value="deal_won" <?= $source === 'deal_won' ? 'selected' : '' ?>>Won deal</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>

  <div class="row g-3">
    <div class="col-lg-7">
      <?php if (!$rows): ?>
        <div class="card-soft task-empty">
          <div class="task-empty-icon"><i class="bi bi-clipboard2-check"></i></div>
          <h2>No jobs</h2>
          <p>Try another filter, or open a job from a won deal or the form.</p>
        </div>
      <?php else: foreach ($rows as $r):
          $st = job_status_label((string) ($r['status'] ?? 'open'));
          $need = trim((string) ($r['body'] ?? ''));
          $from = $sourceLabel((string) ($r['source'] ?? ''));
          $owner = trim((string) ($r['assignee_name'] ?? ''));
          $visitWhen = !empty($r['visit_at']) ? dt_fmt($r['visit_at'], 'M j, Y g:i A') : '';
      ?>
        <div class="svc-visit svc-tone-<?= e($st['tone']) ?>">
          <a class="svc-visit-main" href="<?= e(url('jobs/' . (int) $r['id'])) ?>">
            <div class="svc-visit-icon"><i class="bi <?= e($jobIcon($st['tone'])) ?>"></i></div>
            <div class="min-w-0 flex-grow-1">
              <div class="svc-visit-name"><?= e((string) ($r['subject'] ?: $r['number'])) ?></div>
              <div class="svc-visit-sub">
                <span><i class="bi bi-hash"></i> <?= e((string) $r['number']) ?></span>
                <?php if (!empty($r['account_name'])): ?>
                  <span><i class="bi bi-buildings"></i> <?= e((string) $r['account_name']) ?></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 endif; ?>
                <?php if ($from !== ''): ?>
                  <span><i class="bi bi-box-arrow-in-right"></i> <?= e($from) ?></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($st['class']) ?>"><?= e($st['text']) ?></span>
            </div>
          </a>
        </div>
      <?php endforeach; endif; ?>
      <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
    </div>
    <?php if ($canEdit): ?>
    <div class="col-lg-5" id="job-create">
      <form class="svc-req ajax-form" action="<?= e(url('jobs')) ?>" 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">New job</div>
            <h2>Open a work order</h2>
            <p>This gets a job number. Assign a person and keep notes on what was done.</p>
          </div>
        </div>
        <div class="svc-req-body">
          <label class="form-label" for="job-account"><?= e(noun('account', 'Account')) ?> *</label>
          <select class="form-select mb-2" id="job-account" 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>
          <label class="form-label" for="job-subject">Subject *</label>
          <input class="form-control mb-2" id="job-subject" name="subject" maxlength="180" required placeholder="Toner, jam, install…">
          <label class="form-label" for="job-assignee">Assigned person</label>
          <select class="form-select mb-2" id="job-assignee" name="assignee_id">
            <option value="">Me</option>
            <?php foreach ($assignees as $sp): ?>
              <option value="<?= (int) $sp['id'] ?>"><?= e(trim($sp['first_name'] . ' ' . $sp['last_name'])) ?></option>
            <?php endforeach; ?>
          </select>
          <label class="form-label" for="job-body">What is wrong</label>
          <textarea class="form-control mb-2" id="job-body" name="body" rows="4" placeholder="What is wrong and what should happen next."></textarea>
          <div class="svc-req-foot">
            <div class="svc-wait-chips">
              <span class="lst-chip">Job ticket</span>
              <span class="lst-chip">Not a visit</span>
            </div>
            <button class="btn btn-primary" type="submit"><i class="bi bi-check2"></i> Open job</button>
          </div>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>
