<?php
/* ============================================================================
   WBMCZ ADMIN — ACTIVITY & TASK
   ----------------------------------------------------------------------------
   The board where work is handed out and followed to the end.

     · Super Admin / Admin  see every task, create them, assign them, delete them
     · Employee             sees the tasks they hold or raised, updates them,
                            and can hand one over to a colleague with a reason

   Every create, assign, hand-over, status change and note is written to
   task_activities, so the whole life of a task can be read back at any time.
   ============================================================================ */
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/task_criteria.php';

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

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

tasks_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'); }

$ME       = tasks_actor($db);
$IS_BOSS  = tasks_is_boss($db);
$ROLES    = tasks_roles();
$MODULES  = tasks_modules();
$CATS     = tasks_all_categories($db);
$STATUSES = tasks_statuses();
$PRIOS    = tasks_priorities();
$STAFF    = tasks_staff_list($db);

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

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

/* current slice of the board */
$TAB = $_GET['role'] ?? 'user';   if (!isset($ROLES[$TAB]))     { $TAB = 'user'; }
$MOD = $_GET['mod']  ?? 'lead';   if (!isset($MODULES[$MOD]))   { $MOD = 'lead'; }

/* The rule that says who belongs on this tab — everybody who registered,
   everybody without KYC, and so on. Editable in Admin → Task Criteria. */
tcrit_ensure_schema($db);
$CRIT     = tcrit_get($db, $TAB, $MOD);
$CAN_CRIT = tcrit_can_manage($db);   /* may see the matching people and hand them out */

/* Two views share the tab: the task board, and the people the criteria caught */
$VIEW = ($_GET['view'] ?? 'tasks') === 'people' ? 'people' : 'tasks';

function at_back() {
    $q = array_intersect_key($_GET, array_flip(['role','mod','q','status','prio','assign','range','p']));
    return 'activity_task.php?' . http_build_query($q);
}
function at_qs($over = []) {
    $q = array_merge($_GET, $over);
    unset($q['export'], $q['ajax'], $q['id']);
    $q = array_filter($q, function ($v) { return $v !== '' && $v !== null; });
    return 'activity_task.php?' . http_build_query($q);
}

/* one task row, respecting what this account is allowed to see */
function at_task($db, $id) {
    $r = $db->select("SELECT * FROM tasks WHERE id = ?", [(int)$id]);
    return !empty($r) ? $r[0] : null;
}

/* ============================================================================
   AJAX — task detail + its history
   ============================================================================ */
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $id = (int)($_GET['id'] ?? 0);
    $t  = $id ? at_task($db, $id) : null;

    if (!$t || !tasks_can_touch($db, $t)) { echo json_encode(['ok' => false, 'msg' => 'Task not found.']); exit; }

    $logs = [];
    try { $logs = $db->select("SELECT * FROM task_activities WHERE task_id = ? ORDER BY id DESC LIMIT 300", [$id]); }
    catch (\Throwable $e) {}

    foreach ($logs as &$l) {
        $m = tasks_action_meta($l['action']);
        $l['action_label'] = $m[0]; $l['action_icon'] = $m[1]; $l['action_class'] = $m[2];
        $l['ago'] = tasks_ago($l['created_at']);
        $l['when'] = date('d M Y, h:i A', strtotime($l['created_at']));
    }
    unset($l);

    $t['module_label']   = $GLOBALS['MODULES'][$t['module_key']][0] ?? ucfirst($t['module_key']);
    $t['status_label']   = tasks_status_meta($t['status'])[0];
    $t['priority_label'] = tasks_priority_meta($t['priority'])[0];
    $t['can_edit']       = tasks_can_touch($db, $t) ? 1 : 0;

    echo json_encode(['ok' => true, 'task' => $t, 'logs' => $logs]);
    exit;
}

/* ============================================================================
   CREATE  —  admin / super admin only
   ============================================================================ */
/* ---------------------------------------------------------------------------
   BULK ASSIGN — hand a whole list of matching people out in one go.
   The list comes from the criteria behind this tab (Admin → Task Criteria),
   so "Lead" is everybody who registered, "KYC" is everybody who never filled
   it, and so on. One task is raised per person.
   --------------------------------------------------------------------------- */
if (isset($_POST['bulk_assign_people'])) {
    if (!tcrit_can_manage($db)) {
        $_SESSION['flash_error'] = 'Your role does not allow creating tasks. Ask an administrator to tick Activity & Task → Create a task.';
        redirect(at_qs([]));
    }

    $ids = array_values(array_filter(array_map('intval', explode(',', (string)($_POST['people_ids'] ?? '')))));
    if (empty($ids)) {
        $_SESSION['flash_error'] = 'Nobody was ticked.';
        redirect(at_qs(['view' => 'people']));
    }

    $to       = (int)($_POST['assigned_to'] ?? 0);
    $cat_key  = sanitize($_POST['category_key'] ?? '');
    $priority = sanitize($_POST['priority'] ?? 'medium');
    $due      = trim((string)($_POST['due_date'] ?? ''));
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $due)) { $due = null; }
    $note     = sanitize($_POST['bulk_remark'] ?? '');
    $titleTpl = trim((string)sanitize($_POST['bulk_title'] ?? ''));

    $to_name = $to_role = '';
    if ($to > 0) {
        foreach (tasks_staff_list($db) as $st) {
            if ((int)$st['id'] === $to) { $to_name = (string)$st['name']; $to_role = (string)($st['role_name'] ?? ''); break; }
        }
    }

    /* only people who really match the tab's criteria can be assigned from here */
    $chunk = implode(',', array_map('intval', $ids));
    $rows  = tcrit_rows($db, $CRIT['rules'], $MOD, $CRIT['sort'], 500, 0, "u.id IN ($chunk)");

    $made = 0;
    foreach ($rows as $r) {
        $title = $titleTpl !== '' ? $titleTpl : ($MODULES[$MOD][0] . ' — ' . $r['name']);
        $id = tasks_create($db, [
            'scope_role'     => $TAB,
            'module_key'     => $MOD,
            'category_key'   => $cat_key !== '' ? $cat_key : 'gen_task',
            'title'          => $title,
            'description'    => $note,
            'target_user_id' => (int)$r['id'],
            'target_name'    => (string)$r['name'],
            'target_mobile'  => (string)$r['mobile'],
            'assigned_to'    => $to > 0 ? $to : null,
            'assigned_name'  => $to_name ?: null,
            'assigned_role'  => $to_role ?: null,
            'priority'       => $priority,
            'due_date'       => $due,
            'remark'         => $note,
        ]);
        if ($id) { $made++; }
    }

    $_SESSION['flash_success'] = $made . ' task(s) raised'
        . ($to_name !== '' ? ' and handed to ' . $to_name : ' — still unassigned') . '.';
    redirect(at_qs(['view' => 'people']));
}

if (isset($_POST['create_task'])) {
    if (!tasks_can_manage($db)) {
        $_SESSION['flash_error'] = 'Only an administrator can raise a new task.';
        redirect(at_back());
    }
    $mod   = $_POST['module_key'] ?? 'general';
    $cat   = $_POST['category_key'] ?? 'gen_task';
    $title = trim((string)($_POST['title'] ?? ''));
    if ($title === '') { $title = tasks_category_label($db, $mod, $cat); }

    $aid   = (int)($_POST['assigned_to'] ?? 0);
    $aname = ''; $arole = '';
    foreach ($STAFF as $s) { if ((int)$s['id'] === $aid) { $aname = $s['name']; $arole = $s['role_key']; break; } }

    $due = trim((string)($_POST['due_date'] ?? ''));
    $due = $due !== '' ? str_replace('T', ' ', $due) . (strlen($due) <= 10 ? ' 23:59:00' : ':00') : null;

    $newId = tasks_create($db, [
        'scope_role'      => $_POST['scope_role'] ?? $TAB,
        'module_key'      => $mod,
        'category_key'    => $cat,
        'title'           => $title,
        'description'     => trim((string)($_POST['description'] ?? '')),
        'target_user_id'  => (int)($_POST['target_user_id'] ?? 0),
        'target_name'     => trim((string)($_POST['target_name'] ?? '')),
        'target_mobile'   => trim((string)($_POST['target_mobile'] ?? '')),
        'target_ref_type' => trim((string)($_POST['target_ref_type'] ?? '')),
        'target_ref_id'   => (int)($_POST['target_ref_id'] ?? 0),
        'assigned_to'     => $aid,
        'assigned_name'   => $aname,
        'assigned_role'   => $arole,
        'priority'        => $_POST['priority'] ?? 'medium',
        'status'          => 'pending',
        'due_date'        => $due,
        'next_follow_up'  => trim((string)($_POST['next_follow_up'] ?? '')) ?: null,
        'remark'          => trim((string)($_POST['remark'] ?? '')),
    ]);

    if ($newId) {
        activity_log($db, 'create', 'Activity & Task', "Raised task: $title" . ($aname ? " → $aname" : ''), 'task', $newId);
        $_SESSION['flash_success'] = 'Task created' . ($aname ? " and assigned to $aname." : '. Assign it when you are ready.');
    } else {
        $_SESSION['flash_error'] = 'The task could not be saved. Please try again.';
    }
    redirect(at_back());
}

/* ============================================================================
   UPDATE  —  status, priority, progress, due date, remark
   The person holding the task may do this; so may an administrator.
   ============================================================================ */
if (isset($_POST['update_task'])) {
    $id = (int)($_POST['task_id'] ?? 0);
    $t  = at_task($db, $id);
    if (!$t || !tasks_can_touch($db, $t)) {
        $_SESSION['flash_error'] = 'This task is not yours to change.';
        redirect(at_back());
    }

    $status   = $_POST['status']   ?? $t['status'];
    $priority = $_POST['priority'] ?? $t['priority'];
    $progress = max(0, min(100, (int)($_POST['progress'] ?? $t['progress'])));
    $remark   = trim((string)($_POST['remark'] ?? ''));
    $reason   = trim((string)($_POST['reject_reason'] ?? ''));
    $nfu      = trim((string)($_POST['next_follow_up'] ?? ''));
    $due      = trim((string)($_POST['due_date'] ?? ''));
    $due      = $due !== '' ? str_replace('T', ' ', $due) . (strlen($due) <= 10 ? ' 23:59:00' : ':00') : $t['due_date'];

    if (!isset($STATUSES[$status])) { $status = $t['status']; }
    if (!isset($PRIOS[$priority]))  { $priority = $t['priority']; }

    /* an employee may not quietly change the deadline the admin set */
    if (!$IS_BOSS) { $due = $t['due_date']; }

    $started   = $t['started_at'];
    $completed = $t['completed_at'];
    if ($status === 'in_progress' && empty($started))   { $started = date('Y-m-d H:i:s'); }
    if ($status === 'completed')                        { $completed = date('Y-m-d H:i:s'); $progress = 100; }
    if ($status !== 'completed')                        { $completed = null; }

    try {
        $db->insert(
            "UPDATE tasks SET status = ?, priority = ?, progress = ?, due_date = ?, next_follow_up = ?,
                    remark = ?, reject_reason = ?, started_at = ?, completed_at = ?, updated_at = NOW()
             WHERE id = ?",
            [$status, $priority, $progress, $due ?: null, $nfu ?: null,
             $remark !== '' ? $remark : $t['remark'], $reason !== '' ? $reason : $t['reject_reason'],
             $started, $completed, $id]
        );
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = 'The task could not be updated.';
        redirect(at_back());
    }

    /* every change gets its own line in the task's history */
    if ($status !== $t['status']) {
        $act = $status === 'completed' ? 'complete' : ($status === 'rejected' ? 'reject' : 'status');
        if (in_array($t['status'], ['completed', 'rejected'], true) && !in_array($status, ['completed', 'rejected'], true)) { $act = 'reopen'; }
        tasks_log($db, $id, $act, 'Status',
            tasks_status_meta($t['status'])[0], tasks_status_meta($status)[0],
            $reason !== '' ? $reason : $remark, $t['task_code']);
    }
    if ($priority !== $t['priority']) {
        tasks_log($db, $id, 'priority', 'Priority', tasks_priority_meta($t['priority'])[0], tasks_priority_meta($priority)[0], '', $t['task_code']);
    }
    if ((int)$progress !== (int)$t['progress']) {
        tasks_log($db, $id, 'progress', 'Progress', $t['progress'] . '%', $progress . '%', '', $t['task_code']);
    }
    if ($due !== $t['due_date']) {
        tasks_log($db, $id, 'due', 'Due date',
            $t['due_date'] ? date('d M Y h:i A', strtotime($t['due_date'])) : 'none',
            $due ? date('d M Y h:i A', strtotime($due)) : 'none', '', $t['task_code']);
    }
    if ($remark !== '' && $remark !== (string)$t['remark']) {
        tasks_log($db, $id, 'note', 'Remark', null, null, $remark, $t['task_code']);
    }

    activity_log($db, 'update', 'Activity & Task', "Updated task {$t['task_code']} → " . tasks_status_meta($status)[0], 'task', $id);
    $_SESSION['flash_success'] = "Task {$t['task_code']} updated.";
    redirect(at_back());
}

/* ============================================================================
   HAND OVER  —  the task moves to another staff member, with a reason
   ============================================================================ */
if (isset($_POST['reassign_task'])) {
    $id = (int)($_POST['task_id'] ?? 0);
    $t  = at_task($db, $id);
    if (!$t || !tasks_can_touch($db, $t)) {
        $_SESSION['flash_error'] = 'This task is not yours to hand over.';
        redirect(at_back());
    }

    $to = (int)($_POST['assign_to'] ?? 0);
    if ($to <= 0 || $to === (int)$t['assigned_to']) {
        $_SESSION['flash_error'] = 'Pick a different person to hand this task to.';
        redirect(at_back());
    }

    $name = ''; $role = '';
    foreach ($STAFF as $s) { if ((int)$s['id'] === $to) { $name = $s['name']; $role = $s['role_key']; break; } }
    if ($name === '') {
        $_SESSION['flash_error'] = 'That staff account was not found.';
        redirect(at_back());
    }

    $why = trim((string)($_POST['handover_reason'] ?? ''));
    if ($why === '') { $why = 'No reason given.'; }

    $wasName = $t['assigned_name'] ?: 'nobody';
    $newStatus = $t['status'] === 'completed' ? 'completed' : 'pending';

    try {
        $db->insert(
            "UPDATE tasks SET assigned_to = ?, assigned_name = ?, assigned_role = ?, assigned_at = NOW(),
                    assigned_by = ?, assigned_by_name = ?, status = ?, reassign_count = reassign_count + 1,
                    updated_at = NOW()
             WHERE id = ?",
            [$to, $name, $role, $ME['id'], $ME['name'], $newStatus, $id]
        );
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = 'The hand-over could not be saved.';
        redirect(at_back());
    }

    tasks_log($db, $id, 'reassign', 'Assigned to', $wasName, $name, $why, $t['task_code']);
    activity_log($db, 'assign', 'Activity & Task', "Handed task {$t['task_code']} from $wasName to $name — $why", 'task', $id);

    $_SESSION['flash_success'] = "Task {$t['task_code']} handed over to $name. The reason is saved in the task log.";
    redirect(at_back());
}

/* ============================================================================
   NOTE  —  a line of progress on the task, without changing anything else
   ============================================================================ */
if (isset($_POST['add_task_note'])) {
    $id = (int)($_POST['task_id'] ?? 0);
    $t  = at_task($db, $id);
    $nt = trim((string)($_POST['note'] ?? ''));
    if (!$t || !tasks_can_touch($db, $t) || $nt === '') {
        $_SESSION['flash_error'] = 'Nothing was saved.';
        redirect(at_back());
    }
    tasks_log($db, $id, 'note', 'Note', null, null, $nt, $t['task_code']);
    try { $db->insert("UPDATE tasks SET updated_at = NOW() WHERE id = ?", [$id]); } catch (\Throwable $e) {}
    activity_log($db, 'update', 'Activity & Task', "Note on task {$t['task_code']}", 'task', $id);
    $_SESSION['flash_success'] = 'Note added to the task log.';
    redirect(at_back());
}

/* ============================================================================
   DELETE  —  administrators only
   ============================================================================ */
if (isset($_POST['delete_task'])) {
    if (!tasks_can_manage($db)) {
        $_SESSION['flash_error'] = 'Only an administrator can delete a task.';
        redirect(at_back());
    }
    $id = (int)($_POST['task_id'] ?? 0);
    $t  = at_task($db, $id);
    if ($t) {
        try {
            $db->insert("DELETE FROM tasks WHERE id = ?", [$id]);
            $db->insert("DELETE FROM task_activities WHERE task_id = ?", [$id]);
            activity_log($db, 'delete', 'Activity & Task', "Deleted task {$t['task_code']} — {$t['title']}", 'task', $id);
            $_SESSION['flash_success'] = "Task {$t['task_code']} deleted.";
        } catch (\Throwable $e) { $_SESSION['flash_error'] = 'The task could not be deleted.'; }
    }
    redirect(at_back());
}

/* ============================================================================
   FILTERS + DATA
   ============================================================================ */
$f_q      = trim((string)($_GET['q']      ?? ''));
$f_status = trim((string)($_GET['status'] ?? ''));
$f_prio   = trim((string)($_GET['prio']   ?? ''));
$f_assign = trim((string)($_GET['assign'] ?? ''));
$f_range  = trim((string)($_GET['range']  ?? ''));
$f_from   = trim((string)($_GET['from']   ?? ''));
$f_to     = trim((string)($_GET['to']     ?? ''));
$page     = max(1, (int)($_GET['p'] ?? 1));
$per      = 25;

/* what this account is allowed to see at all */
list($scopeSql, $scopeParams) = tasks_scope_sql($db, 't');

$where  = [$scopeSql, "t.scope_role = ?", "t.module_key = ?"];
$params = array_merge($scopeParams, [$TAB, $MOD]);

if ($f_q !== '') {
    $where[] = "(t.task_code LIKE ? OR t.title LIKE ? OR t.target_name LIKE ? OR t.target_mobile LIKE ? OR t.assigned_name LIKE ? OR t.category_label LIKE ?)";
    $like = "%$f_q%";
    array_push($params, $like, $like, $like, $like, $like, $like);
}
if ($f_status !== '' && isset($STATUSES[$f_status])) { $where[] = "t.status = ?";   $params[] = $f_status; }
if ($f_prio   !== '' && isset($PRIOS[$f_prio]))      { $where[] = "t.priority = ?"; $params[] = $f_prio; }
if ($f_assign === 'me')       { $where[] = "t.assigned_to = ?"; $params[] = $ME['id']; }
elseif ($f_assign === 'none') { $where[] = "(t.assigned_to IS NULL OR t.assigned_to = 0)"; }
elseif ($f_assign !== '')     { $where[] = "t.assigned_to = ?"; $params[] = (int)$f_assign; }

switch ($f_range) {
    case 'today':   $where[] = "DATE(t.created_at) = CURDATE()"; break;
    case '7':       $where[] = "t.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"; break;
    case '30':      $where[] = "t.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"; break;
    case 'overdue': $where[] = "t.due_date IS NOT NULL AND t.due_date < NOW() AND t.status NOT IN ('completed','rejected','cancelled')"; break;
    case 'custom':
        if ($f_from !== '') { $where[] = "DATE(t.created_at) >= ?"; $params[] = $f_from; }
        if ($f_to   !== '') { $where[] = "DATE(t.created_at) <= ?"; $params[] = $f_to; }
        break;
}
$where_sql = implode(' AND ', $where);

/* counters — for this slice, and for every chip / tab so the numbers show up */
$stats = tasks_stats($db, $where_sql, $params);

$modCounts = [];
try {
    $r = $db->select("SELECT module_key, COUNT(*) c FROM tasks t WHERE $scopeSql AND t.scope_role = ? GROUP BY module_key",
                     array_merge($scopeParams, [$TAB]));
    foreach ($r as $x) { $modCounts[$x['module_key']] = (int)$x['c']; }
} catch (\Throwable $e) {}

$roleCounts = [];
try {
    $r = $db->select("SELECT scope_role, COUNT(*) c FROM tasks t WHERE $scopeSql GROUP BY scope_role", $scopeParams);
    foreach ($r as $x) { $roleCounts[$x['scope_role']] = (int)$x['c']; }
} catch (\Throwable $e) {}

/* ---------------- CSV EXPORT ---------------- */
if (isset($_GET['export'])) {
    $rows = [];
    try { $rows = $db->select("SELECT t.* FROM tasks t WHERE $where_sql ORDER BY t.id DESC LIMIT 10000", $params); }
    catch (\Throwable $e) {}

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=tasks_' . $TAB . '_' . $MOD . '_' . date('Ymd_His') . '.csv');
    $out = fopen('php://output', 'w');
    /* the separator / enclosure / escape are passed on purpose: PHP 8.4 deprecates
       leaving $escape out, and a deprecation notice would corrupt the CSV */
    fputcsv($out, ['Task ID','Role','Module','Task Type','Title','About','Mobile','Assigned To',
                   'Priority','Status','Progress','Due Date','Created By','Created On','Hand-overs'], ',', '"', '\\');
    foreach ($rows as $r) {
        fputcsv($out, [
            $r['task_code'], $ROLES[$r['scope_role']][0] ?? $r['scope_role'],
            $MODULES[$r['module_key']][0] ?? $r['module_key'], $r['category_label'], $r['title'],
            $r['target_name'], $r['target_mobile'], $r['assigned_name'],
            tasks_priority_meta($r['priority'])[0], tasks_status_meta($r['status'])[0],
            $r['progress'] . '%', $r['due_date'], $r['created_by_name'], $r['created_at'], $r['reassign_count'],
        ], ',', '"', '\\');
    }
    fclose($out);
    activity_log($db, 'export', 'Activity & Task', 'Exported the task list');
    exit;
}

$total = 0;
try { $c = $db->select("SELECT COUNT(*) c FROM tasks t WHERE $where_sql", $params); $total = (int)($c[0]['c'] ?? 0); }
catch (\Throwable $e) {}
$pages  = max(1, (int)ceil($total / $per));
$page   = min($page, $pages);
$offset = ($page - 1) * $per;

/* The task keeps the number that was typed when it was raised, but people change
   their number. Bring the account's current call / WhatsApp numbers along too, so
   the buttons in the Action column always dial something that still works. */
$tasks = [];
$__cols = "t.*, u.mobile AS u_mobile, u.call_number AS u_call, u.whatsapp_number AS u_wa";
$__join = "LEFT JOIN users u ON u.id = t.target_user_id";
try {
    $tasks = $db->select(
        "SELECT $__cols FROM tasks t $__join WHERE $where_sql
         ORDER BY FIELD(t.status,'pending','in_progress','followup','on_hold','completed','rejected','cancelled'),
                  FIELD(t.priority,'urgent','high','medium','low'), t.due_date IS NULL, t.due_date ASC, t.id DESC
         LIMIT $per OFFSET $offset", $params);
} catch (\Throwable $e) {}

/* an older database may not have call_number / whatsapp_number — fall back quietly */
if (empty($tasks)) {
    try {
        $tasks = $db->select(
            "SELECT t.*, u.mobile AS u_mobile FROM tasks t $__join WHERE $where_sql
             ORDER BY FIELD(t.status,'pending','in_progress','followup','on_hold','completed','rejected','cancelled'),
                      FIELD(t.priority,'urgent','high','medium','low'), t.due_date IS NULL, t.due_date ASC, t.id DESC
             LIMIT $per OFFSET $offset", $params);
    } catch (\Throwable $e) {}
}

/**
 * The two numbers the Action column needs.
 * Prefers whatever was written on the task, then the account's own numbers.
 * @return array ['call' => '10 digits or empty', 'wa' => '10 digits or empty']
 */
function at_phone($t) {
    $clean = function ($v) {
        $d = preg_replace('/\D/', '', (string)$v);
        if (strlen($d) > 10) { $d = substr($d, -10); }
        return strlen($d) === 10 ? $d : '';
    };
    $onTask = $clean($t['target_mobile'] ?? '');
    $call   = $clean($t['u_call'] ?? '') ?: ($onTask ?: $clean($t['u_mobile'] ?? ''));
    $wa     = $clean($t['u_wa']   ?? '') ?: ($onTask ?: $clean($t['u_mobile'] ?? ''));
    return ['call' => $call, 'wa' => $wa];
}

/* people the board can offer in the "Assigned To" filter */
$assignables = $STAFF;
?>
<!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 htmlspecialchars($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@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        [x-cloak] { display: none !important; }
        .hide-scrollbar::-webkit-scrollbar { display: none; }
        .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
        .lbl  { display:block; font-size:11px; font-weight:700; color:#475569; margin-bottom:4px; }
        .fld  { width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:8px 11px; font-size:13px; background:#fff; }
        .fld:focus { outline:none; border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.15); }
        .chip { white-space:nowrap; }
        .tl::before { content:''; position:absolute; left:15px; top:28px; bottom:-10px; width:2px; background:#e2e8f0; }
        .tl:last-child::before { display:none; }
    </style>
</head>
<body class="bg-gray-50" x-data="taskBoard()" 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 ============ -->
        <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 transition-colors"><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
                            ? 'Hand work to your team and follow it to the end'
                            : 'The work assigned to you, and everything you have raised'; ?>
                    </p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <a href="<?php echo htmlspecialchars(at_qs(['export' => 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 transition-colors">
                    <i class="fas fa-file-csv"></i> Export
                </a>
                <?php if ($IS_BOSS): ?>
                <button @click="openCreate()" 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 transition-all">
                    <i class="fas fa-plus"></i> Create Task
                </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 flex items-center shadow-sm text-sm">
                <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($flash_ok); ?></span>
            </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 flex items-center shadow-sm text-sm">
                <i class="fas fa-circle-exclamation mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($flash_err); ?></span>
            </div>
            <?php endif; ?>

            <!-- ============ ROLE TABS ============ -->
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 mb-4">
                <?php foreach ($ROLES as $rk => $rv):
                    $on = ($rk === $TAB);
                    $n  = $roleCounts[$rk] ?? 0;
                ?>
                <a href="<?php echo htmlspecialchars(at_qs(['role' => $rk, 'p' => 1])); ?>"
                   class="relative flex items-center justify-center gap-2 px-4 py-3.5 rounded-2xl text-sm font-bold transition-all border
                          <?php echo $on
                            ? 'bg-gradient-to-r ' . $rv[2] . ' text-white border-transparent shadow-lg'
                            : 'bg-white text-slate-600 border-slate-200 hover:border-slate-300 hover:shadow-sm'; ?>">
                    <i class="fas <?php echo $rv[1]; ?>"></i>
                    <span><?php echo $rv[0]; ?></span>
                    <?php if ($n): ?>
                    <span class="ml-1 text-[10px] font-black px-1.5 py-0.5 rounded-full <?php echo $on ? 'bg-white/25' : 'bg-slate-100 text-slate-500'; ?>"><?php echo $n; ?></span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>

            <!-- ============ MODULE CHIPS ============ -->
            <div class="flex gap-2 overflow-x-auto hide-scrollbar pb-1 mb-6">
                <?php foreach ($MODULES as $mk => $mv):
                    $on = ($mk === $MOD);
                    $n  = $modCounts[$mk] ?? 0;
                ?>
                <a href="<?php echo htmlspecialchars(at_qs(['mod' => $mk, 'p' => 1])); ?>"
                   class="chip flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-bold border transition-all
                          <?php echo $on
                            ? 'bg-white border-indigo-400 text-indigo-600 ring-2 ring-indigo-100 shadow-sm'
                            : 'bg-white border-slate-200 text-slate-500 hover:border-slate-300'; ?>">
                    <i class="fas <?php echo $mv[1]; ?> <?php echo $on ? 'text-indigo-500' : 'text-slate-400'; ?>"></i>
                    <?php echo $mv[0]; ?>
                    <?php if ($n): ?><span class="text-[10px] font-black text-slate-400">(<?php echo $n; ?>)</span><?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>

            <!-- ============ TASKS  |  PEOPLE  switch ============ -->
            <?php
                /* Everyone the tab's criteria catches, and how many of them */
                $people_total = 0; $people = []; $people_ids = [];
                if ($CAN_CRIT && (int)$CRIT['status'] === 1) {
                    $people_total = tcrit_count($db, $CRIT['rules'], $MOD);
                }
                $pp_per  = 100;
                $pp_page = max(1, (int)($_GET['pp'] ?? 1));
                if ($VIEW === 'people' && $CAN_CRIT) {
                    $people = tcrit_rows($db, $CRIT['rules'], $MOD, $CRIT['sort'], $pp_per, ($pp_page - 1) * $pp_per);
                    foreach ($people as $pr) { $people_ids[] = (int)$pr['id']; }
                }
                $pp_pages = max(1, (int)ceil($people_total / $pp_per));
            ?>
            <?php if ($CAN_CRIT): ?>
            <div class="flex flex-wrap items-center gap-2 mb-4">
                <a href="<?php echo htmlspecialchars(at_qs(['view' => 'tasks', 'pp' => 1])); ?>"
                   class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-bold border
                          <?php echo $VIEW === 'tasks' ? 'bg-slate-900 text-white border-slate-900' : 'bg-white text-slate-600 border-slate-200'; ?>">
                    <i class="fas fa-list-check"></i> Tasks
                </a>
                <a href="<?php echo htmlspecialchars(at_qs(['view' => 'people', 'pp' => 1])); ?>"
                   class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-bold border
                          <?php echo $VIEW === 'people' ? 'bg-slate-900 text-white border-slate-900' : 'bg-white text-slate-600 border-slate-200'; ?>">
                    <i class="fas fa-users"></i>
                    <?php echo esc($CRIT['label'] !== '' ? $CRIT['label'] : 'Matching people'); ?>
                    <span class="text-[10px] font-black px-1.5 py-0.5 rounded-full <?php echo $VIEW === 'people' ? 'bg-white/25' : 'bg-slate-100 text-slate-500'; ?>">
                        <?php echo number_format($people_total); ?>
                    </span>
                </a>
                <a href="task_criteria.php?role=<?php echo urlencode($TAB); ?>&mod=<?php echo urlencode($MOD); ?>"
                   class="ml-auto inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-slate-600 text-xs font-bold hover:border-indigo-300">
                    <i class="fas fa-sliders text-indigo-500"></i> Criteria
                </a>
            </div>
            <?php endif; ?>

            <?php if ($VIEW === 'people' && $CAN_CRIT): ?>
            <!-- ============ PEOPLE THE CRITERIA CAUGHT ============ -->
            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden mb-6"
                 x-data="peopleBox(<?php echo htmlspecialchars(json_encode($people_ids), ENT_QUOTES); ?>)">

                <div class="p-5 md:p-6 border-b border-slate-100 flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-extrabold text-slate-800">
                            <?php echo esc($CRIT['label'] !== '' ? $CRIT['label'] : $MODULES[$MOD][0] . ' — matching people'); ?>
                        </h3>
                        <p class="text-xs text-slate-400 mt-0.5">
                            <?php echo esc(tcrit_summary($CRIT['rules'])); ?>
                            · <b><?php echo number_format($people_total); ?></b> match
                        </p>
                    </div>
                    <a href="task_criteria.php?role=<?php echo urlencode($TAB); ?>&mod=<?php echo urlencode($MOD); ?>"
                       class="text-[11px] font-bold text-indigo-600 hover:underline">Change who shows here</a>
                </div>

                <!-- bulk bar -->
                <div x-show="sel.length" style="display:none" class="px-5 md:px-6 py-3 bg-slate-900 text-white">
                    <form method="POST" class="flex flex-wrap items-end gap-2">
                        <input type="hidden" name="people_ids" :value="sel.join(',')">
                        <span class="text-xs font-bold mr-1"><span x-text="sel.length"></span> selected</span>

                        <div>
                            <label class="block text-[9px] font-black uppercase tracking-wide text-white/60 mb-1">Task type</label>
                            <select name="category_key" class="px-2.5 py-1.5 rounded-lg text-slate-800 text-xs font-semibold" style="min-width:11rem">
                                <?php foreach (($CATS[$MOD] ?? ['gen_task' => 'General task']) as $ck => $cl): ?>
                                    <option value="<?php echo esc($ck); ?>"><?php echo esc(is_array($cl) ? ($cl['label'] ?? $ck) : $cl); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[9px] font-black uppercase tracking-wide text-white/60 mb-1">Hand to</label>
                            <select name="assigned_to" class="px-2.5 py-1.5 rounded-lg text-slate-800 text-xs font-semibold" style="min-width:10rem">
                                <option value="0">Nobody yet</option>
                                <?php foreach (tasks_staff_list($db) as $st): ?>
                                    <option value="<?php echo (int)$st['id']; ?>"><?php echo esc($st['name']); ?><?php echo !empty($st['role_name']) ? ' · ' . esc($st['role_name']) : ''; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[9px] font-black uppercase tracking-wide text-white/60 mb-1">Priority</label>
                            <select name="priority" class="px-2.5 py-1.5 rounded-lg text-slate-800 text-xs font-semibold">
                                <?php foreach ($PRIOS as $pk => $pv): ?>
                                    <option value="<?php echo esc($pk); ?>" <?php echo $pk === 'medium' ? 'selected' : ''; ?>><?php echo esc(is_array($pv) ? $pv[0] : $pv); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[9px] font-black uppercase tracking-wide text-white/60 mb-1">Due</label>
                            <input type="date" name="due_date" class="px-2.5 py-1.5 rounded-lg text-slate-800 text-xs font-semibold">
                        </div>
                        <div class="flex-1 min-w-[10rem]">
                            <label class="block text-[9px] font-black uppercase tracking-wide text-white/60 mb-1">Note</label>
                            <input name="bulk_remark" placeholder="What should they do?" class="w-full px-2.5 py-1.5 rounded-lg text-slate-800 text-xs font-semibold">
                        </div>

                        <button type="submit" name="bulk_assign_people" value="1"
                                @click="return confirm('Raise a task for ' + sel.length + ' person(s)?')"
                                class="px-4 py-2 rounded-lg bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-black">
                            <i class="fas fa-user-check mr-1"></i>Assign
                        </button>
                        <button type="button" @click="sel = []" class="px-3 py-2 text-xs font-bold text-white/70 hover:text-white">Clear</button>
                    </form>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-left text-xs">
                        <thead>
                            <tr class="bg-slate-50 text-[9.5px] uppercase tracking-wider text-slate-400">
                                <th class="p-3 w-9"><input type="checkbox" :checked="allOnPage()" @change="toggleAll($event.target.checked)"></th>
                                <th class="p-3 font-black">Member</th>
                                <th class="p-3 font-black">Contact</th>
                                <th class="p-3 font-black">Location</th>
                                <th class="p-3 font-black">KYC</th>
                                <th class="p-3 font-black">Subscription</th>
                                <th class="p-3 font-black">Orders</th>
                                <th class="p-3 font-black">Lead</th>
                                <th class="p-3 font-black">Registered</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                        <?php if (empty($people)): ?>
                            <tr><td colspan="9" class="p-10 text-center text-slate-400">
                                Nobody matches this tab's criteria right now.
                                <a href="task_criteria.php?role=<?php echo urlencode($TAB); ?>&mod=<?php echo urlencode($MOD); ?>" class="text-indigo-600 font-bold">Loosen it</a>.
                            </td></tr>
                        <?php else: foreach ($people as $pr):
                            $k = (string)($pr['kyc_status'] ?? '');
                        ?>
                            <tr class="hover:bg-slate-50/60">
                                <td class="p-3"><input type="checkbox" :checked="isSel(<?php echo (int)$pr['id']; ?>)" @change="toggleOne(<?php echo (int)$pr['id']; ?>)"></td>
                                <td class="p-3">
                                    <p class="font-extrabold text-slate-800"><?php echo esc($pr['name']); ?></p>
                                    <p class="text-[10px] text-slate-400">WBMCZ<?php echo str_pad((string)$pr['id'], 4, '0', STR_PAD_LEFT); ?></p>
                                </td>
                                <td class="p-3">
                                    <p class="font-semibold text-slate-700"><?php echo esc($pr['mobile']); ?></p>
                                    <div class="flex gap-1 mt-1">
                                        <a href="tel:<?php echo esc($pr['mobile']); ?>" class="px-2 py-0.5 rounded bg-slate-500 text-white text-[10px] font-bold"><i class="fas fa-phone"></i></a>
                                        <a href="https://wa.me/91<?php echo preg_replace('/\D/', '', (string)$pr['mobile']); ?>" target="_blank" class="px-2 py-0.5 rounded bg-emerald-600 text-white text-[10px] font-bold"><i class="fab fa-whatsapp"></i></a>
                                    </div>
                                </td>
                                <td class="p-3 text-[11px] text-slate-500">
                                    <?php echo esc($pr['district'] ?: '—'); ?><br><span class="text-slate-400"><?php echo esc($pr['state'] ?: ''); ?></span>
                                </td>
                                <td class="p-3">
                                    <?php if ($k === 'approved'): ?><span class="px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 text-[10px] font-black">Approved</span>
                                    <?php elseif ($k === 'pending'): ?><span class="px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 text-[10px] font-black">Pending</span>
                                    <?php elseif ($k === 'rejected'): ?><span class="px-2 py-0.5 rounded-full bg-rose-100 text-rose-700 text-[10px] font-black">Rejected</span>
                                    <?php else: ?><span class="px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 text-[10px] font-black">Not filled</span><?php endif; ?>
                                </td>
                                <td class="p-3">
                                    <?php if (!empty($pr['is_subscribed'])): ?><span class="px-2 py-0.5 rounded-full bg-violet-100 text-violet-700 text-[10px] font-black">Active</span>
                                    <?php else: ?><span class="px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 text-[10px] font-black">None</span><?php endif; ?>
                                </td>
                                <td class="p-3 text-[11px] font-bold text-slate-600"><?php echo (int)$pr['order_count']; ?></td>
                                <td class="p-3 text-[11px]">
                                    <?php if (!empty($pr['lead_status'])): ?>
                                        <span class="font-bold text-slate-700"><?php echo esc(ucfirst(str_replace('_', ' ', (string)$pr['lead_status']))); ?></span><br>
                                        <span class="text-[10px] text-slate-400"><?php echo esc($pr['lead_owner'] ?: 'no owner'); ?></span>
                                    <?php else: ?><span class="text-slate-300">—</span><?php endif; ?>
                                </td>
                                <td class="p-3 text-[11px] text-slate-500"><?php echo !empty($pr['created_at']) ? date('d M Y', strtotime($pr['created_at'])) : '—'; ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($pp_pages > 1): ?>
                <div class="flex flex-wrap items-center justify-center gap-1.5 p-4 border-t border-slate-100">
                    <?php for ($i = 1; $i <= min($pp_pages, 15); $i++): ?>
                        <a href="<?php echo htmlspecialchars(at_qs(['view' => 'people', 'pp' => $i])); ?>"
                           class="px-3 py-1.5 rounded-lg text-xs font-bold <?php echo $i === $pp_page ? 'bg-slate-900 text-white' : 'bg-white border border-slate-200 text-slate-600'; ?>"><?php echo $i; ?></a>
                    <?php endfor; ?>
                </div>
                <?php endif; ?>
            </div>

            <script>
            function peopleBox(ids) {
                return {
                    sel: [], pageIds: ids || [],
                    isSel(i) { return this.sel.indexOf(i) > -1; },
                    toggleOne(i) { const k = this.sel.indexOf(i); if (k > -1) this.sel.splice(k, 1); else this.sel.push(i); },
                    allOnPage() { return this.pageIds.length > 0 && this.pageIds.every(i => this.sel.includes(i)); },
                    toggleAll(on) {
                        if (on) { this.pageIds.forEach(i => { if (!this.sel.includes(i)) this.sel.push(i); }); }
                        else { this.sel = this.sel.filter(i => !this.pageIds.includes(i)); }
                    }
                }
            }
            </script>
            <?php endif; ?>

            <!-- ============ PANEL ============ -->
            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden"<?php echo $VIEW === 'people' ? ' style="display:none"' : ''; ?>>

                <div class="p-5 md:p-6 border-b border-slate-100 flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-extrabold text-slate-800">
                            <?php echo htmlspecialchars($ROLES[$TAB][0] . ' — ' . $MODULES[$MOD][0] . ' Tasks'); ?>
                        </h3>
                        <p class="text-xs text-slate-400 mt-0.5">
                            Manage <?php echo strtolower($MODULES[$MOD][0]); ?> work for <?php echo strtolower($ROLES[$TAB][0]); ?>s
                            <?php if (!$IS_BOSS): ?><span class="text-indigo-500 font-semibold">· showing only your own tasks</span><?php endif; ?>
                        </p>
                    </div>
                    <?php if ($IS_BOSS): ?>
                    <button @click="openCreate()" 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-plus"></i> Create Task
                    </button>
                    <?php endif; ?>
                </div>

                <!-- ============ STAT CARDS ============ -->
                <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3 p-5 md:p-6 pb-2">
                    <?php
                    $cards = [
                        ['Total Tasks', $stats['total'],       'fa-clipboard-list', 'indigo',  'All ' . strtolower($MODULES[$MOD][0]) . ' tasks', ''],
                        ['Pending',     $stats['pending'],     'fa-clock',          'amber',   'Not started yet',   'pending'],
                        ['In Progress', $stats['in_progress'], 'fa-spinner',        'sky',     'Being worked on',   'in_progress'],
                        ['Completed',   $stats['completed'],   'fa-circle-check',   'emerald', 'Finished',          'completed'],
                        ['Rejected',    $stats['rejected'],    'fa-circle-xmark',   'rose',    'Turned down',       'rejected'],
                        ['Follow-up',   $stats['followup'],    'fa-phone-volume',   'violet',  'Need a call back',  'followup'],
                    ];
                    foreach ($cards as $c):
                        $href = $c[5] === '' ? at_qs(['status' => '', 'p' => 1]) : at_qs(['status' => $c[5], 'p' => 1]);
                        $active = ($f_status === $c[5]);
                    ?>
                    <a href="<?php echo htmlspecialchars($href); ?>"
                       class="rounded-2xl border p-4 transition-all hover:shadow-md <?php echo $active ? 'border-' . $c[3] . '-300 bg-' . $c[3] . '-50/60 ring-2 ring-' . $c[3] . '-100' : 'border-slate-200 bg-white'; ?>">
                        <div class="flex items-start gap-3">
                            <div class="w-10 h-10 rounded-xl bg-<?php echo $c[3]; ?>-100 text-<?php echo $c[3]; ?>-600 flex items-center justify-center text-sm flex-shrink-0">
                                <i class="fas <?php echo $c[2]; ?>"></i>
                            </div>
                            <div class="min-w-0">
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wide truncate"><?php echo $c[0]; ?></p>
                                <p class="text-2xl font-black text-slate-800 leading-tight"><?php echo (int)$c[1]; ?></p>
                                <p class="text-[10px] text-slate-400 truncate"><?php echo $c[4]; ?></p>
                            </div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>

                <?php if ($stats['overdue'] > 0): ?>
                <div class="mx-5 md:mx-6 mb-2">
                    <a href="<?php echo htmlspecialchars(at_qs(['range' => 'overdue', 'p' => 1])); ?>" class="flex items-center gap-2 text-xs font-bold text-rose-600 bg-rose-50 border border-rose-200 rounded-xl px-4 py-2.5 hover:bg-rose-100">
                        <i class="fas fa-triangle-exclamation"></i>
                        <?php echo $stats['overdue']; ?> task<?php echo $stats['overdue'] > 1 ? 's have' : ' has'; ?> passed the due date — click to see them
                    </a>
                </div>
                <?php endif; ?>

                <!-- ============ FILTERS ============ -->
                <form method="GET" class="px-5 md:px-6 py-4 border-y border-slate-100 bg-slate-50/60">
                    <input type="hidden" name="role" value="<?php echo htmlspecialchars($TAB); ?>">
                    <input type="hidden" name="mod"  value="<?php echo htmlspecialchars($MOD); ?>">
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-3 items-end">
                        <div class="lg:col-span-2">
                            <label class="lbl">Search</label>
                            <div class="relative">
                                <input type="text" name="q" value="<?php echo htmlspecialchars($f_q); ?>" placeholder="Task ID, name, mobile, task type…" class="fld pr-9">
                                <i class="fas fa-search absolute right-3 top-1/2 -translate-y-1/2 text-slate-300 text-xs"></i>
                            </div>
                        </div>
                        <div>
                            <label class="lbl">Assigned To</label>
                            <select name="assign" class="fld">
                                <option value="">All</option>
                                <option value="me"   <?php echo $f_assign === 'me'   ? 'selected' : ''; ?>>Assigned to me</option>
                                <option value="none" <?php echo $f_assign === 'none' ? 'selected' : ''; ?>>Not assigned yet</option>
                                <?php foreach ($assignables as $s): ?>
                                <option value="<?php echo (int)$s['id']; ?>" <?php echo $f_assign === (string)$s['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($s['name'] . ' · ' . $s['role_label']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="lbl">Priority</label>
                            <select name="prio" class="fld">
                                <option value="">All Priority</option>
                                <?php foreach ($PRIOS as $pk => $pv): ?>
                                <option value="<?php echo $pk; ?>" <?php echo $f_prio === $pk ? 'selected' : ''; ?>><?php echo $pv[0]; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="lbl">Status</label>
                            <select name="status" class="fld">
                                <option value="">All Status</option>
                                <?php foreach ($STATUSES as $sk => $sv): ?>
                                <option value="<?php echo $sk; ?>" <?php echo $f_status === $sk ? 'selected' : ''; ?>><?php echo $sv[0]; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="lbl">Date Range</label>
                            <select name="range" class="fld" x-model="range">
                                <option value=""        <?php echo $f_range === ''        ? 'selected' : ''; ?>>Any time</option>
                                <option value="today"   <?php echo $f_range === 'today'   ? 'selected' : ''; ?>>Today</option>
                                <option value="7"       <?php echo $f_range === '7'       ? 'selected' : ''; ?>>Last 7 days</option>
                                <option value="30"      <?php echo $f_range === '30'      ? 'selected' : ''; ?>>Last 30 days</option>
                                <option value="overdue" <?php echo $f_range === 'overdue' ? 'selected' : ''; ?>>Overdue only</option>
                                <option value="custom"  <?php echo $f_range === 'custom'  ? 'selected' : ''; ?>>Custom…</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-4 gap-3 items-end mt-3" x-show="range === 'custom'">
                        <div><label class="lbl">From</label><input type="date" name="from" value="<?php echo htmlspecialchars($f_from); ?>" class="fld"></div>
                        <div><label class="lbl">To</label><input type="date" name="to" value="<?php echo htmlspecialchars($f_to); ?>" class="fld"></div>
                    </div>

                    <div class="flex flex-wrap gap-2 mt-3">
                        <button type="submit" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold hover:bg-indigo-700"><i class="fas fa-filter"></i> Filter</button>
                        <a href="<?php echo htmlspecialchars('activity_task.php?role=' . $TAB . '&mod=' . $MOD); ?>" class="inline-flex items-center gap-2 px-5 py-2.5 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> Reset</a>
                    </div>
                </form>

                <!-- ============ TABLE ============ -->
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse text-xs">
                        <thead>
                            <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider border-b border-slate-200">
                                <th class="p-4 font-semibold">Task ID</th>
                                <th class="p-4 font-semibold">About</th>
                                <th class="p-4 font-semibold">Task Details</th>
                                <th class="p-4 font-semibold">Assigned To</th>
                                <th class="p-4 font-semibold">Priority</th>
                                <th class="p-4 font-semibold">Due Date</th>
                                <th class="p-4 font-semibold">Status</th>
                                <th class="p-4 font-semibold">Created On</th>
                                <th class="p-4 font-semibold text-center">Action</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                        <?php if (!empty($tasks)): foreach ($tasks as $t):
                            $sm  = tasks_status_meta($t['status']);
                            $pm  = tasks_priority_meta($t['priority']);
                            $due = tasks_due_note($t['due_date']);
                            $mine = ((int)$t['assigned_to'] === $ME['id']);
                        ?>
                            <tr class="hover:bg-slate-50/70 transition align-top <?php echo $mine ? 'bg-indigo-50/30' : ''; ?>">

                                <td class="p-4 whitespace-nowrap">
                                    <button @click="openView(<?php echo (int)$t['id']; ?>)" class="font-bold text-indigo-600 hover:text-indigo-800 hover:underline">
                                        <?php echo htmlspecialchars($t['task_code'] ?: ('#' . $t['id'])); ?>
                                    </button>
                                    <?php if ((int)$t['reassign_count'] > 0): ?>
                                    <p class="text-[10px] text-orange-500 font-bold mt-1"><i class="fas fa-people-arrows"></i> <?php echo (int)$t['reassign_count']; ?>x handed over</p>
                                    <?php endif; ?>
                                </td>

                                <td class="p-4">
                                    <?php if ($t['target_name']): ?>
                                        <div class="flex items-start gap-2">
                                            <div class="w-7 h-7 rounded-full bg-slate-200 text-slate-500 flex items-center justify-center text-[10px] font-black flex-shrink-0">
                                                <?php echo strtoupper(substr($t['target_name'], 0, 1)); ?>
                                            </div>
                                            <div class="min-w-0">
                                                <p class="font-bold text-slate-800 truncate max-w-[150px]"><?php echo htmlspecialchars($t['target_name']); ?></p>
                                                <p class="text-slate-400 text-[11px]">
                                                    <?php if ($t['target_user_id']): ?>USR<?php echo (int)$t['target_user_id']; ?><?php endif; ?>
                                                    <?php if ($t['target_mobile']): ?> · <?php echo htmlspecialchars($t['target_mobile']); ?><?php endif; ?>
                                                </p>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-slate-300">—</span>
                                    <?php endif; ?>
                                    <?php if ($t['target_ref_type']): ?>
                                    <p class="text-[10px] text-slate-400 mt-1"><?php echo htmlspecialchars(ucfirst($t['target_ref_type'])); ?> #<?php echo (int)$t['target_ref_id']; ?></p>
                                    <?php endif; ?>
                                </td>

                                <td class="p-4">
                                    <p class="font-bold text-slate-800 max-w-[220px]"><?php echo htmlspecialchars($t['title']); ?></p>
                                    <p class="text-slate-400 text-[11px] max-w-[220px] truncate"><?php echo htmlspecialchars($t['category_label'] ?: $t['category_key']); ?></p>
                                    <?php if ((int)$t['progress'] > 0 && $t['status'] !== 'completed'): ?>
                                    <div class="w-24 h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden">
                                        <div class="h-full rounded-full bg-sky-500" style="width: <?php echo (int)$t['progress']; ?>%"></div>
                                    </div>
                                    <?php endif; ?>
                                </td>

                                <td class="p-4">
                                    <?php if ($t['assigned_name']): ?>
                                        <div class="flex items-start gap-2">
                                            <div class="w-7 h-7 rounded-full bg-gradient-to-br from-indigo-400 to-violet-500 text-white flex items-center justify-center text-[10px] font-black flex-shrink-0">
                                                <?php echo strtoupper(substr($t['assigned_name'], 0, 1)); ?>
                                            </div>
                                            <div class="min-w-0">
                                                <p class="font-bold text-slate-700 truncate max-w-[130px]"><?php echo htmlspecialchars($t['assigned_name']); ?></p>
                                                <p class="text-slate-400 text-[10px] uppercase"><?php echo htmlspecialchars($t['assigned_role'] === 'superadmin' ? 'Super Admin' : ucfirst((string)$t['assigned_role'])); ?></p>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <span class="inline-flex items-center gap-1 text-[10px] font-bold text-amber-600 bg-amber-50 ring-1 ring-amber-200 px-2 py-1 rounded-lg"><i class="fas fa-user-slash"></i> Not assigned</span>
                                    <?php endif; ?>
                                </td>

                                <td class="p-4 whitespace-nowrap">
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[10px] font-bold ring-1 <?php echo $pm[1]; ?>">
                                        <span class="w-1.5 h-1.5 rounded-full <?php echo $pm[2]; ?>"></span><?php echo $pm[0]; ?>
                                    </span>
                                </td>

                                <td class="p-4 whitespace-nowrap">
                                    <?php if ($t['due_date']): ?>
                                        <p class="font-semibold text-slate-700"><?php echo date('d M Y', strtotime($t['due_date'])); ?></p>
                                        <p class="text-[11px] <?php echo $due[1]; ?>"><?php echo date('h:i A', strtotime($t['due_date'])); ?> · <?php echo $due[0]; ?></p>
                                    <?php else: ?>
                                        <span class="text-slate-300">No deadline</span>
                                    <?php endif; ?>
                                </td>

                                <td class="p-4 whitespace-nowrap">
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[10px] font-bold ring-1 <?php echo $sm[2]; ?>">
                                        <i class="fas <?php echo $sm[1]; ?>"></i><?php echo $sm[0]; ?>
                                    </span>
                                </td>

                                <td class="p-4 whitespace-nowrap">
                                    <p class="text-slate-600"><?php echo date('d M Y', strtotime($t['created_at'])); ?></p>
                                    <p class="text-[11px] text-slate-400"><?php echo date('h:i A', strtotime($t['created_at'])); ?></p>
                                    <?php if ($t['created_by_name']): ?>
                                    <p class="text-[10px] text-slate-400 truncate max-w-[110px]">by <?php echo htmlspecialchars($t['created_by_name']); ?></p>
                                    <?php endif; ?>
                                </td>

                                <td class="p-4">
                                    <div class="flex items-center justify-center gap-1.5">
                                        <?php
                                            $ph = at_phone($t);
                                            /* a line that says who is calling and about what, so the person
                                               on the other end knows straight away */
                                            $waText = rawurlencode(
                                                ($t['target_name'] ? 'Hello ' . $t['target_name'] . ', ' : 'Hello, ')
                                                . 'this is ' . $company_name . ' regarding '
                                                . ($t['category_label'] ?: $t['title'])
                                                . ' (Ref: ' . $t['task_code'] . ').'
                                            );
                                        ?>
                                        <?php if ($ph['call'] !== ''): ?>
                                        <a href="tel:+91<?php echo htmlspecialchars($ph['call']); ?>" title="Call +91 <?php echo htmlspecialchars($ph['call']); ?>"
                                           class="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 hover:bg-emerald-100 transition flex items-center justify-center"><i class="fas fa-phone text-xs"></i></a>
                                        <?php else: ?>
                                        <span title="No mobile number on this task"
                                              class="w-8 h-8 rounded-lg bg-slate-50 text-slate-300 cursor-not-allowed flex items-center justify-center"><i class="fas fa-phone-slash text-xs"></i></span>
                                        <?php endif; ?>

                                        <?php if ($ph['wa'] !== ''): ?>
                                        <a href="https://wa.me/91<?php echo htmlspecialchars($ph['wa']); ?>?text=<?php echo $waText; ?>" target="_blank" rel="noopener"
                                           title="WhatsApp +91 <?php echo htmlspecialchars($ph['wa']); ?>"
                                           class="w-8 h-8 rounded-lg bg-green-50 text-green-600 hover:bg-green-100 transition flex items-center justify-center"><i class="fab fa-whatsapp text-sm"></i></a>
                                        <?php else: ?>
                                        <span title="No mobile number on this task"
                                              class="w-8 h-8 rounded-lg bg-slate-50 text-slate-300 cursor-not-allowed flex items-center justify-center"><i class="fab fa-whatsapp text-sm"></i></span>
                                        <?php endif; ?>

                                        <button @click="openView(<?php echo (int)$t['id']; ?>)" title="Open task &amp; history"
                                                class="w-8 h-8 rounded-lg bg-slate-100 text-slate-500 hover:bg-indigo-100 hover:text-indigo-600 transition"><i class="fas fa-eye text-xs"></i></button>
                                        <?php if (tasks_can_touch($db, $t)): ?>
                                        <button @click="openUpdate(<?php echo (int)$t['id']; ?>)" title="Update this task"
                                                class="w-8 h-8 rounded-lg bg-sky-50 text-sky-600 hover:bg-sky-100 transition"><i class="fas fa-pen text-xs"></i></button>
                                        <button @click="openHandover(<?php echo (int)$t['id']; ?>)" title="Hand over to someone else"
                                                class="w-8 h-8 rounded-lg bg-orange-50 text-orange-600 hover:bg-orange-100 transition"><i class="fas fa-people-arrows text-xs"></i></button>
                                        <?php endif; ?>
                                        <?php if ($IS_BOSS): ?>
                                        <button @click="askDelete(<?php echo (int)$t['id']; ?>, '<?php echo htmlspecialchars(addslashes($t['task_code']), ENT_QUOTES); ?>')" title="Delete"
                                                class="w-8 h-8 rounded-lg bg-rose-50 text-rose-600 hover:bg-rose-100 transition"><i class="fas fa-trash text-xs"></i></button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; else: ?>
                            <tr><td colspan="9" class="p-16 text-center">
                                <div class="w-16 h-16 rounded-2xl bg-slate-100 text-slate-300 flex items-center justify-center text-2xl mx-auto mb-4"><i class="fas fa-clipboard-list"></i></div>
                                <p class="font-bold text-slate-600 text-sm">No tasks here yet</p>
                                <p class="text-slate-400 text-xs mt-1 max-w-sm mx-auto">
                                    <?php echo $IS_BOSS
                                        ? 'Use Create Task to hand the first piece of ' . strtolower($MODULES[$MOD][0]) . ' work to your team.'
                                        : 'Nothing has been assigned to you in this section.'; ?>
                                </p>
                            </td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- ============ PAGINATION ============ -->
                <div class="px-5 md:px-6 py-4 border-t border-slate-100 flex flex-wrap items-center justify-between gap-3">
                    <p class="text-xs text-slate-500">
                        <?php if ($total > 0): ?>
                            Showing <b><?php echo $offset + 1; ?></b> to <b><?php echo min($offset + $per, $total); ?></b> of <b><?php echo $total; ?></b> tasks
                        <?php else: ?>No entries<?php endif; ?>
                    </p>
                    <?php if ($pages > 1): ?>
                    <div class="flex items-center gap-1">
                        <a href="<?php echo htmlspecialchars(at_qs(['p' => max(1, $page - 1)])); ?>" class="w-8 h-8 rounded-lg bg-white ring-1 ring-slate-200 text-slate-500 flex items-center justify-center hover:bg-slate-50 text-xs"><i class="fas fa-chevron-left"></i></a>
                        <?php
                        $from = max(1, $page - 2); $to = min($pages, $from + 4); $from = max(1, $to - 4);
                        for ($i = $from; $i <= $to; $i++): ?>
                        <a href="<?php echo htmlspecialchars(at_qs(['p' => $i])); ?>"
                           class="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold <?php echo $i === $page ? 'bg-indigo-600 text-white' : 'bg-white ring-1 ring-slate-200 text-slate-500 hover:bg-slate-50'; ?>"><?php echo $i; ?></a>
                        <?php endfor; ?>
                        <a href="<?php echo htmlspecialchars(at_qs(['p' => min($pages, $page + 1)])); ?>" class="w-8 h-8 rounded-lg bg-white ring-1 ring-slate-200 text-slate-500 flex items-center justify-center hover:bg-slate-50 text-xs"><i class="fas fa-chevron-right"></i></a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<?php if ($IS_BOSS): ?>
<!-- ================= CREATE TASK ================= -->
<div x-show="create" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="create = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[92vh] overflow-y-auto">
        <form method="POST">
            <input type="hidden" name="create_task" value="1">
            <input type="hidden" name="scope_role" :value="c.scope_role">

            <div class="px-6 py-5 border-b border-slate-100 flex items-center justify-between sticky top-0 bg-white z-10">
                <div>
                    <h3 class="text-lg font-extrabold text-slate-800">Create Task</h3>
                    <p class="text-xs text-slate-400">Pick the area, describe the work, and hand it to someone</p>
                </div>
                <button type="button" @click="create = false" class="w-9 h-9 rounded-xl bg-slate-100 text-slate-500 hover:bg-slate-200"><i class="fas fa-xmark"></i></button>
            </div>

            <div class="p-6 space-y-4">

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div>
                        <label class="lbl">This task is about</label>
                        <select name="scope_role" x-model="c.scope_role" class="fld">
                            <?php foreach ($ROLES as $rk => $rv): ?>
                            <option value="<?php echo $rk; ?>"><?php echo $rv[0]; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Module</label>
                        <select name="module_key" x-model="c.module_key" @change="c.category_key = firstCat(c.module_key)" class="fld">
                            <?php foreach ($MODULES as $mk => $mv): ?>
                            <option value="<?php echo $mk; ?>"><?php echo $mv[0]; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Task type</label>
                        <select name="category_key" x-model="c.category_key" class="fld">
                            <template x-for="(lbl, key) in (CATS[c.module_key] || {})" :key="key">
                                <option :value="key" x-text="lbl"></option>
                            </template>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="lbl">Task title <span class="text-slate-400 font-normal">— leave blank to use the task type</span></label>
                    <input type="text" name="title" x-model="c.title" class="fld" :placeholder="(CATS[c.module_key] || {})[c.category_key] || 'Task title'">
                </div>

                <div>
                    <label class="lbl">What needs to be done</label>
                    <textarea name="description" rows="3" class="fld" placeholder="Write the instruction clearly so the person picking it up knows exactly what to do."></textarea>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50/70 p-4">
                    <p class="text-[11px] font-black text-slate-500 uppercase tracking-wide mb-3">Who is this task about? <span class="font-normal normal-case text-slate-400">(optional)</span></p>
                    <div class="grid grid-cols-1 sm:grid-cols-4 gap-3">
                        <div><label class="lbl">Name</label><input type="text" name="target_name" class="fld" placeholder="Rahul Das"></div>
                        <div><label class="lbl">Mobile</label><input type="text" name="target_mobile" class="fld" placeholder="9876543210"></div>
                        <div><label class="lbl">User ID</label><input type="number" name="target_user_id" class="fld" placeholder="1025"></div>
                        <div class="grid grid-cols-2 gap-2">
                            <div>
                                <label class="lbl">Ref type</label>
                                <select name="target_ref_type" class="fld">
                                    <option value="">—</option>
                                    <option value="lead">Lead</option>
                                    <option value="order">Order</option>
                                    <option value="service">Product</option>
                                    <option value="ticket">Ticket</option>
                                    <option value="seller">Seller</option>
                                    <option value="plan">Plan</option>
                                </select>
                            </div>
                            <div><label class="lbl">Ref ID</label><input type="number" name="target_ref_id" class="fld" placeholder="0"></div>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-4 gap-4">
                    <div class="sm:col-span-2">
                        <label class="lbl">Assign to</label>
                        <select name="assigned_to" class="fld">
                            <option value="0">Leave unassigned for now</option>
                            <?php foreach ($STAFF as $s): ?>
                            <option value="<?php echo (int)$s['id']; ?>"><?php echo htmlspecialchars($s['name'] . ' — ' . $s['role_label']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Priority</label>
                        <select name="priority" class="fld">
                            <?php foreach ($PRIOS as $pk => $pv): ?>
                            <option value="<?php echo $pk; ?>" <?php echo $pk === 'medium' ? 'selected' : ''; ?>><?php echo $pv[0]; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Due date &amp; time</label>
                        <input type="datetime-local" name="due_date" class="fld">
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div><label class="lbl">Next follow-up date</label><input type="date" name="next_follow_up" class="fld"></div>
                    <div><label class="lbl">Internal remark</label><input type="text" name="remark" class="fld" placeholder="Anything the team should know"></div>
                </div>
            </div>

            <div class="px-6 py-4 border-t border-slate-100 flex justify-end gap-2 sticky bottom-0 bg-white">
                <button type="button" @click="create = false" class="px-5 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50">Cancel</button>
                <button type="submit" class="px-6 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-plus mr-1"></i> Create Task</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- ================= VIEW TASK + FULL HISTORY ================= -->
<div x-show="view" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="view = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[92vh] overflow-y-auto">

        <div class="px-6 py-5 border-b border-slate-100 flex items-start justify-between sticky top-0 bg-white z-10">
            <div class="min-w-0">
                <div class="flex items-center gap-2 flex-wrap">
                    <h3 class="text-lg font-extrabold text-slate-800" x-text="t.task_code || 'Task'"></h3>
                    <span class="text-[10px] font-black px-2 py-1 rounded-lg bg-slate-100 text-slate-500 uppercase" x-text="t.module_label"></span>
                </div>
                <p class="text-xs text-slate-400 mt-0.5" x-text="t.title"></p>
            </div>
            <button type="button" @click="view = false" class="w-9 h-9 rounded-xl bg-slate-100 text-slate-500 hover:bg-slate-200 flex-shrink-0"><i class="fas fa-xmark"></i></button>
        </div>

        <div class="p-6 grid grid-cols-1 lg:grid-cols-5 gap-6">

            <!-- left: the task itself -->
            <div class="lg:col-span-2 space-y-4">
                <div class="rounded-2xl border border-slate-200 p-4 space-y-3">
                    <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Task</p>
                    <div><p class="text-[10px] text-slate-400 font-bold uppercase">Type</p><p class="text-sm font-bold text-slate-700" x-text="t.category_label"></p></div>
                    <div x-show="t.description"><p class="text-[10px] text-slate-400 font-bold uppercase">Instruction</p><p class="text-xs text-slate-600 whitespace-pre-line leading-relaxed" x-text="t.description"></p></div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><p class="text-[10px] text-slate-400 font-bold uppercase">Status</p><p class="text-sm font-bold text-slate-700" x-text="t.status_label"></p></div>
                        <div><p class="text-[10px] text-slate-400 font-bold uppercase">Priority</p><p class="text-sm font-bold text-slate-700" x-text="t.priority_label"></p></div>
                        <div><p class="text-[10px] text-slate-400 font-bold uppercase">Progress</p><p class="text-sm font-bold text-slate-700"><span x-text="t.progress || 0"></span>%</p></div>
                        <div><p class="text-[10px] text-slate-400 font-bold uppercase">Hand-overs</p><p class="text-sm font-bold text-slate-700" x-text="t.reassign_count || 0"></p></div>
                    </div>
                </div>

                <div class="rounded-2xl border border-slate-200 p-4 space-y-3">
                    <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider">People &amp; dates</p>
                    <div><p class="text-[10px] text-slate-400 font-bold uppercase">Assigned to</p><p class="text-sm font-bold text-slate-700" x-text="t.assigned_name || 'Not assigned yet'"></p></div>
                    <div><p class="text-[10px] text-slate-400 font-bold uppercase">Raised by</p><p class="text-sm font-bold text-slate-700" x-text="t.created_by_name || '—'"></p></div>
                    <div x-show="t.target_name"><p class="text-[10px] text-slate-400 font-bold uppercase">About</p>
                        <p class="text-sm font-bold text-slate-700"><span x-text="t.target_name"></span> <span class="text-slate-400 font-normal text-xs" x-text="t.target_mobile ? '· ' + t.target_mobile : ''"></span></p></div>
                    <div><p class="text-[10px] text-slate-400 font-bold uppercase">Due</p><p class="text-sm font-bold text-slate-700" x-text="t.due_date || 'No deadline'"></p></div>
                    <div><p class="text-[10px] text-slate-400 font-bold uppercase">Created</p><p class="text-sm font-bold text-slate-700" x-text="t.created_at"></p></div>
                    <div x-show="t.remark"><p class="text-[10px] text-slate-400 font-bold uppercase">Remark</p><p class="text-xs text-slate-600 whitespace-pre-line" x-text="t.remark"></p></div>
                    <div x-show="t.reject_reason"><p class="text-[10px] text-rose-400 font-bold uppercase">Reject reason</p><p class="text-xs text-rose-600 whitespace-pre-line" x-text="t.reject_reason"></p></div>
                </div>

                <div class="flex flex-wrap gap-2" x-show="t.can_edit == 1">
                    <button @click="view = false; openUpdate(t.id)" class="flex-1 px-4 py-2.5 rounded-xl bg-sky-600 text-white text-xs font-bold hover:bg-sky-700"><i class="fas fa-pen mr-1"></i> Update</button>
                    <button @click="view = false; openHandover(t.id)" class="flex-1 px-4 py-2.5 rounded-xl bg-orange-500 text-white text-xs font-bold hover:bg-orange-600"><i class="fas fa-people-arrows mr-1"></i> Hand over</button>
                </div>

                <form method="POST" class="rounded-2xl border border-slate-200 p-4" x-show="t.can_edit == 1">
                    <input type="hidden" name="add_task_note" value="1">
                    <input type="hidden" name="task_id" :value="t.id">
                    <label class="lbl">Add a note to this task</label>
                    <textarea name="note" rows="2" class="fld" placeholder="What happened just now…" required></textarea>
                    <button type="submit" class="mt-2 w-full px-4 py-2.5 rounded-xl bg-slate-800 text-white text-xs font-bold hover:bg-slate-900"><i class="fas fa-paper-plane mr-1"></i> Save note</button>
                </form>
            </div>

            <!-- right: the log -->
            <div class="lg:col-span-3">
                <div class="flex items-center justify-between mb-4">
                    <p class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Task history</p>
                    <span class="text-[10px] font-bold text-slate-400"><span x-text="logs.length"></span> entries</span>
                </div>

                <div x-show="loading" class="py-16 text-center text-slate-400 text-xs"><i class="fas fa-circle-notch fa-spin text-xl mb-2 block"></i> Loading history…</div>

                <div class="space-y-0" x-show="!loading">
                    <template x-for="l in logs" :key="l.id">
                        <div class="tl relative pl-11 pb-5">
                            <div class="absolute left-0 top-0 w-8 h-8 rounded-xl flex items-center justify-center text-xs" :class="l.action_class">
                                <i class="fas" :class="l.action_icon"></i>
                            </div>
                            <div class="bg-slate-50 rounded-xl border border-slate-200 px-4 py-3">
                                <div class="flex items-start justify-between gap-3 flex-wrap">
                                    <p class="text-xs font-bold text-slate-700" x-text="l.action_label"></p>
                                    <p class="text-[10px] text-slate-400" x-text="l.when"></p>
                                </div>
                                <p class="text-[11px] text-slate-600 mt-1" x-show="l.field_label">
                                    <span class="font-semibold" x-text="l.field_label"></span>
                                    <template x-if="l.old_value"><span> · <span class="line-through text-slate-400" x-text="l.old_value"></span></span></template>
                                    <template x-if="l.new_value"><span> → <span class="font-bold text-slate-800" x-text="l.new_value"></span></span></template>
                                </p>
                                <p class="text-[11px] text-slate-600 mt-1 whitespace-pre-line" x-show="l.remark" x-text="l.remark"></p>
                                <p class="text-[10px] text-slate-400 mt-2">
                                    <i class="fas fa-user mr-1"></i><span x-text="l.done_by_name || 'System'"></span>
                                    <span x-show="l.done_by_role"> · <span class="uppercase" x-text="l.done_by_role"></span></span>
                                    <span x-show="l.ip_address"> · <span x-text="l.ip_address"></span></span>
                                </p>
                            </div>
                        </div>
                    </template>
                    <p x-show="!logs.length" class="text-center text-xs text-slate-400 py-12">Nothing has happened on this task yet.</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ================= UPDATE TASK ================= -->
<div x-show="update" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="update = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[92vh] overflow-y-auto">
        <form method="POST">
            <input type="hidden" name="update_task" value="1">
            <input type="hidden" name="task_id" :value="t.id">

            <div class="px-6 py-5 border-b border-slate-100">
                <h3 class="text-lg font-extrabold text-slate-800">Update task</h3>
                <p class="text-xs text-slate-400"><span x-text="t.task_code"></span> · <span x-text="t.title"></span></p>
            </div>

            <div class="p-6 space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="lbl">Status</label>
                        <select name="status" x-model="u.status" class="fld">
                            <?php foreach ($STATUSES as $sk => $sv): ?>
                            <option value="<?php echo $sk; ?>"><?php echo $sv[0]; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Priority</label>
                        <select name="priority" x-model="u.priority" class="fld">
                            <?php foreach ($PRIOS as $pk => $pv): ?>
                            <option value="<?php echo $pk; ?>"><?php echo $pv[0]; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="lbl">Progress — <span x-text="u.progress"></span>%</label>
                    <input type="range" name="progress" min="0" max="100" step="5" x-model="u.progress" class="w-full accent-indigo-600">
                </div>

                <?php if ($IS_BOSS): ?>
                <div>
                    <label class="lbl">Due date &amp; time</label>
                    <input type="datetime-local" name="due_date" x-model="u.due_date" class="fld">
                </div>
                <?php endif; ?>

                <div>
                    <label class="lbl">Next follow-up date</label>
                    <input type="date" name="next_follow_up" x-model="u.next_follow_up" class="fld">
                </div>

                <div>
                    <label class="lbl">Work note / remark</label>
                    <textarea name="remark" rows="3" class="fld" placeholder="What did you do, and what is left?"></textarea>
                </div>

                <div x-show="u.status === 'rejected'">
                    <label class="lbl text-rose-600">Why is this being rejected?</label>
                    <textarea name="reject_reason" rows="2" class="fld" placeholder="Give a clear reason — it is saved in the task log."></textarea>
                </div>

                <p class="text-[11px] text-slate-400 bg-slate-50 border border-slate-200 rounded-xl p-3">
                    <i class="fas fa-circle-info mr-1"></i>Every change here is written to the task history with your name, the time and your IP.
                </p>
            </div>

            <div class="px-6 py-4 border-t border-slate-100 flex justify-end gap-2">
                <button type="button" @click="update = false" class="px-5 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50">Cancel</button>
                <button type="submit" class="px-6 py-2.5 rounded-xl bg-sky-600 text-white text-xs font-bold hover:bg-sky-700"><i class="fas fa-check mr-1"></i> Save update</button>
            </div>
        </form>
    </div>
</div>

<!-- ================= HAND OVER ================= -->
<div x-show="handover" x-cloak class="fixed inset-0 z-[70] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="handover = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        <form method="POST">
            <input type="hidden" name="reassign_task" value="1">
            <input type="hidden" name="task_id" :value="t.id">

            <div class="px-6 py-5 border-b border-slate-100">
                <h3 class="text-lg font-extrabold text-slate-800">Hand this task over</h3>
                <p class="text-xs text-slate-400">Stuck, or not the right person? Pass it on — the reason stays in the log.</p>
            </div>

            <div class="p-6 space-y-4">
                <div class="rounded-xl bg-slate-50 border border-slate-200 px-4 py-3">
                    <p class="text-[10px] text-slate-400 font-bold uppercase">Task</p>
                    <p class="text-sm font-bold text-slate-700"><span x-text="t.task_code"></span> — <span x-text="t.title"></span></p>
                    <p class="text-[11px] text-slate-500 mt-1">Currently with <b x-text="t.assigned_name || 'nobody'"></b></p>
                </div>

                <div>
                    <label class="lbl">Hand over to</label>
                    <select name="assign_to" class="fld" required>
                        <option value="">Choose a colleague…</option>
                        <?php foreach ($STAFF as $s): ?>
                        <option value="<?php echo (int)$s['id']; ?>"><?php echo htmlspecialchars($s['name'] . ' — ' . $s['role_label']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="lbl">Why are you handing it over? <span class="text-rose-500">*</span></label>
                    <textarea name="handover_reason" rows="3" class="fld" required placeholder="e.g. Customer speaks Hindi only — passing to Sanjay. Or: this needs bank verification access I do not have."></textarea>
                </div>

                <p class="text-[11px] text-amber-700 bg-amber-50 border border-amber-200 rounded-xl p-3">
                    <i class="fas fa-triangle-exclamation mr-1"></i>The task moves out of your list and back to <b>Pending</b> for the new person. Both names stay in the history.
                </p>
            </div>

            <div class="px-6 py-4 border-t border-slate-100 flex justify-end gap-2">
                <button type="button" @click="handover = false" class="px-5 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50">Cancel</button>
                <button type="submit" class="px-6 py-2.5 rounded-xl bg-orange-500 text-white text-xs font-bold hover:bg-orange-600"><i class="fas fa-people-arrows mr-1"></i> Hand over</button>
            </div>
        </form>
    </div>
</div>

<?php if ($IS_BOSS): ?>
<!-- ================= DELETE ================= -->
<div x-show="del" x-cloak class="fixed inset-0 z-[80] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm" @click.self="del = false">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm p-6 text-center">
        <div class="w-14 h-14 rounded-2xl bg-rose-50 text-rose-500 flex items-center justify-center text-xl mx-auto mb-4"><i class="fas fa-trash"></i></div>
        <h3 class="text-base font-extrabold text-slate-800 mb-1">Delete this task?</h3>
        <p class="text-xs text-slate-500 mb-5">Task <b x-text="delCode"></b> and its whole history will be removed. This cannot be undone.</p>
        <form method="POST" class="flex gap-2">
            <input type="hidden" name="delete_task" value="1">
            <input type="hidden" name="task_id" :value="delId">
            <button type="button" @click="del = false" class="flex-1 px-4 py-2.5 rounded-xl bg-white ring-1 ring-slate-200 text-xs font-bold text-slate-600">Keep it</button>
            <button type="submit" class="flex-1 px-4 py-2.5 rounded-xl bg-rose-600 text-white text-xs font-bold hover:bg-rose-700">Delete</button>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
function taskBoard() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        range: '<?php echo htmlspecialchars($f_range, ENT_QUOTES); ?>',

        CATS: <?php echo json_encode($CATS, JSON_UNESCAPED_UNICODE); ?>,

        create: false, view: false, update: false, handover: false, del: false,
        loading: false,
        t: {}, logs: [],
        u: { status: 'pending', priority: 'medium', progress: 0, due_date: '', next_follow_up: '' },
        c: { scope_role: '<?php echo $TAB; ?>', module_key: '<?php echo $MOD; ?>', category_key: '', title: '' },
        delId: 0, delCode: '',

        init() { this.c.category_key = this.firstCat(this.c.module_key); },

        firstCat(mod) {
            const keys = Object.keys(this.CATS[mod] || {});
            return keys.length ? keys[0] : '';
        },

        openCreate() {
            this.c = { scope_role: '<?php echo $TAB; ?>', module_key: '<?php echo $MOD; ?>', category_key: '', title: '' };
            this.c.category_key = this.firstCat(this.c.module_key);
            this.create = true;
        },

        async load(id) {
            this.loading = true; this.logs = []; this.t = {};
            try {
                const r = await fetch('activity_task.php?ajax=1&id=' + id, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
                const j = await r.json();
                if (!j.ok) { alert(j.msg || 'Task not found.'); this.loading = false; return false; }
                this.t = j.task; this.logs = j.logs || [];
                this.loading = false;
                return true;
            } catch (e) {
                this.loading = false;
                alert('Could not load the task. Please refresh and try again.');
                return false;
            }
        },

        async openView(id) { this.view = true; await this.load(id); },

        async openUpdate(id) {
            const ok = await this.load(id);
            if (!ok) return;
            this.u = {
                status:   this.t.status   || 'pending',
                priority: this.t.priority || 'medium',
                progress: parseInt(this.t.progress || 0, 10),
                due_date: this.t.due_date ? String(this.t.due_date).replace(' ', 'T').substring(0, 16) : '',
                next_follow_up: this.t.next_follow_up || ''
            };
            this.update = true;
        },

        async openHandover(id) { const ok = await this.load(id); if (ok) this.handover = true; },

        askDelete(id, code) { this.delId = id; this.delCode = code; this.del = true; }
    };
}
</script>

</body>
</html>
