<?php
$counts = $counts ?? ['open' => 0, 'completed' => 0, 'cancelled' => 0, 'overdue' => 0, 'today' => 0, 'all' => 0];
$related = $related ?? 'all';
$when = $when ?? 'all';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$owners = $owners ?? [];
$q = $q ?? '';
$status = $status ?? 'open';
$summaries = [
    ['Past due', (int) $counts['overdue'], 'bi-exclamation-circle-fill', '#ef4444', '#fef2f2'],
    ['Due today', (int) $counts['today'], 'bi-calendar-event-fill', '#16a34a', '#f0fdf4'],
    ['Open', (int) $counts['open'], 'bi-check2-square', '#2563eb', '#eff6ff'],
    ['Done', (int) $counts['completed'], 'bi-check-circle-fill', '#0f766e', '#f0fdfa'],
];
$toneFor = static function (array $due, string $st): string {
    if ($st === 'completed') {
        return 'done';
    }
    if ($st === 'cancelled') {
        return 'cancelled';
    }
    return match ($due['class'] ?? '') {
        'due-overdue' => 'overdue',
        'due-today' => 'today',
        default => 'later',
    };
};
$iconFor = static function (string $tone): string {
    return match ($tone) {
        'overdue' => 'bi-exclamation-circle',
        'today' => 'bi-sun',
        'done' => 'bi-check-lg',
        'cancelled' => 'bi-x-lg',
        default => 'bi-clock',
    };
};
?>
<div class="task-page">
  <div class="mb-3">
    <h1 class="page-title">Tasks</h1>
    <p class="page-sub mb-0"><?= (int) $total ?> in this view · change status on any row</p>
  </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 card-soft p-3 mb-3<?= $showAssigned ? ' has-assigned' : '' ?>" method="get">
    <div class="task-filter-search">
      <label class="form-label" for="task-q">Search</label>
      <input class="form-control" id="task-q" name="q" value="<?= e($q) ?>" placeholder="Search tasks" autocomplete="off">
    </div>
    <div>
      <label class="form-label" for="task-when">View</label>
      <select class="form-select" id="task-when" name="when">
        <option value="all" <?= $when === 'all' ? 'selected' : '' ?>>All</option>
        <option value="today" <?= $when === 'today' ? 'selected' : '' ?>>Today’s Tasks</option>
        <option value="upcoming" <?= $when === 'upcoming' ? 'selected' : '' ?>>Upcoming Tasks</option>
        <option value="overdue" <?= $when === 'overdue' ? 'selected' : '' ?>>Overdue</option>
        <option value="this_week" <?= $when === 'this_week' ? 'selected' : '' ?>>This week</option>
        <option value="this_month" <?= $when === 'this_month' ? 'selected' : '' ?>>This month</option>
        <option value="last_week" <?= $when === 'last_week' ? 'selected' : '' ?>>Last week</option>
        <option value="last_month" <?= $when === 'last_month' ? 'selected' : '' ?>>Last month</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="task-related">Related to</label>
      <select class="form-select" id="task-related" name="related">
        <option value="all" <?= $related === 'all' ? 'selected' : '' ?>>All</option>
        <option value="leads" <?= $related === 'leads' ? 'selected' : '' ?>><?= e(noun('leads', 'Leads')) ?></option>
        <option value="opportunities" <?= $related === 'opportunities' ? 'selected' : '' ?>>Opportunities</option>
        <option value="others" <?= $related === 'others' ? 'selected' : '' ?>>Others</option>
      </select>
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="task-assigned">Assigned to</label>
      <select class="form-select" id="task-assigned" name="assigned">
        <option value="0" <?= $assigned === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($owners 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="task-status">Status</label>
      <select class="form-select" id="task-status" name="status">
        <option value="open" <?= $status === 'open' ? 'selected' : '' ?>>Open</option>
        <option value="completed" <?= $status === 'completed' ? 'selected' : '' ?>>Done</option>
        <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : '' ?>>Cancelled</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 if (!$rows): ?>
    <div class="card-soft task-empty">
      <div class="task-empty-icon"><i class="bi bi-check2-square"></i></div>
      <h2>No tasks here</h2>
      <p>Try another filter, or use <strong>Add New → Task</strong> and pick Related to.</p>
    </div>
  <?php else: ?>
    <?php foreach ($rows as $t):
      $st = $t['status'] ?? 'open';
      $due = due_label($t['due_at'], $st);
      $tone = $toneFor($due, $st);
      $owner = trim((string) ($t['owner_name'] ?? ''));
      $relatedName = trim((string) ($t['related_name'] ?? ''));
      $relUrl = related_url($t['related_type'] ?? null, (int) ($t['related_id'] ?? 0));
      $relKind = match ((string) ($t['related_type'] ?? '')) {
          'lead' => noun('lead', 'Lead'),
          'opportunity' => opportunity_label(),
          'account' => noun('account', 'Account'),
          'contact' => noun('contact', 'Contact'),
          default => '',
      };
      $prio = (string) ($t['priority'] ?? 'normal');
    ?>
      <div class="task-row task-card task-tone-<?= e($tone) ?> <?= $st === 'completed' ? 'is-done' : '' ?>">
        <div class="task-card-icon"><i class="bi <?= e($iconFor($tone)) ?>"></i></div>
        <div class="flex-grow-1 min-w-0">
          <div class="task-card-title"><?= e($t['title']) ?></div>
          <div class="task-card-sub">
            <?php if ($relatedName !== '' && $relUrl !== '#'): ?>
              <a href="<?= e($relUrl) ?>"><?php if ($relKind !== ''): ?><?= e($relKind) ?> · <?php endif; ?><?= e($relatedName) ?></a>
            <?php elseif ($relatedName !== ''): ?>
              <span><?php if ($relKind !== ''): ?><?= e($relKind) ?> · <?php endif; ?><?= e($relatedName) ?></span>
            <?php elseif ($relKind === ''): ?>
              <span>Not linked</span>
            <?php endif; ?>
            <?php if ($prio === 'high'): ?><span class="task-prio high">High</span><?php endif; ?>
            <?php if ($prio === 'low'): ?><span class="task-prio low">Low</span><?php endif; ?>
            <?= task_file_chip($t['file_name'] ?? null, (int) $t['id']) ?>
          </div>
        </div>
        <div class="task-meta">
          <?php if ($owner !== ''): ?>
            <span class="task-owner-chip" title="<?= e($owner) ?>">
              <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
              <span class="task-owner text-truncate"><?= e($owner) ?></span>
            </span>
          <?php endif; ?>
          <span class="due-pill js-task-due <?= e($due['class']) ?>"><?= e($due['text'] ?: dt_fmt($t['due_at'])) ?></span>
          <select class="form-select form-select-sm js-task-status" data-id="<?= (int) $t['id'] ?>" data-prev="<?= e($st) ?>" aria-label="Task status">
            <option value="open" <?= $st === 'open' ? 'selected' : '' ?>>Open</option>
            <option value="completed" <?= $st === 'completed' ? 'selected' : '' ?>>Done</option>
            <option value="cancelled" <?= $st === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
          </select>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
</div>
