<?php
// ============================================================
//  admin/tasks.php — Tasks list
// ============================================================
//
//  Filters:
//    - tab=mine   (default) — assigned to me + unassigned ones I created
//    - tab=all    — every task in the system (super admins only)
//    - tab=created — tasks I created (any assignee)
//    - status=open|in_progress|done|cancelled  — filter by status
//    - q=text     — search title + description
//
//  Quick-action: tick a task done from the list (POST action=mark_done)
//  POST handling lives ABOVE _guard.php so header() redirects work.
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/mailer.php';
auth_require_admin();

$me       = auth_admin_user();
$is_super = ($me['role'] === 'super_admin');

// (No POST handlers on this page — all task actions live in task-edit.php.)

// ── Now safe to render — load chrome ────────────────────────
$page_title = 'Tasks';
require __DIR__ . '/_guard.php';

// ── Filters ─────────────────────────────────────────────────
$tab = $_GET['tab'] ?? 'mine';
$q   = trim((string)($_GET['q'] ?? ''));

// Non-super admins can only see "mine" or "created" or "done"
if (!$is_super && $tab === 'all') $tab = 'mine';

$where  = ['1=1'];
$params = [];

switch ($tab) {
case 'all':
        // System-wide (super admin only) — only open + in_progress
        $where[] = "t.status IN ('open','in_progress')";
        break;

    case 'created':
            $where[] = 't.created_by = :cb';
            $where[] = "t.status IN ('open','in_progress')";
            $params['cb'] = $me['id'];
            break;

        case 'done':
                $where[] = "t.status IN ('done','cancelled')";
                if (!$is_super) {
                    $where[] = '(t.assigned_to = :da OR t.created_by = :dc)';
                    $params['da'] = $me['id'];
                    $params['dc'] = $me['id'];
                }
                break;

            case 'mine':
                default:
                        $where[] = '(t.assigned_to = :me1 OR (t.assigned_to IS NULL AND t.created_by = :me2))';
                        $where[] = "t.status IN ('open','in_progress')";
                        $params['me1'] = $me['id'];
                        $params['me2'] = $me['id'];
                        break;
                    }

                    if ($q !== '') {
                        $where[] = '(t.title LIKE :q OR t.description LIKE :q)';
                        $params['q'] = '%' . $q . '%';
                    }

                    $sql = "
                    SELECT t.*,
                    c.first_name AS creator_first,  c.last_name AS creator_last,
                    a.first_name AS assignee_first, a.last_name AS assignee_last,
                    m.business_name AS member_business,
                    (SELECT COUNT(*) FROM admin_task_items WHERE task_id = t.id)                  AS cl_total,
                    (SELECT COUNT(*) FROM admin_task_items WHERE task_id = t.id AND checked = 1)  AS cl_done
                    FROM admin_tasks t
                    LEFT JOIN admin_users c ON c.id = t.created_by
                    LEFT JOIN admin_users a ON a.id = t.assigned_to
                    LEFT JOIN members     m ON m.id = t.member_id
                    WHERE " . implode(' AND ', $where) . "
                    ORDER BY
                    CASE t.status
                    WHEN 'in_progress' THEN 1
                    WHEN 'open'        THEN 2
                    WHEN 'done'        THEN 3
                    WHEN 'cancelled'   THEN 4
                    END,
                    FIELD(t.priority,'urgent','high','normal','low'),
                    (t.due_date IS NULL),
                    t.due_date ASC,
                    t.id DESC
                    LIMIT 500";

                    $tasks = db_all($sql, $params);

                    // ── Counts for tab badges ────────────────────────────────────
                    $mine_count = (int)db_value(
                        "SELECT COUNT(*) FROM admin_tasks
                        WHERE (assigned_to = :me1 OR (assigned_to IS NULL AND created_by = :me2))
                        AND status IN ('open','in_progress')",
                        ['me1' => $me['id'], 'me2' => $me['id']]
                    );
                    $created_count = (int)db_value(
                        "SELECT COUNT(*) FROM admin_tasks
                        WHERE created_by = :me AND status IN ('open','in_progress')",
                        ['me' => $me['id']]
                    );
                    $all_count = (int)db_value(
                        "SELECT COUNT(*) FROM admin_tasks WHERE status IN ('open','in_progress')"
                    );
                    $done_count = (int)db_value(
                        $is_super
                        ? "SELECT COUNT(*) FROM admin_tasks WHERE status IN ('done','cancelled')"
                        : "SELECT COUNT(*) FROM admin_tasks
                        WHERE status IN ('done','cancelled')
                        AND (assigned_to = :me1 OR created_by = :me2)",
                        $is_super ? [] : ['me1' => $me['id'], 'me2' => $me['id']]
                    );

                    function task_status_pill(string $s): string {
                        $map = [
                            'open'        => ['Open',        '#dbeafe', '#1e40af'],
                            'in_progress' => ['In progress', '#fef3c7', '#92400e'],
                            'done'        => ['Done',        '#dcfce7', '#166534'],
                            'cancelled'   => ['Cancelled',   '#e5e7eb', '#374151'],
                        ];
                        [$label, $bg, $fg] = $map[$s] ?? [ucfirst($s), '#e5e7eb', '#374151'];
                        return '<span style="background:'.$bg.';color:'.$fg.';padding:.18em .55em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;">'.$label.'</span>';
                    }

                    function task_priority_pill(string $p): string {
                        $map = [
                            'low'    => ['Low',    '#e5e7eb', '#374151'],
                            'normal' => ['Normal', '#dbeafe', '#1e40af'],
                            'high'   => ['High',   '#fed7aa', '#9a3412'],
                            'urgent' => ['Urgent', '#fee2e2', '#991b1b'],
                        ];
                        [$label, $bg, $fg] = $map[$p] ?? [ucfirst($p), '#e5e7eb', '#374151'];
                        return '<span style="background:'.$bg.';color:'.$fg.';padding:.18em .55em;border-radius:3px;font-size:.68rem;font-weight:700;">'.$label.'</span>';
                    }

                    function task_initials(?string $first, ?string $last): string {
                        $i1 = $first ? mb_substr($first, 0, 1) : '';
                        $i2 = $last  ? mb_substr($last,  0, 1) : '';
                        return strtoupper($i1 . $i2) ?: '?';
                    }
                    ?>

                    <style>
                    .tasks-bar{display:flex;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;flex-wrap:wrap;}
                    .tasks-bar h1{margin:0;}

                    .tabs{display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1rem;}
                    .tab{padding:.4rem .9rem;border-radius:999px;border:1px solid var(--line);text-decoration:none;color:var(--ink);font-size:.85rem;background:#fff;display:inline-flex;align-items:center;gap:.4rem;}
                    .tab.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
                    .tab .ct{font-size:.7rem;background:rgba(0,0,0,.1);padding:.05em .45em;border-radius:999px;}
                    .tab.on .ct{background:rgba(255,255,255,.25);}

                    .tasks-filters{display:flex;gap:.6rem;align-items:center;flex-wrap:wrap;margin-bottom:1rem;font-size:.85rem;}
                    .tasks-filters input[type="search"], .tasks-filters select{
                        padding:.45rem .65rem;border:1px solid var(--line);border-radius:6px;font-size:.85rem;font-family:inherit;
                    }

                    .tasks-tbl{width:100%;border-collapse:collapse;font-size:.875rem;}
                    .tasks-tbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
                    .tasks-tbl td{padding:.7rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;}
                    .tasks-tbl tr.clickable{cursor:pointer;}
                    .tasks-tbl tr.clickable:hover td{background:#f5f3ee;}
                    .tasks-tbl a.title-link{color:var(--brand-primary);text-decoration:none;font-weight:600;}
                    .tasks-tbl a.title-link:hover{text-decoration:underline;}
                    .tasks-tbl .desc-snip{color:var(--ink-muted);font-size:.78rem;margin-top:.15rem;line-height:1.35;display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;}
                    .tasks-tbl .meta-row{display:flex;gap:.5rem;align-items:center;font-size:.75rem;color:var(--ink-muted);margin-top:.25rem;}

                    .tasks-empty{text-align:center;padding:2.5rem 1rem;color:var(--ink-muted);}

                    .avatar{width:26px;height:26px;border-radius:50%;background:#6366f1;color:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:700;flex-shrink:0;}
                    .avatar.unassigned{background:#9ca3af;}
                    .avatar.me{background:#16a34a;}

                    .due-overdue{color:#991b1b;font-weight:700;}
                    .due-today{color:#92400e;font-weight:700;}
                    .due-soon{color:#1e40af;}

                    .row-done td{opacity:.55;}
                    .row-done .title-link{text-decoration:line-through;}

                    /* Inline checklist progress on a row */
                    .row-cl-progress{
                        margin-top:.4rem;height:5px;background:#e5e7eb;border-radius:999px;
                        position:relative;max-width:280px;
                    }
                    .row-cl-bar{
                        height:100%;background:linear-gradient(90deg,#6366f1,#10b981);
                        border-radius:999px;transition:width .25s ease;
                    }
                    .row-cl-text{
                        position:absolute;left:calc(100% + .55rem);top:-5px;
                        font-size:.7rem;color:var(--ink-muted);white-space:nowrap;
                    }
                    </style>

                    <section class="section"><div class="container">

                    <?php if (!empty($_GET['msg'])): ?>
                    <div class="alert alert-success" data-autohide style="margin-bottom:1rem;">
                    <?= htmlspecialchars((string)$_GET['msg']) ?>
                    </div>
                    <?php endif; ?>

                    <div class="tasks-bar">
                    <h1>Tasks</h1>
                    <a href="task-edit.php" class="btn">+ New task</a>
                    </div>

                    <!-- Tabs -->
                    <div class="tabs">
                    <a href="?tab=mine" class="tab <?= $tab==='mine'?'on':'' ?>">
                    My tasks <span class="ct"><?= $mine_count ?></span>
                    </a>
                    <a href="?tab=created" class="tab <?= $tab==='created'?'on':'' ?>">
                    I created <span class="ct"><?= $created_count ?></span>
                    </a>
                    <?php if ($is_super): ?>
                    <a href="?tab=all" class="tab <?= $tab==='all'?'on':'' ?>">
                    All tasks <span class="ct"><?= $all_count ?></span>
                    </a>
                    <?php endif; ?>
                    <a href="?tab=done" class="tab <?= $tab==='done'?'on':'' ?>">
                    Done <span class="ct"><?= $done_count ?></span>
                    </a>
                    </div>

                    <!-- Search -->
                    <form method="get" class="tasks-filters">
                    <input type="hidden" name="tab" value="<?= htmlspecialchars($tab) ?>">
                    <input type="search" name="q" placeholder="Search title or description…" value="<?= htmlspecialchars($q) ?>">
                    <button type="submit" class="btn btn-outline" style="padding:.4rem .9rem;font-size:.85rem;">Search</button>
                    <?php if ($q): ?>
                    <a href="?tab=<?= htmlspecialchars($tab) ?>" style="font-size:.8rem;color:var(--ink-muted);">Clear</a>
                    <?php endif; ?>
                    </form>

                    <!-- Table -->
                    <div class="card" style="padding:0;overflow:auto;">
                    <?php if (empty($tasks)): ?>
                    <div class="tasks-empty">
                    <p>No tasks here.</p>
                    <p style="margin-top:.5rem;">
                    <a href="task-edit.php" class="btn">Create your first task →</a>
                    </p>
                    </div>
                    <?php else: ?>
                    <table class="tasks-tbl">
                    <thead>
                    <tr>
                    <th>Status</th>
                    <th>Title</th>
                    <th>Priority</th>
                    <th>Assignee</th>
                    <th>Due</th>
                    <th>Created</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $today = date('Y-m-d');
                    foreach ($tasks as $t):
                    $row_class = in_array($t['status'], ['done','cancelled'], true) ? 'row-done' : '';

                    // Due classification
                    $due_class = '';
                    $due_text  = '—';
                    if (!empty($t['due_date'])) {
                        if (in_array($t['status'], ['done','cancelled'], true)) {
                            $due_text = date('j M', strtotime($t['due_date']));
                        } elseif ($t['due_date'] < $today) {
                            $due_class = 'due-overdue';
                            $due_text  = 'Overdue (' . date('j M', strtotime($t['due_date'])) . ')';
                        } elseif ($t['due_date'] === $today) {
                            $due_class = 'due-today';
                            $due_text  = 'Today';
                        } else {
                            $diff = (strtotime($t['due_date']) - strtotime($today)) / 86400;
                            if ($diff <= 7) $due_class = 'due-soon';
                            $due_text = date('j M', strtotime($t['due_date']));
                        }
                    }

                    $is_me_assigned = ((int)$t['assigned_to'] === (int)$me['id']);

                    $cl_total_row = (int)$t['cl_total'];
                    $cl_done_row  = (int)$t['cl_done'];
                    $cl_pct_row   = $cl_total_row > 0 ? (int)round(($cl_done_row / $cl_total_row) * 100) : 0;
                    ?>
                    <tr class="clickable <?= $row_class ?>" data-href="task-edit.php?id=<?= (int)$t['id'] ?>">
                    <td><?= task_status_pill((string)$t['status']) ?></td>
                    <td>
                    <a href="task-edit.php?id=<?= (int)$t['id'] ?>" class="title-link">
                    <?= htmlspecialchars($t['title']) ?>
                    </a>
                    <?php if (!empty($t['description'])): ?>
                    <div class="desc-snip"><?= htmlspecialchars(mb_substr($t['description'], 0, 140)) ?></div>
                    <?php endif; ?>
                    <?php if ($cl_total_row > 0): ?>
                    <div class="row-cl-progress">
                    <div class="row-cl-bar" style="width:<?= $cl_pct_row ?>%;"></div>
                    <span class="row-cl-text"><?= $cl_done_row ?>/<?= $cl_total_row ?> done</span>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($t['member_business'])): ?>
                    <div class="meta-row">
                    👤 <a href="member-edit.php?id=<?= (int)$t['member_id'] ?>" style="color:var(--ink-muted);">
                    <?= htmlspecialchars($t['member_business']) ?>
                    </a>
                    </div>
                    <?php endif; ?>
                    </td>
                    <td><?= task_priority_pill((string)$t['priority']) ?></td>
                    <td>
                    <?php if ($t['assigned_to']): ?>
                    <span style="display:inline-flex;align-items:center;gap:.4rem;">
                    <span class="avatar <?= $is_me_assigned ? 'me' : '' ?>">
                    <?= htmlspecialchars(task_initials($t['assignee_first'], $t['assignee_last'])) ?>
                    </span>
                    <span style="font-size:.82rem;">
                    <?= htmlspecialchars(trim(($t['assignee_first'] ?? '').' '.($t['assignee_last'] ?? ''))) ?>
                    <?= $is_me_assigned ? ' (you)' : '' ?>
                    </span>
                    </span>
                    <?php else: ?>
                    <span style="display:inline-flex;align-items:center;gap:.4rem;">
                    <span class="avatar unassigned">?</span>
                    <span style="color:var(--ink-muted);font-size:.82rem;">Unassigned</span>
                    </span>
                    <?php endif; ?>
                    </td>
                    <td class="<?= $due_class ?>" style="white-space:nowrap;font-size:.82rem;">
                    <?= htmlspecialchars($due_text) ?>
                    </td>
                    <td style="white-space:nowrap;font-size:.78rem;color:var(--ink-muted);">
                    <?= htmlspecialchars(date('j M', strtotime($t['created_at']))) ?>
                    <br>by <?= htmlspecialchars(trim(($t['creator_first'] ?? '').' '.($t['creator_last'] ?? ''))) ?>
                    </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                    </table>
                    <?php endif; ?>
                    </div>

                    </div></section>

                    <script>
                    // Make task rows clickable to open the task page
                    document.querySelectorAll('.tasks-tbl tr.clickable').forEach(function (tr) {
                            tr.addEventListener('click', function (e) {
                                    // Don't hijack clicks on any embedded link/button/form/input
                                    if (e.target.closest('a, button, form, input, label')) return;
                                    var href = tr.getAttribute('data-href');
                                    if (href) window.location.href = href;
                                });
                        });
                    </script>

                    <?php require __DIR__ . '/_footer.php'; ?>
