<?php
/* ============================================================================
   WBMCZ ADMIN — ACTIVITY & TASK
   ----------------------------------------------------------------------------
   Six tabs, and only two kinds of screen underneath them.

     User    a line: Lead -> KYC -> Refer / Order, plus KYC requests and Support
     Seller  a line: KYC -> Subscription -> Refer / Order, plus Seller requests,
             KYC requests, Product requests and Support
     Employee / Admin / Super Admin   what each of them is carrying
     Office  Wallet, Payout, Website requests, and the settings pages

   A STEP is a line a member walks; it opens and closes itself from facts about
   them, so nobody ticks "done". A DESK is a queue somebody decides on, read
   straight from the real table, so a verdict here is the same verdict as on
   that table's own admin page.

   What a step or desk is allowed to show is decided per person — see
   includes/pipeline.php.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/rbac.php';
require_once __DIR__ . '/../includes/activity.php';
@require_once __DIR__ . '/../includes/acl.php';
require_once __DIR__ . '/../includes/tasks.php';
require_once __DIR__ . '/../includes/pipeline.php';

if (!isLoggedIn() || !isAdmin()) { redirect('../login.php'); }

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

pipe_ensure_schema($db);

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user      = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('../login.php'); }

$company_name = getSetting('company_name', getSetting('site_name', 'WBMCZ'));

$ME      = tasks_actor($db);
$IS_BOSS = pipe_is_boss($db);
$ROLES   = pipe_roles();
$ALLTABS = pipe_all_tabs();
$OUT     = pipe_outcomes();
$DEC     = pipe_decisions();
$STAFF   = tasks_staff_list($db);
$MINE    = pipe_access($db);

$flash_ok  = isset($_SESSION['flash_success']) ? $_SESSION['flash_success'] : ''; unset($_SESSION['flash_success']);
$flash_err = isset($_SESSION['flash_error'])   ? $_SESSION['flash_error']   : ''; unset($_SESSION['flash_error']);

/* ============================================================================
   WHAT STAFF DO HERE
   ============================================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $back = 'activity_task.php?' . $_SERVER['QUERY_STRING'];

    if (isset($_POST['save_outcome'])) {
        $r = pipe_apply_outcome($db, (int)$_POST['task_id'], (string)$_POST['outcome'],
                                (string)($_POST['remark'] ?? ''), (string)($_POST['follow_date'] ?? ''));
        if (!empty($r['ok'])) {
            $m = pipe_outcome_meta($r['outcome']);
            $_SESSION['flash_success'] = 'Saved — marked as ' . $m[0] . '.';
            activity_log($db, 'update', 'Activity & Task', 'Outcome: ' . $m[0]);
        } else { $_SESSION['flash_error'] = $r['error']; }
        redirect($back);
    }

    if (isset($_POST['save_assign'])) {
        $staff = (int)($_POST['staff_id'] ?? 0);
        $ids   = array_filter(array_map('intval', explode(',', (string)($_POST['task_ids'] ?? ''))));
        $ok = 0; $err = '';
        foreach ($ids as $tid) {
            $r = pipe_assign($db, $tid, $staff, (string)($_POST['assign_note'] ?? ''));
            if (!empty($r['ok'])) { $ok++; } else { $err = $r['error']; }
        }
        if ($ok > 0 && $IS_BOSS && $staff > 0 && isset($_POST['set_access'])) {
            pipe_set_access($db, $staff, (array)($_POST['access'] ?? []));
        }
        $_SESSION[$ok > 0 ? 'flash_success' : 'flash_error'] = $ok > 0
            ? ($ok . ' handed over.' . (isset($_POST['set_access']) ? ' Their access was saved too.' : ''))
            : ($err !== '' ? $err : 'Nothing was handed over.');
        if ($ok > 0) activity_log($db, 'assign', 'Activity & Task', $ok . ' task(s) handed over');
        redirect($back);
    }

    /* every desk decides through the same door */
    if (isset($_POST['desk_decide'])) {
        $deskKey = (string)($_POST['desk'] ?? '');
        $desks   = pipe_desks();
        if (!isset($desks[$deskKey]) || !pipe_can_stage($db, $deskKey)) {
            $_SESSION['flash_error'] = 'That desk is not open to you.';
        } else {
            $d = $desks[$deskKey];
            $r = call_user_func($d['decide'], $db, (int)$_POST['ref_id'],
                                (string)$_POST['decision'], trim((string)($_POST['remark'] ?? '')));
            if (!empty($r['ok'])) {
                $_SESSION['flash_success'] = $d['label'] . ' — ' . $DEC[(string)$_POST['decision']][0] . 'ed.';
                activity_log($db, 'update', 'Activity & Task', $d['label'] . ': ' . $_POST['decision']);
            } else { $_SESSION['flash_error'] = $r['error']; }
        }
        redirect($back);
    }

    if (isset($_POST['save_team_access']) && $IS_BOSS) {
        $n = 0;
        foreach ((array)($_POST['team'] ?? []) as $sid => $keys) {
            if (pipe_set_access($db, (int)$sid, (array)$keys)) $n++;
        }
        $_SESSION['flash_success'] = 'Access saved for ' . $n . ' people.';
        activity_log($db, 'update', 'Activity & Task', 'Task access updated for ' . $n . ' staff');
        redirect($back);
    }
}

/* ============================================================================
   KEEP THE LINE HONEST
   ============================================================================ */
$sync = pipe_sync($db, isset($_GET['sync']));
if (isset($_GET['sync'])) {
    $_SESSION['flash_success'] = 'Line refreshed — ' . $sync['created'] . ' opened, ' . $sync['completed'] . ' completed on their own.';
    redirect('activity_task.php?role=' . urlencode((string)($_GET['role'] ?? 'user')) . '&tab=' . urlencode((string)($_GET['tab'] ?? '')));
}

/* ============================================================================
   WHAT WE ARE LOOKING AT
   ============================================================================ */
$ROLE = isset($_GET['role']) ? (string)$_GET['role'] : 'user';
if (!isset($ROLES[$ROLE])) $ROLE = 'user';
$KIND = $ROLES[$ROLE]['kind'];

$roleTabs = pipe_role_tabs($ROLE);
$VIS = [];
foreach ($roleTabs as $k => $v) { if ($IS_BOSS || in_array($k, $MINE, true)) $VIS[$k] = $v; }

$TAB = isset($_GET['tab']) ? (string)$_GET['tab'] : '';
if (!isset($VIS[$TAB])) { $TAB = !empty($VIS) ? array_key_first($VIS) : ''; }
$T   = $TAB !== '' ? $VIS[$TAB] : null;
$IS_DESK = $T && $T['type'] === 'desk';

$show = isset($_GET['show']) ? (string)$_GET['show'] : 'open';
if (!in_array($show, ['open', 'due', 'unassigned', 'dropped', 'done', 'all'], true)) $show = 'open';
$q    = trim((string)(isset($_GET['q']) ? $_GET['q'] : ''));
$who  = isset($_GET['who']) ? (string)$_GET['who'] : '';
$page = max(1, (int)(isset($_GET['p']) ? $_GET['p'] : 1));
$per  = 25;

function pq($over = []) {
    $keep = ['role', 'tab', 'show', 'q', 'who', 'p'];
    $base = [];
    foreach ($keep as $k) { $base[$k] = isset($_GET[$k]) ? $_GET[$k] : ''; }
    $m = array_filter(array_merge($base, $over), function ($v) { return $v !== '' && $v !== null; });
    return 'activity_task.php?' . http_build_query($m);
}

list($scopeSql, $scopeParams) = tasks_scope_sql($db, 't');

/* counts on the chips */
$tabCounts = [];
foreach ($VIS as $k => $v) {
    if ($v['type'] === 'desk') {
        $tabCounts[$k] = empty($v['decisions']) ? 0 : (int)call_user_func($v['count'], $db, '');
    } else {
        $st = pipe_stage_stats($db, $ROLE, $k, $scopeSql, $scopeParams);
        $tabCounts[$k] = $st['open'];
    }
}

$stat = ['open' => 0, 'due' => 0, 'done' => 0, 'dropped' => 0, 'unassigned' => 0];
$rows = []; $total = 0; $team = [];

if ($KIND === 'team') {
    $team = pipe_team_rows($db, $ROLE);

} elseif ($TAB !== '' && $IS_DESK && !empty($T['decisions'])) {
    $total = (int)call_user_func($T['count'], $db, $q);
    $rows  = call_user_func($T['rows'], $db, $q, $per, ($page - 1) * $per);

} elseif ($TAB !== '' && !$IS_DESK) {
    $stat = pipe_stage_stats($db, $ROLE, $TAB, $scopeSql, $scopeParams);

    $w = ["t.scope_role = ?", "t.module_key = ?", "($scopeSql)"];
    $p = array_merge([$ROLE, $TAB], $scopeParams);

    switch ($show) {
        case 'due':
            $w[] = "t.status NOT IN ('completed','rejected','cancelled')";
            $w[] = "t.next_follow_up IS NOT NULL AND t.next_follow_up <= CURDATE()"; break;
        case 'unassigned':
            $w[] = "t.status NOT IN ('completed','rejected','cancelled')";
            $w[] = "(t.assigned_to IS NULL OR t.assigned_to = 0)"; break;
        case 'dropped': $w[] = "t.outcome = 'not_interested'"; break;
        case 'done':    $w[] = "t.status = 'completed'"; break;
        case 'all':     break;
        default:        $w[] = "t.status NOT IN ('completed','rejected','cancelled')";
    }
    if ($q !== '') {
        $w[] = "(t.target_name LIKE ? OR t.target_mobile LIKE ? OR t.task_code LIKE ?)";
        $like = '%' . $q . '%'; array_push($p, $like, $like, $like);
    }
    if ($who === 'me')       { $w[] = "t.assigned_to = ?"; $p[] = (int)$ME['id']; }
    elseif ($who === 'none') { $w[] = "(t.assigned_to IS NULL OR t.assigned_to = 0)"; }
    elseif ($who !== '')     { $w[] = "t.assigned_to = ?"; $p[] = (int)$who; }

    $where = implode(' AND ', $w);
    $c = pipe_qa($db, "SELECT COUNT(*) c FROM tasks t WHERE $where", $p);
    $total = (int)(isset($c[0]['c']) ? $c[0]['c'] : 0);

    /* Overdue call-backs first, then people nobody holds, then the soonest
       call-back, then newest. Nothing has to be sorted by hand. */
    $rows = pipe_qa($db,
        "SELECT t.*, u.mobile AS live_mobile FROM tasks t
           LEFT JOIN users u ON u.id = t.target_user_id
          WHERE $where
          ORDER BY (t.next_follow_up IS NOT NULL AND t.next_follow_up <= CURDATE()
                    AND t.status NOT IN ('completed','rejected','cancelled')) DESC,
                   (t.assigned_to IS NULL OR t.assigned_to = 0) DESC,
                   t.next_follow_up IS NULL, t.next_follow_up ASC, t.id DESC
          LIMIT $per OFFSET " . (($page - 1) * $per), $p);
}

$pages = max(1, (int)ceil($total / $per));
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Activity &amp; Task - <?php echo esc($company_name); ?> Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
  body { font-family:'Inter',sans-serif; }
  [x-cloak] { display:none !important; }
  .lbl { display:block; font-size:11px; font-weight:800; color:#64748b; margin-bottom:5px;
         text-transform:uppercase; letter-spacing:.04em; }
  .fld { width:100%; border:1.5px solid #e2e8f0; border-radius:11px; padding:9px 12px; font-size:13.5px; background:#fff; }
  .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }
  .pill { display:inline-flex; align-items:center; gap:5px; padding:3px 10px; border-radius:999px;
          font-size:11px; font-weight:800; white-space:nowrap; }
  .oc { display:flex; align-items:flex-start; gap:10px; width:100%; text-align:left; padding:11px 13px;
        border:1.5px solid #e2e8f0; border-radius:13px; background:#fff; cursor:pointer; transition:.15s; }
  .oc:hover { border-color:#cbd5e1; }
  .oc.on { border-color:#4f46e5; background:#eef2ff; box-shadow:0 0 0 3px rgba(79,70,229,.1); }
  .stat { background:#fff; border:1px solid #e8edf5; border-radius:16px; padding:14px 16px; display:block; transition:.15s; }
  .stat:hover { border-color:#c7d2fe; }
  .stat.on { border-color:#4f46e5; box-shadow:0 0 0 3px rgba(79,70,229,.1); }
  .rolebtn { display:flex; align-items:center; justify-content:center; gap:8px; padding:13px 10px; border-radius:16px;
             font-size:13px; font-weight:800; border:1.5px solid #e8edf5; background:#fff; color:#475569; transition:.15s; }
  .rolebtn:hover { border-color:#c7d2fe; color:#4338ca; }
  .rolebtn.on { background:linear-gradient(135deg,#4f46e5,#7c3aed); border-color:transparent; color:#fff;
                box-shadow:0 10px 24px -14px rgba(79,70,229,.9); }
  .chipbtn { display:inline-flex; align-items:center; gap:7px; padding:9px 15px; border-radius:13px;
             font-size:12.5px; font-weight:800; border:1.5px solid #e8edf5; background:#fff; color:#475569;
             white-space:nowrap; transition:.15s; }
  .chipbtn:hover { border-color:#c7d2fe; color:#4338ca; }
  .chipbtn.on { background:#0b1220; border-color:#0b1220; color:#fff; }
  .hide-sb::-webkit-scrollbar { display:none; }
  .hide-sb { -ms-overflow-style:none; scrollbar-width:none; }
</style>
</head>
<body class="bg-gray-50" x-data="board()" x-cloak>

<div class="flex h-screen overflow-hidden">

  <?php include __DIR__ . '/includes/sidebar.php'; ?>

  <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">

    <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
      <div class="flex items-center min-w-0">
        <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-indigo-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
        <div class="min-w-0">
          <h2 class="text-xl font-bold truncate">Activity &amp; Task</h2>
          <p class="text-[11px] text-slate-400 hidden sm:block">
            <?php echo $IS_BOSS
                ? 'People move themselves along — you decide who works on them'
                : 'The people you were given, and what to do about them next'; ?>
          </p>
        </div>
      </div>
      <div class="flex items-center gap-2">
        <a href="<?php echo esc(pq(['sync' => 1])); ?>"
           class="hidden sm:inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50">
          <i class="fas fa-rotate"></i> Refresh the line
        </a>
        <?php if ($IS_BOSS): ?>
        <button @click="team = true" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-white text-xs font-bold shadow hover:shadow-lg">
          <i class="fas fa-user-shield"></i> Team access
        </button>
        <?php endif; ?>
      </div>
    </header>

    <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

      <?php if ($flash_ok): ?>
        <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl text-sm font-medium">
          <i class="fas fa-circle-check mr-1.5"></i><?php echo esc($flash_ok); ?></div>
      <?php endif; ?>
      <?php if ($flash_err): ?>
        <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl text-sm font-medium">
          <i class="fas fa-circle-exclamation mr-1.5"></i><?php echo esc($flash_err); ?></div>
      <?php endif; ?>

      <!-- ===================== ROLE TABS ===================== -->
      <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mb-5">
        <?php foreach ($ROLES as $rk => $rv): ?>
          <a href="<?php echo esc(pq(['role' => $rk, 'tab' => '', 'show' => '', 'q' => '', 'who' => '', 'p' => ''])); ?>"
             class="rolebtn <?php echo $rk === $ROLE ? 'on' : ''; ?>">
            <i class="fas <?php echo $rv['icon']; ?>"></i> <?php echo esc($rv['label']); ?>
          </a>
        <?php endforeach; ?>
      </div>

      <?php if ($KIND === 'team'): ?>
      <!-- ===================== WHAT THE TEAM IS CARRYING ===================== -->
      <div class="bg-white border border-slate-200 rounded-2xl px-5 py-4 mb-5">
        <p class="text-sm font-extrabold text-slate-800">
          <i class="fas <?php echo $ROLES[$ROLE]['icon']; ?> text-indigo-500 mr-1.5"></i>
          <?php echo esc($ROLES[$ROLE]['label']); ?></p>
        <p class="text-[12.5px] text-slate-500 mt-0.5">
          What each of them is carrying right now, and which steps they can reach.
        </p>
      </div>

      <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden">
        <?php if (empty($team)): ?>
          <div class="p-12 text-center">
            <i class="fas fa-user-slash text-4xl text-slate-200 mb-3"></i>
            <p class="font-bold text-slate-700">Nobody of this kind yet</p>
            <p class="text-sm text-slate-500 mt-1">Add them under Staff &amp; Roles.</p>
          </div>
        <?php else: ?>
        <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-slate-50 text-[10.5px] uppercase tracking-wide text-slate-400 font-black">
            <tr>
              <th class="text-left px-5 py-3">Person</th>
              <th class="px-4 py-3">Open</th>
              <th class="px-4 py-3">Call back today</th>
              <th class="px-4 py-3">Completed</th>
              <th class="px-4 py-3">Dropped</th>
              <th class="text-left px-5 py-3">Can reach</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-100">
          <?php foreach ($team as $s): ?>
            <tr class="hover:bg-slate-50/60">
              <td class="px-5 py-3.5">
                <p class="font-bold text-slate-800"><?php echo esc($s['name']); ?></p>
                <p class="text-[11.5px] text-slate-400"><?php echo esc($s['role_label']); ?></p>
              </td>
              <td class="px-4 py-3.5 text-center font-black text-slate-800"><?php echo (int)$s['open']; ?></td>
              <td class="px-4 py-3.5 text-center font-black <?php echo $s['due'] > 0 ? 'text-blue-600' : 'text-slate-300'; ?>"><?php echo (int)$s['due']; ?></td>
              <td class="px-4 py-3.5 text-center font-black text-emerald-600"><?php echo (int)$s['done']; ?></td>
              <td class="px-4 py-3.5 text-center font-black text-rose-500"><?php echo (int)$s['dropped']; ?></td>
              <td class="px-5 py-3.5">
                <?php if (empty($s['role_id'])): ?>
                  <span class="pill bg-slate-900 text-white"><i class="fas fa-infinity"></i> everything</span>
                <?php elseif (empty($s['access'])): ?>
                  <span class="pill bg-amber-100 text-amber-700"><i class="fas fa-lock"></i> nothing yet</span>
                <?php else: foreach ($s['access'] as $ak): if (!isset($ALLTABS[$ak])) continue; ?>
                  <span class="pill bg-slate-100 text-slate-600 mr-1 mb-1"><?php echo esc($ALLTABS[$ak]['label']); ?></span>
                <?php endforeach; endif; ?>
                <a href="<?php echo esc(pq(['role' => 'user', 'tab' => '', 'who' => (int)$s['id'], 'show' => 'all'])); ?>"
                   class="block text-[11.5px] font-bold text-indigo-600 mt-1 hover:underline">See their work</a>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        </div>
        <?php endif; ?>
      </div>

      <?php elseif ($TAB === ''): ?>
        <div class="bg-white border border-slate-200 rounded-2xl p-10 text-center max-w-xl mx-auto">
          <i class="fas fa-user-lock text-4xl text-slate-300 mb-4"></i>
          <p class="font-bold text-slate-800">Nothing here has been opened up to you</p>
          <p class="text-sm text-slate-500 mt-1.5">
            An administrator decides which steps and desks you work on. Ask them to give you
            one and this tab fills up.
          </p>
        </div>

      <?php else: ?>

      <!-- ===================== CHIPS ===================== -->
      <div class="flex gap-2.5 overflow-x-auto hide-sb pb-1 mb-5">
        <?php foreach ($VIS as $k => $v): $on = ($k === $TAB); ?>
          <a href="<?php echo esc(pq(['tab' => $k, 'show' => '', 'p' => '', 'q' => '', 'who' => ''])); ?>"
             class="chipbtn <?php echo $on ? 'on' : ''; ?>">
            <i class="fas <?php echo $v['icon']; ?>"></i>
            <?php echo esc($v['label']); ?>
            <?php if (!empty($v['decisions']) || $v['type'] === 'stage'): ?>
              <span class="px-1.5 py-0.5 rounded-md text-[10px] <?php echo $on ? 'bg-white/20' : 'bg-slate-100 text-slate-500'; ?>"><?php echo (int)$tabCounts[$k]; ?></span>
            <?php endif; ?>
          </a>
        <?php endforeach; ?>
      </div>

      <div class="bg-white border border-slate-200 rounded-2xl px-5 py-4 mb-5">
        <p class="text-sm font-extrabold text-slate-800">
          <i class="fas <?php echo $T['icon']; ?> text-indigo-500 mr-1.5"></i><?php echo esc($T['label']); ?></p>
        <p class="text-[12.5px] text-slate-500 mt-0.5">
          <?php echo esc($T['blurb']); ?><?php if (!$IS_DESK): ?> · <span class="font-semibold text-slate-600">This step closes itself when: <?php echo esc($T['goal']); ?></span><?php endif; ?>
        </p>
        <?php if (!$IS_BOSS && !$IS_DESK): ?>
          <p class="text-[11.5px] text-amber-700 mt-1.5"><i class="fas fa-user-check mr-1"></i>Showing only the people you hold.</p>
        <?php endif; ?>
      </div>

      <?php if ($IS_DESK && empty($T['decisions'])): ?>
      <!-- ===================== GENERAL: pages, not a queue ===================== -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <?php foreach ($T['links'] as $L): ?>
          <a href="<?php echo esc($L[2]); ?>" class="bg-white border border-slate-200 rounded-2xl p-5 hover:border-indigo-300 transition-colors">
            <div class="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center mb-3">
              <i class="fas <?php echo $L[1]; ?>"></i></div>
            <p class="font-bold text-slate-800 text-[14px]"><?php echo $L[0]; ?></p>
            <p class="text-[12.5px] text-slate-500 mt-0.5"><?php echo esc($L[3]); ?></p>
          </a>
        <?php endforeach; ?>
      </div>

      <?php else: ?>

      <?php if (!$IS_DESK): ?>
      <!-- ===================== COUNTS ===================== -->
      <div class="grid grid-cols-2 lg:grid-cols-5 gap-3 mb-5">
        <?php foreach ([
            ['open',       'Open',            'fa-list-check',   'text-slate-800',   $stat['open']],
            ['due',        'Call back today', 'fa-phone-volume', 'text-blue-600',    $stat['due']],
            ['unassigned', 'Nobody holds',    'fa-user-slash',   'text-amber-600',   $stat['unassigned']],
            ['done',       'Completed',       'fa-circle-check', 'text-emerald-600', $stat['done']],
            ['dropped',    'Not interested',  'fa-circle-xmark', 'text-rose-600',    $stat['dropped']],
        ] as $tl): ?>
          <a href="<?php echo esc(pq(['show' => $tl[0], 'p' => ''])); ?>" class="stat <?php echo $show === $tl[0] ? 'on' : ''; ?>">
            <p class="text-[10.5px] font-black uppercase tracking-wide text-slate-400"><i class="fas <?php echo $tl[2]; ?> mr-1"></i><?php echo $tl[1]; ?></p>
            <p class="text-2xl font-black <?php echo $tl[3]; ?> mt-1"><?php echo (int)$tl[4]; ?></p>
          </a>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <!-- ===================== FILTERS ===================== -->
      <form method="GET" class="bg-white border border-slate-200 rounded-2xl p-4 mb-5 flex flex-wrap gap-3 items-end">
        <input type="hidden" name="role" value="<?php echo esc($ROLE); ?>">
        <input type="hidden" name="tab"  value="<?php echo esc($TAB); ?>">
        <input type="hidden" name="show" value="<?php echo esc($show); ?>">
        <div class="flex-1 min-w-[200px]">
          <label class="lbl">Search</label>
          <input name="q" value="<?php echo esc($q); ?>" class="fld"
                 placeholder="<?php echo esc($IS_DESK ? ($T['search'] ?? 'search') : 'Name, mobile or task code'); ?>">
        </div>
        <?php if (!$IS_DESK && $IS_BOSS): ?>
        <div class="min-w-[190px]">
          <label class="lbl">Held by</label>
          <select name="who" class="fld">
            <option value="">Anybody</option>
            <option value="me"   <?php echo $who === 'me' ? 'selected' : ''; ?>>Me</option>
            <option value="none" <?php echo $who === 'none' ? 'selected' : ''; ?>>Nobody yet</option>
            <?php foreach ($STAFF as $s): ?>
              <option value="<?php echo (int)$s['id']; ?>" <?php echo (string)$who === (string)$s['id'] ? 'selected' : ''; ?>><?php echo esc($s['name']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php endif; ?>
        <button class="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold"><i class="fas fa-filter mr-1"></i> Filter</button>
        <a href="<?php echo esc(pq(['q' => '', 'who' => '', 'p' => ''])); ?>" class="px-5 py-2.5 rounded-xl bg-slate-100 text-slate-600 text-xs font-bold"><i class="fas fa-rotate-left mr-1"></i> Reset</a>
      </form>

      <?php if ($IS_DESK): ?>
      <!-- ===================== A DESK ===================== -->
      <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden">
        <?php if (empty($rows)): ?>
          <div class="p-12 text-center">
            <i class="fas fa-mug-hot text-4xl text-slate-200 mb-3"></i>
            <p class="font-bold text-slate-700">Nothing is waiting</p>
            <p class="text-sm text-slate-500 mt-1">Everything on this desk has been dealt with.</p>
          </div>
        <?php else: ?>
        <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-slate-50 text-[10.5px] uppercase tracking-wide text-slate-400 font-black">
            <tr>
              <?php foreach ($T['cols'] as $c): ?><th class="text-left px-5 py-3"><?php echo $c; ?></th><?php endforeach; ?>
              <th class="text-right px-5 py-3">Decide</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-100">
          <?php foreach ($rows as $r):
              $cells = call_user_func($T['row'], $r);
              $rid   = (int)call_user_func($T['key'], $r);
              $ttl   = (string)call_user_func($T['title'], $r); ?>
            <tr class="hover:bg-slate-50/60 align-top">
              <?php foreach ($cells as $c): ?><td class="px-5 py-3.5"><?php echo $c; ?></td><?php endforeach; ?>
              <td class="px-5 py-3.5 text-right">
                <button @click='openDesk(<?php echo esc(json_encode(['id' => $rid, 'name' => $ttl])); ?>)'
                        class="px-4 py-2 rounded-xl bg-slate-900 text-white text-[11.5px] font-bold">
                  <i class="fas fa-gavel mr-1"></i> Decide</button>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        </div>
        <?php endif; ?>
      </div>

      <?php else: ?>
      <!-- ===================== A STEP ===================== -->
      <form method="POST" id="assignForm" x-ref="assignForm">
      <input type="hidden" name="save_assign" value="1">
      <input type="hidden" name="task_ids" :value="picked.join(',')">

      <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden">
        <div class="px-5 py-3.5 border-b border-slate-100 flex flex-wrap items-center justify-between gap-3">
          <p class="text-[12.5px] font-bold text-slate-600"><?php echo (int)$total; ?> on this step · <?php echo esc($show); ?></p>
          <template x-if="picked.length">
            <button type="button" @click="openAssign()" class="px-4 py-2 rounded-xl bg-indigo-600 text-white text-[11.5px] font-bold">
              <i class="fas fa-user-plus mr-1"></i> Hand <span x-text="picked.length"></span> over</button>
          </template>
        </div>

        <?php if (empty($rows)): ?>
          <div class="p-12 text-center">
            <i class="fas fa-check-double text-4xl text-slate-200 mb-3"></i>
            <p class="font-bold text-slate-700">Nothing here</p>
            <p class="text-sm text-slate-500 mt-1"><?php echo $show === 'open' ? 'Everybody on this step has been dealt with.' : 'Try another filter above.'; ?></p>
          </div>
        <?php else: ?>
        <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-slate-50 text-[10.5px] uppercase tracking-wide text-slate-400 font-black">
            <tr>
              <th class="px-4 py-3 w-9"><input type="checkbox" @change="toggleAll($event)" class="accent-indigo-600"></th>
              <th class="text-left px-4 py-3">Person</th>
              <th class="text-left px-4 py-3">Where it stands</th>
              <th class="text-left px-4 py-3">Held by</th>
              <th class="text-left px-4 py-3">Call back</th>
              <th class="text-right px-4 py-3">Action</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-100">
          <?php foreach ($rows as $t):
              $om   = pipe_outcome_meta((string)$t['outcome']);
              $due  = !empty($t['next_follow_up']) && $t['next_follow_up'] <= date('Y-m-d')
                      && !in_array($t['status'], ['completed','rejected','cancelled'], true);
              $mob  = !empty($t['live_mobile']) ? $t['live_mobile'] : $t['target_mobile'];
              $can  = tasks_can_touch($db, $t); ?>
            <tr class="<?php echo $due ? 'bg-blue-50/50' : ''; ?> hover:bg-slate-50/60">
              <td class="px-4 py-3.5 align-top">
                <?php if ($can): ?><input type="checkbox" value="<?php echo (int)$t['id']; ?>" @change="pick($event)" class="accent-indigo-600"><?php endif; ?>
              </td>
              <td class="px-4 py-3.5">
                <p class="font-bold text-slate-800"><?php echo esc((string)$t['target_name']); ?></p>
                <p class="text-[12px] text-slate-500"><?php echo esc((string)$mob); ?>
                  <span class="text-slate-300">·</span>
                  <span class="font-mono text-[11px]"><?php echo esc((string)$t['task_code']); ?></span></p>
                <?php if ($mob !== ''): ?>
                <div class="flex gap-2 mt-1.5">
                  <a href="tel:<?php echo esc((string)$mob); ?>" class="text-[11px] font-bold text-slate-500 hover:text-indigo-600"><i class="fas fa-phone"></i> Call</a>
                  <a href="https://wa.me/91<?php echo preg_replace('/\D/', '', (string)$mob); ?>" target="_blank" class="text-[11px] font-bold text-emerald-600"><i class="fab fa-whatsapp"></i> WhatsApp</a>
                </div>
                <?php endif; ?>
              </td>
              <td class="px-4 py-3.5">
                <span class="pill <?php echo $om[2]; ?>"><i class="fas <?php echo $om[1]; ?>"></i><?php echo esc($om[0]); ?></span>
                <?php if (!empty($t['remark'])): ?>
                  <p class="text-[12px] text-slate-500 mt-1.5 max-w-[280px]"><?php echo esc((string)$t['remark']); ?></p>
                <?php endif; ?>
              </td>
              <td class="px-4 py-3.5 text-[12.5px]">
                <?php if (empty($t['assigned_to'])): ?>
                  <span class="pill bg-amber-100 text-amber-700"><i class="fas fa-user-slash"></i> nobody</span>
                <?php else: ?>
                  <span class="font-semibold text-slate-700"><?php echo esc((string)$t['assigned_name']); ?></span>
                <?php endif; ?>
              </td>
              <td class="px-4 py-3.5 text-[12.5px]">
                <?php if (!empty($t['next_follow_up'])): ?>
                  <span class="<?php echo $due ? 'font-black text-blue-700' : 'text-slate-600'; ?>"><?php echo date('d M', strtotime((string)$t['next_follow_up'])); ?></span>
                  <?php if ($due): ?><p class="text-[10.5px] font-black text-blue-600 uppercase">due now</p><?php endif; ?>
                <?php else: ?><span class="text-slate-300">—</span><?php endif; ?>
              </td>
              <td class="px-4 py-3.5 text-right">
                <?php if ($can && $t['status'] !== 'completed'): ?>
                <button type="button" @click='openOutcome(<?php echo esc(json_encode([
                            'id' => (int)$t['id'], 'name' => (string)$t['target_name'],
                            'remark' => (string)$t['remark'], 'follow' => (string)$t['next_follow_up']])); ?>)'
                        class="px-4 py-2 rounded-xl bg-slate-900 text-white text-[11.5px] font-bold">
                  <i class="fas fa-pen-to-square mr-1"></i> Update</button>
                <?php elseif ($t['status'] === 'completed'): ?>
                  <span class="pill bg-emerald-600 text-white"><i class="fas fa-circle-check"></i> done</span>
                <?php else: ?><span class="text-[11.5px] text-slate-300">not yours</span><?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        </div>
        <?php endif; ?>
      </div>
      </form>
      <?php endif; ?>

      <?php if ($pages > 1): ?>
      <div class="flex justify-center gap-1.5 mt-5">
        <?php for ($i = max(1, $page - 2); $i <= min($pages, $page + 2); $i++): ?>
          <a href="<?php echo esc(pq(['p' => $i])); ?>"
             class="px-3.5 py-2 rounded-xl text-xs font-bold <?php echo $i === $page ? 'bg-slate-900 text-white' : 'bg-white ring-1 ring-slate-200 text-slate-600'; ?>"><?php echo $i; ?></a>
        <?php endfor; ?>
      </div>
      <?php endif; ?>

      <?php endif; /* general vs queue */ ?>
      <?php endif; /* team / empty / normal */ ?>

    </main>
  </div>
</div>

<!-- ===================== OUTCOME MODAL ===================== -->
<div x-show="oc.open" x-cloak class="fixed inset-0 z-[90] flex items-center justify-center p-4">
  <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="oc.open = false"></div>
  <form method="POST" class="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl max-h-[92vh] flex flex-col">
    <input type="hidden" name="save_outcome" value="1">
    <input type="hidden" name="task_id" :value="oc.id">
    <input type="hidden" name="outcome" :value="oc.pick">
    <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
      <div><h3 class="font-extrabold text-slate-800">What happened?</h3>
           <p class="text-[12px] text-slate-500" x-text="oc.name"></p></div>
      <button type="button" @click="oc.open = false" class="text-slate-400 text-2xl leading-none">&times;</button>
    </div>
    <div class="p-6 overflow-y-auto space-y-2.5">
      <?php if ($T && !$IS_DESK): foreach ($T['outcomes'] as $ok): $m = $OUT[$ok]; ?>
        <button type="button" @click="oc.pick = '<?php echo $ok; ?>'" class="oc" :class="oc.pick === '<?php echo $ok; ?>' && 'on'">
          <span class="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0 <?php echo $m[2]; ?>"><i class="fas <?php echo $m[1]; ?> text-[13px]"></i></span>
          <span class="min-w-0">
            <span class="block font-bold text-[13.5px] text-slate-800"><?php echo $m[0]; ?></span>
            <span class="block text-[12px] text-slate-500 leading-snug"><?php echo $m[4]; ?></span>
          </span>
        </button>
      <?php endforeach; endif; ?>
      <div x-show="oc.pick === 'follow_up'" x-cloak class="pt-2">
        <label class="lbl">Call back on</label>
        <input type="date" name="follow_date" class="fld" x-model="oc.follow" :min="today">
      </div>
      <div class="pt-2">
        <label class="lbl">Remark<span x-show="oc.pick === 'not_interested'" class="text-rose-500"> — required</span></label>
        <textarea name="remark" rows="3" class="fld" x-model="oc.remark" placeholder="What did they say?"></textarea>
      </div>
    </div>
    <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2">
      <button type="button" @click="oc.open = false" class="px-5 py-2.5 rounded-xl text-slate-600 font-bold text-xs">Cancel</button>
      <button class="px-6 py-2.5 rounded-xl bg-indigo-600 text-white font-bold text-xs" :disabled="!oc.pick" :class="!oc.pick && 'opacity-40 pointer-events-none'">
        <i class="fas fa-floppy-disk mr-1"></i> Save</button>
    </div>
  </form>
</div>

<!-- ===================== DESK DECISION MODAL ===================== -->
<div x-show="dk.open" x-cloak class="fixed inset-0 z-[90] flex items-center justify-center p-4">
  <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="dk.open = false"></div>
  <form method="POST" class="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl max-h-[92vh] flex flex-col">
    <input type="hidden" name="desk_decide" value="1">
    <input type="hidden" name="desk" value="<?php echo esc($TAB); ?>">
    <input type="hidden" name="ref_id" :value="dk.id">
    <input type="hidden" name="decision" :value="dk.pick">
    <div class="px-6 py-4 border-b border-slate-100">
      <h3 class="font-extrabold text-slate-800"><?php echo $T ? esc($T['label']) : 'Decision'; ?></h3>
      <p class="text-[12px] text-slate-500" x-text="dk.name"></p>
    </div>
    <div class="p-6 overflow-y-auto space-y-2.5">
      <?php if ($T && $IS_DESK && !empty($T['decisions'])):
        $labels = isset($T['decision_labels']) ? $T['decision_labels'] : [];
        foreach ($T['decisions'] as $dk2): $dv = $DEC[$dk2]; ?>
        <button type="button" @click="dk.pick = '<?php echo $dk2; ?>'" class="oc" :class="dk.pick === '<?php echo $dk2; ?>' && 'on'">
          <span class="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0 bg-<?php echo $dv[2]; ?>-100 text-<?php echo $dv[2]; ?>-700">
            <i class="fas <?php echo $dv[1]; ?> text-[13px]"></i></span>
          <span class="min-w-0">
            <span class="block font-bold text-[13.5px] text-slate-800"><?php echo isset($labels[$dk2]) ? $labels[$dk2] : $dv[0]; ?></span>
            <span class="block text-[12px] text-slate-500 leading-snug"><?php
              echo $dk2 === 'accept' ? 'Approved — it moves on'
                 : ($dk2 === 'hold'  ? 'Stays where it is, with a note for us'
                                     : 'Sent back, or closed'); ?></span>
          </span>
        </button>
      <?php endforeach; endif; ?>
      <div class="pt-2">
        <label class="lbl"><?php echo $T && isset($T['remark_label']) ? $T['remark_label'] : 'Remark'; ?><span x-show="dk.pick && dk.pick !== 'accept'" class="text-rose-500"> — required</span></label>
        <textarea name="remark" rows="3" class="fld" placeholder="What did you find?"></textarea>
      </div>
    </div>
    <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2">
      <button type="button" @click="dk.open = false" class="px-5 py-2.5 rounded-xl text-slate-600 font-bold text-xs">Cancel</button>
      <button class="px-6 py-2.5 rounded-xl bg-slate-900 text-white font-bold text-xs" :disabled="!dk.pick" :class="!dk.pick && 'opacity-40 pointer-events-none'">
        <i class="fas fa-gavel mr-1"></i> Save decision</button>
    </div>
  </form>
</div>

<!-- ===================== ASSIGN MODAL ===================== -->
<div x-show="asg" x-cloak class="fixed inset-0 z-[90] flex items-center justify-center p-4">
  <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="asg = false"></div>
  <div class="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl max-h-[92vh] flex flex-col">
    <div class="px-6 py-4 border-b border-slate-100">
      <h3 class="font-extrabold text-slate-800">Hand <span x-text="picked.length"></span> over</h3>
      <p class="text-[12px] text-slate-500">Pick who does this work, and what they are allowed to reach.</p>
    </div>
    <div class="p-6 overflow-y-auto space-y-4">
      <div>
        <label class="lbl">To</label>
        <select class="fld" x-model="asgStaff" @change="loadAccess()" form="assignForm" name="staff_id">
          <option value="">— choose somebody —</option>
          <?php foreach ($STAFF as $s): ?>
            <option value="<?php echo (int)$s['id']; ?>"><?php echo esc($s['name'] . ' · ' . $s['role_label']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($IS_BOSS): ?>
      <div x-show="asgStaff" x-cloak class="rounded-xl border border-slate-200 p-4">
        <label class="flex items-center gap-2 mb-3">
          <input type="checkbox" checked form="assignForm" name="set_access" value="1" class="accent-indigo-600">
          <span class="text-[12.5px] font-bold text-slate-700">Set what this person can reach</span>
        </label>
        <?php foreach ($ROLES as $rk => $rv):
          $rt = pipe_role_tabs($rk); if (empty($rt)) continue; ?>
          <p class="text-[10.5px] font-black uppercase tracking-wide text-slate-400 mt-3 mb-1.5"><?php echo esc($rv['label']); ?></p>
          <div class="grid grid-cols-2 gap-2">
            <?php foreach ($rt as $k => $v): ?>
              <label class="flex items-center gap-2 text-[12.5px] text-slate-600">
                <input type="checkbox" form="assignForm" name="access[]" value="<?php echo $k; ?>"
                       :checked="asgAccess.includes('<?php echo $k; ?>')" class="accent-indigo-600">
                <?php echo esc($v['label']); ?>
              </label>
            <?php endforeach; ?>
          </div>
        <?php endforeach; ?>
        <p class="text-[11px] text-slate-400 mt-3 leading-snug">They see only what is ticked here, and within a step only the people they hold.</p>
      </div>
      <?php endif; ?>
      <div>
        <label class="lbl">Note (optional)</label>
        <input class="fld" form="assignForm" name="assign_note" placeholder="Anything they should know">
      </div>
    </div>
    <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2">
      <button type="button" @click="asg = false" class="px-5 py-2.5 rounded-xl text-slate-600 font-bold text-xs">Cancel</button>
      <button type="button" @click="$refs.assignForm.submit()" class="px-6 py-2.5 rounded-xl bg-indigo-600 text-white font-bold text-xs"
              :disabled="!asgStaff" :class="!asgStaff && 'opacity-40 pointer-events-none'">
        <i class="fas fa-user-plus mr-1"></i> Hand over</button>
    </div>
  </div>
</div>

<?php if ($IS_BOSS): ?>
<!-- ===================== TEAM ACCESS ===================== -->
<div x-show="team" x-cloak class="fixed inset-0 z-[90] flex items-center justify-center p-4">
  <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="team = false"></div>
  <form method="POST" class="relative w-full max-w-5xl bg-white rounded-2xl shadow-2xl max-h-[92vh] flex flex-col">
    <input type="hidden" name="save_team_access" value="1">
    <div class="px-6 py-4 border-b border-slate-100">
      <h3 class="font-extrabold text-slate-800">Who works on what</h3>
      <p class="text-[12px] text-slate-500">A tick opens that step or desk for them. Within a step they still only see the people they hold.</p>
    </div>
    <div class="p-6 overflow-auto">
      <table class="w-full text-sm">
        <thead class="text-[10px] uppercase tracking-wide text-slate-400 font-black">
          <tr>
            <th class="text-left pb-3 sticky left-0 bg-white">Person</th>
            <?php foreach ($ALLTABS as $k => $v): ?>
              <th class="pb-3 px-1.5 text-center whitespace-nowrap">
                <span class="block text-slate-300 font-bold"><?php echo esc(pipe_roles()[$v['role']]['label']); ?></span>
                <?php echo esc($v['label']); ?></th>
            <?php endforeach; ?>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
        <?php foreach ($STAFF as $s):
              $owner = empty($s['role_id']);
              $has   = pipe_access($db, (int)$s['id']); ?>
          <tr>
            <td class="py-3 sticky left-0 bg-white">
              <p class="font-bold text-slate-800 whitespace-nowrap"><?php echo esc($s['name']); ?></p>
              <p class="text-[11.5px] text-slate-400"><?php echo esc($s['role_label']); ?></p>
            </td>
            <?php foreach (array_keys($ALLTABS) as $k): ?>
              <td class="py-3 px-1.5 text-center">
                <?php if ($owner): ?>
                  <i class="fas fa-infinity text-slate-300" title="the owner account holds everything"></i>
                <?php else: ?>
                  <input type="checkbox" name="team[<?php echo (int)$s['id']; ?>][]" value="<?php echo $k; ?>"
                         <?php echo in_array($k, $has, true) ? 'checked' : ''; ?> class="accent-indigo-600 w-4 h-4">
                <?php endif; ?>
              </td>
            <?php endforeach; ?>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2">
      <button type="button" @click="team = false" class="px-5 py-2.5 rounded-xl text-slate-600 font-bold text-xs">Close</button>
      <button class="px-6 py-2.5 rounded-xl bg-indigo-600 text-white font-bold text-xs"><i class="fas fa-floppy-disk mr-1"></i> Save access</button>
    </div>
  </form>
</div>
<?php endif; ?>

<script>
function board() {
  return {
    sidebarOpen: window.innerWidth >= 768,
    today: '<?php echo date('Y-m-d'); ?>',
    picked: [],
    oc: { open:false, id:0, name:'', pick:'', remark:'', follow:'' },
    dk: { open:false, id:0, name:'', pick:'' },
    asg: false, team: false, asgStaff: '', asgAccess: [],
    access: <?php
      $map = [];
      foreach ($STAFF as $s) { $map[(int)$s['id']] = pipe_access($db, (int)$s['id']); }
      echo json_encode($map);
    ?>,
    pick(e) {
      var v = parseInt(e.target.value, 10);
      if (e.target.checked) { if (this.picked.indexOf(v) < 0) this.picked.push(v); }
      else { this.picked = this.picked.filter(function (x) { return x !== v; }); }
    },
    toggleAll(e) {
      var boxes = document.querySelectorAll('#assignForm tbody input[type=checkbox]');
      this.picked = [];
      for (var i = 0; i < boxes.length; i++) {
        boxes[i].checked = e.target.checked;
        if (e.target.checked) this.picked.push(parseInt(boxes[i].value, 10));
      }
    },
    openOutcome(t) { this.oc = { open:true, id:t.id, name:t.name, pick:'', remark:t.remark || '', follow:t.follow || '' }; },
    openDesk(r)    { this.dk = { open:true, id:r.id, name:r.name, pick:'' }; },
    openAssign()   { this.asg = true; this.asgStaff = ''; this.asgAccess = []; },
    loadAccess()   { this.asgAccess = this.access[this.asgStaff] || []; },
  };
}
</script>

</body>
</html>
