<?php
$label = $title ?? opportunity_label();
$counts = $counts ?? ['open' => 0, 'open_value' => 0, 'won' => 0, 'won_value' => 0, 'due' => 0, 'today' => 0];
$q = $q ?? '';
$viewMode = $viewMode ?? 'kanban';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$owners = $owners ?? [];
$stages = $stages ?? [];
$stageId = (int) ($stageId ?? 0);
$accountId = (int) ($accountId ?? 0);
$accounts = $accounts ?? [];
$outcome = $outcome ?? 'all';
$created = $created ?? 'all';
$close = $close ?? 'all';
$nextStep = $nextStep ?? 'all';
$probability = $probability ?? 'all';
$viewUrl = static function (string $mode) use ($q, $assigned, $accountId, $stageId, $outcome, $created, $close, $nextStep, $probability): string {
    $qs = ['view' => $mode];
    if ($q !== '') {
        $qs['q'] = $q;
    }
    if ($assigned > 0) {
        $qs['assigned'] = $assigned;
    }
    if ($accountId > 0) {
        $qs['account'] = $accountId;
    }
    if ($stageId > 0) {
        $qs['stage'] = $stageId;
    }
    if ($outcome !== 'all') {
        $qs['outcome'] = $outcome;
    }
    if ($created !== 'all') {
        $qs['created'] = $created;
    }
    if ($close !== 'all') {
        $qs['close'] = $close;
    }
    if ($nextStep !== 'all') {
        $qs['next'] = $nextStep;
    }
    if ($probability !== 'all') {
        $qs['probability'] = $probability;
    }
    return url('opportunities') . '?' . http_build_query($qs);
};
$summaries = [
    ['Open ' . strtolower($label), (string) (int) $counts['open'], 'bi-kanban', '#2563eb', '#eff6ff'],
    ['Pipeline', money_compact($counts['open_value']), 'bi-currency-dollar', '#7c3aed', '#f3e8ff'],
    ['Won this month', money_compact($counts['won_value']), 'bi-trophy-fill', '#16a34a', '#f0fdf4'],
    ['Next step due', (string) ((int) $counts['due'] + (int) $counts['today']), 'bi-flag-fill', '#ef4444', '#fef2f2'],
];
$colTones = ['#2563eb', '#7c3aed', '#0d9488', '#ea580c', '#16a34a', '#db2777', '#0891b2'];
?>
<div class="opp-page">
  <div class="mb-3">
    <h1 class="page-title"><?= e($label) ?></h1>
    <p class="page-sub mb-0"><?= e($industry['name'] ?? '') ?> · drag a card to change stage, or open it for the full record</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"><?= e($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">
    <input type="hidden" name="view" value="<?= e($viewMode) ?>">
    <div class="task-filter-search">
      <label class="form-label" for="opp-q">Search</label>
      <input class="form-control" id="opp-q" name="q" value="<?= e($q) ?>" placeholder="Search deal or account" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="opp-assigned">Assigned to</label>
      <select class="form-select" id="opp-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="opp-account"><?= e(noun('account', 'Account')) ?></label>
      <select class="form-select" id="opp-account" name="account">
        <option value="0" <?= $accountId === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($accounts as $acc): ?>
          <option value="<?= (int) $acc['id'] ?>" <?= $accountId === (int) $acc['id'] ? 'selected' : '' ?>><?= e($acc['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label" for="opp-created">Created</label>
      <select class="form-select" id="opp-created" name="created">
        <option value="all" <?= $created === 'all' ? 'selected' : '' ?>>All</option>
        <option value="today" <?= $created === 'today' ? 'selected' : '' ?>>Today</option>
        <option value="week" <?= $created === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="month" <?= $created === 'month' ? 'selected' : '' ?>>This month</option>
        <option value="last_week" <?= $created === 'last_week' ? 'selected' : '' ?>>Last week</option>
        <option value="last_month" <?= $created === 'last_month' ? 'selected' : '' ?>>Last month</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="opp-stage">Pipeline status</label>
      <select class="form-select" id="opp-stage" name="stage">
        <option value="0" <?= $stageId === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($stages as $st): ?>
          <option value="<?= (int) $st['id'] ?>" <?= $stageId === (int) $st['id'] ? 'selected' : '' ?>><?= e($st['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label" for="opp-outcome">Outcome</label>
      <select class="form-select" id="opp-outcome" name="outcome">
        <option value="all" <?= $outcome === 'all' ? 'selected' : '' ?>>All</option>
        <option value="open" <?= $outcome === 'open' ? 'selected' : '' ?>>Open</option>
        <option value="won" <?= $outcome === 'won' ? 'selected' : '' ?>>Won</option>
        <option value="lost" <?= $outcome === 'lost' ? 'selected' : '' ?>>Lost</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="opp-close">Expected close</label>
      <select class="form-select" id="opp-close" name="close">
        <option value="all" <?= $close === 'all' ? 'selected' : '' ?>>All</option>
        <option value="week" <?= $close === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="month" <?= $close === 'month' ? 'selected' : '' ?>>This month</option>
        <option value="overdue" <?= $close === 'overdue' ? 'selected' : '' ?>>Overdue</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="opp-next">Next step</label>
      <select class="form-select" id="opp-next" name="next">
        <option value="all" <?= $nextStep === 'all' ? 'selected' : '' ?>>All</option>
        <option value="overdue" <?= $nextStep === 'overdue' ? 'selected' : '' ?>>Overdue</option>
        <option value="today" <?= $nextStep === 'today' ? 'selected' : '' ?>>Today</option>
        <option value="week" <?= $nextStep === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="none" <?= $nextStep === 'none' ? 'selected' : '' ?>>No next step</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="opp-probability">Probability</label>
      <select class="form-select" id="opp-probability" name="probability">
        <option value="all" <?= $probability === 'all' ? 'selected' : '' ?>>All</option>
        <option value="high" <?= $probability === 'high' ? 'selected' : '' ?>>High</option>
        <option value="medium" <?= $probability === 'medium' ? 'selected' : '' ?>>Medium</option>
        <option value="low" <?= $probability === 'low' ? 'selected' : '' ?>>Low</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="opp-toolbar mb-3">
    <div class="opp-toggle" role="tablist" aria-label="View">
      <a class="<?= $viewMode === 'kanban' ? 'active' : '' ?>" href="<?= e($viewUrl('kanban')) ?>"><i class="bi bi-kanban"></i> Board</a>
      <a class="<?= $viewMode === 'list' ? 'active' : '' ?>" href="<?= e($viewUrl('list')) ?>"><i class="bi bi-list-ul"></i> List</a>
    </div>
  </div>

  <?php if ($viewMode === 'list'): ?>
    <?php if (empty($rows)): ?>
      <div class="card-soft task-empty">
        <div class="task-empty-icon"><i class="bi bi-currency-dollar"></i></div>
        <h2>No deals here</h2>
        <p>Use <strong>Add New → <?= e(noun('opportunity', 'Deal')) ?></strong> to add one.</p>
      </div>
    <?php else: ?>
      <?php foreach ($rows as $r):
        $won = (int) ($r['is_won'] ?? 0) === 1;
        $lost = (int) ($r['is_lost'] ?? 0) === 1;
        $due = due_label($r['next_step_at'] ?? null, $won ? 'completed' : ($lost ? 'cancelled' : 'open'));
        $tone = $lost ? 'lost' : ($won ? 'won' : match ($due['class'] ?? '') {
            'due-overdue' => 'due',
            'due-today' => 'today',
            default => 'open',
        });
        $owner = trim((string) ($r['owner_name'] ?? ''));
      ?>
        <a class="opp-card opp-tone-<?= e($tone) ?>" href="<?= e(url('opportunities/' . $r['id'])) ?>">
          <div class="opp-avatar"><?= e(name_initials($r['name'] ?? '')) ?></div>
          <div class="flex-grow-1 min-w-0">
            <div class="lead-name"><?= e($r['name']) ?></div>
            <div class="lead-sub">
              <span><?= e($r['account_name']) ?></span>
              <?php if (!empty($r['next_step'])): ?><span><?= e($r['next_step']) ?></span><?php endif; ?>
            </div>
          </div>
          <div class="task-meta">
            <span class="opp-amt"><?= money_fmt($r['amount']) ?></span>
            <?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="lead-status opp-stage-<?= e($tone) ?>"><?= e($r['stage_name']) ?></span>
            <?php if (!empty($due['text'])): ?>
              <span class="due-pill <?= e($due['class']) ?>"><?= e($due['text']) ?></span>
            <?php endif; ?>
          </div>
        </a>
      <?php endforeach; ?>
    <?php endif; ?>
    <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
  <?php else:
    $by = [];
    $colValue = [];
    foreach ($cards as $c) {
        $sid = (int) $c['stage_id'];
        $by[$sid][] = $c;
        $colValue[$sid] = ($colValue[$sid] ?? 0) + (float) $c['amount'];
    }
    $boardStages = [];
    foreach ($stages as $s) {
        if ((int) $s['is_lost'] !== 1) {
            $boardStages[] = $s;
        }
    }
    foreach ($stages as $s) {
        if ((int) $s['is_lost'] === 1) {
            $boardStages[] = $s;
        }
    }
    $stageN = count($boardStages);
  ?>
    <div class="kanban-wrap">
      <div class="kanban-nav">
        <div class="kanban-nav-copy">
          <strong><?= (int) $stageN ?> pipeline <?= $stageN === 1 ? 'status' : 'statuses' ?></strong>
          <span class="kanban-nav-hint is-overflow-only">Only a few fit on screen. Use the arrows, the names below, or scroll sideways to see the rest.</span>
          <span class="kanban-nav-hint is-fit-only">All statuses are on this screen.</span>
        </div>
        <div class="kanban-nav-btns">
          <button class="kanban-nav-btn" type="button" data-kanban-dir="-1" aria-label="Show earlier statuses">
            <i class="bi bi-chevron-left"></i>
          </button>
          <button class="kanban-nav-btn" type="button" data-kanban-dir="1" aria-label="Show later statuses">
            <i class="bi bi-chevron-right"></i>
          </button>
        </div>
      </div>
      <div class="kanban-rail" role="tablist" aria-label="Pipeline statuses">
        <?php foreach ($boardStages as $s):
            $sid = (int) $s['id'];
            $n = count($by[$sid] ?? []);
        ?>
          <button class="kanban-rail-chip <?= !empty($s['is_won']) ? 'is-won' : '' ?> <?= !empty($s['is_lost']) ? 'is-lost' : '' ?>" type="button" data-kanban-jump="<?= $sid ?>">
            <span class="kanban-rail-name"><?= e($s['name']) ?></span>
            <span class="kanban-rail-n"><?= $n ?></span>
          </button>
        <?php endforeach; ?>
      </div>
      <div class="kanban-viewport">
        <button class="kanban-edge is-left" type="button" data-kanban-dir="-1" aria-label="Scroll left"><i class="bi bi-chevron-left"></i></button>
        <button class="kanban-edge is-right" type="button" data-kanban-dir="1" aria-label="Scroll right"><i class="bi bi-chevron-right"></i></button>
        <div class="kanban" tabindex="0" aria-label="Deal board">
      <?php $i = 0; foreach ($stages as $s): if ((int) $s['is_lost'] === 1) continue;
        $sid = (int) $s['id'];
        $tone = !empty($s['is_won']) ? '#16a34a' : $colTones[$i % count($colTones)];
        $i++;
        $n = count($by[$sid] ?? []);
      ?>
        <div class="kanban-col <?= !empty($s['is_won']) ? 'is-won' : '' ?>" id="kanban-stage-<?= $sid ?>" data-stage="<?= $sid ?>" data-lost="0" style="--col-tone: <?= e($tone) ?>">
          <div class="kanban-head">
            <div>
              <div class="kanban-title"><?= e($s['name']) ?></div>
              <div class="kanban-sub"><?= $n ?> · <?= money_compact($colValue[$sid] ?? 0) ?></div>
            </div>
            <span class="kanban-count"><?= $n ?></span>
          </div>
          <?php foreach ($by[$sid] ?? [] as $c):
            $owner = trim((string) ($c['owner_name'] ?? ''));
            $due = due_label($c['next_step_at'] ?? null, 'open');
          ?>
            <div class="kanban-card" draggable="true" data-id="<?= (int) $c['id'] ?>" data-href="<?= e(url('opportunities/' . $c['id'])) ?>">
              <a class="kanban-name" href="<?= e(url('opportunities/' . $c['id'])) ?>" draggable="false"><?= e($c['name']) ?></a>
              <div class="small text-muted text-truncate"><?= e($c['account_name']) ?></div>
              <div class="kanban-amt"><?= money_fmt($c['amount']) ?></div>
              <?php if (!empty($c['next_step']) || !empty($due['text'])): ?>
                <div class="kanban-next">
                  <?php if (!empty($c['next_step'])): ?><span class="text-truncate"><?= e($c['next_step']) ?></span><?php endif; ?>
                  <?php if (!empty($due['text'])): ?><span class="due-pill <?= e($due['class']) ?>"><?= e($due['text']) ?></span><?php endif; ?>
                </div>
              <?php endif; ?>
              <?php if ($owner !== ''): ?>
                <div class="task-owner-chip mt-2">
                  <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
                  <span class="task-owner text-truncate"><?= e($owner) ?></span>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endforeach; ?>
      <?php foreach ($stages as $s): if ((int) $s['is_lost'] !== 1) continue;
        $sid = (int) $s['id'];
        $n = count($by[$sid] ?? []);
      ?>
        <div class="kanban-col is-lost" id="kanban-stage-<?= $sid ?>" data-stage="<?= $sid ?>" data-lost="1">
          <div class="kanban-head">
            <div>
              <div class="kanban-title"><?= e($s['name']) ?></div>
              <div class="kanban-sub"><?= $n > 0 ? $n . ' · ' . money_compact($colValue[$sid] ?? 0) : 'Drop here and enter why' ?></div>
            </div>
            <?php if ($n > 0): ?><span class="kanban-count"><?= $n ?></span><?php endif; ?>
          </div>
          <?php foreach ($by[$sid] ?? [] as $c):
            $owner = trim((string) ($c['owner_name'] ?? ''));
            $due = due_label($c['next_step_at'] ?? null, 'cancelled');
          ?>
            <div class="kanban-card" draggable="true" data-id="<?= (int) $c['id'] ?>" data-href="<?= e(url('opportunities/' . $c['id'])) ?>">
              <a class="kanban-name" href="<?= e(url('opportunities/' . $c['id'])) ?>" draggable="false"><?= e($c['name']) ?></a>
              <div class="small text-muted text-truncate"><?= e($c['account_name']) ?></div>
              <div class="kanban-amt"><?= money_fmt($c['amount']) ?></div>
              <?php if ($owner !== ''): ?>
                <div class="task-owner-chip mt-2">
                  <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
                  <span class="task-owner text-truncate"><?= e($owner) ?></span>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endforeach; ?>
        </div>
      </div>
    </div>
  <?php endif; ?>
</div>
