<?php
// ============================================================
//  admin/task-edit.php — create or edit a task
// ============================================================
//
//  POST handling happens BEFORE _guard.php is required, so we
//  can issue header() redirects without "headers already sent".
//  _guard.php is only loaded for the render path (GET, or POST
//  validation failure where we re-render the form with errors).
//
//  Permission rules:
//    - Any admin can create a task (assigned to themselves OR
//      unassigned)
//    - Only super_admin can assign tasks to other admin users
//    - Editing: creator OR assignee can edit. Super admin: any.
//    - Status changes: creator OR assignee.
//
//  When a task is saved with an assignee that is NOT the actor,
//  the assignee gets an email (queued via email_enqueue).
// ============================================================

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

$id   = (int)($_GET['id'] ?? 0);
$task = $id ? db_row('SELECT * FROM admin_tasks WHERE id=:id', ['id' => $id]) : null;

if ($id && !$task) {
    http_response_code(404);
    exit('Task not found.');
}

$prefill_member_id = $task['member_id'] ?? (int)($_GET['member_id'] ?? 0);

// ── Permissions ──────────────────────────────────────────────
//   $can_act          → status changes, ticking checklist items, posting notes
//   $can_edit_content → title, description, priority, due date, assignee,
//                       checklist add/delete (the task definition itself)
$can_act          = true;
$can_edit_content = true;
if ($task) {
    $is_creator       = ((int)$task['created_by']  === (int)$me['id']);
    $is_assignee      = ((int)$task['assigned_to'] === (int)$me['id']);
    $can_act          = $is_super || $is_creator || $is_assignee;
    $can_edit_content = $is_super || $is_creator;
}

$error = '';

/**
 * Email the task creator when someone else marks the task done.
 * Skips if the actor IS the creator (no point emailing yourself).
 */
function task_send_completion_email(array $task_row, array $actor): void {
    $creator_id = (int)$task_row['created_by'];
    if ($creator_id === (int)$actor['id']) return;  // self-close, skip

    $creator = db_row('SELECT first_name, last_name, email FROM admin_users WHERE id=:id', ['id' => $creator_id]);
    if (!$creator || empty($creator['email'])) return;

    $task_url = rtrim(SITE_URL, '/') . '/admin/task-edit.php?id=' . (int)$task_row['id'];
    email_enqueue('task_completed', $creator['email'],
        trim($creator['first_name'].' '.$creator['last_name']),
        [
            'creator_name' => trim($creator['first_name'].' '.$creator['last_name']) ?: 'team member',
            'actor_name'   => trim(($actor['first_name'] ?? '').' '.($actor['last_name'] ?? '')) ?: $actor['email'],
            'task_title'   => $task_row['title'],
            'description'  => $task_row['description'] ?? '',
            'completed_at' => date('j F Y · H:i'),
            'task_url'     => $task_url,
        ]
    );
    app_log("Task #{$task_row['id']} completion email queued to creator admin {$creator_id}");
}

// ── POST handling — runs BEFORE any HTML output ─────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? 'save';

    // Permission gate per-action
    // - Status changes / ticking items / notes  → $can_act (creator OR assignee OR super)
    // - Edit content / add-or-delete items / delete task → $can_edit_content (creator OR super)
    $needs_content_perm = in_array($action, ['save','delete','item_add','item_delete'], true);
    $needs_act_perm     = in_array($action, ['set_status','item_toggle','note_add','note_delete'], true);

    if ($needs_act_perm && !$can_act) {
        $error = 'You don\'t have permission to act on this task.';
    } elseif ($needs_content_perm && !$can_edit_content) {
        $error = 'Only the task creator (or a super admin) can edit the task content or checklist items.';
    } else {

        // Quick status update (called from buttons on existing task)
        if ($action === 'set_status' && $task) {
            $new_status = $_POST['status'] ?? '';
            if (in_array($new_status, ['open','in_progress','done','cancelled'], true)) {
                $previous_status = $task['status'];
                db_exec(
                    "UPDATE admin_tasks
                        SET status=:s,
                            completed_at = CASE WHEN :s2='done' THEN NOW() ELSE completed_at END
                      WHERE id=:id",
                    ['s' => $new_status, 's2' => $new_status, 'id' => $task['id']]
                );

                // Email creator if this transitioned to 'done'
                if ($new_status === 'done' && $previous_status !== 'done') {
                    task_send_completion_email($task, $me);
                }

                header('Location: task-edit.php?id=' . (int)$task['id']
                    . '&msg=' . urlencode('Status updated to ' . str_replace('_',' ',$new_status)));
                exit;
            }
        }

        if ($action === 'delete' && $task) {
            if (!$is_super && (int)$task['created_by'] !== (int)$me['id']) {
                $error = 'Only the creator (or a super admin) can delete a task.';
            } else {
                db_exec('DELETE FROM admin_tasks WHERE id=:id', ['id' => $task['id']]);
                header('Location: tasks.php?msg=' . urlencode('Task deleted.'));
                exit;
            }
        }

        // ── Checklist item actions ────────────────────────────
        if ($action === 'item_add' && $task) {
            $label = trim((string)($_POST['label'] ?? ''));
            if ($label !== '') {
                $next_order = (int)db_value(
                    'SELECT COALESCE(MAX(sort_order),0) + 10 FROM admin_task_items WHERE task_id=:t',
                    ['t' => $task['id']]
                );
                db_insert('admin_task_items', [
                    'task_id'    => (int)$task['id'],
                    'label'      => mb_substr($label, 0, 500),
                    'checked'    => 0,
                    'sort_order' => $next_order,
                ]);
            }
            header('Location: task-edit.php?id=' . (int)$task['id'] . '#checklist');
            exit;
        }

        if ($action === 'item_toggle' && $task) {
            $item_id = (int)($_POST['item_id'] ?? 0);
            // Verify it belongs to this task
            $item = $item_id ? db_row(
                'SELECT * FROM admin_task_items WHERE id=:i AND task_id=:t',
                ['i' => $item_id, 't' => $task['id']]
            ) : null;
            if ($item) {
                $new_checked = $item['checked'] ? 0 : 1;
                db_exec(
                    "UPDATE admin_task_items
                        SET checked=:c,
                            checked_at = CASE WHEN :c2=1 THEN NOW() ELSE NULL END,
                            checked_by = CASE WHEN :c3=1 THEN :who ELSE NULL END
                      WHERE id=:id",
                    ['c'=>$new_checked, 'c2'=>$new_checked, 'c3'=>$new_checked,
                     'who'=>$me['id'], 'id'=>$item_id]
                );
            }
            header('Location: task-edit.php?id=' . (int)$task['id'] . '#checklist');
            exit;
        }

        if ($action === 'item_delete' && $task) {
            $item_id = (int)($_POST['item_id'] ?? 0);
            if ($item_id) {
                db_exec(
                    'DELETE FROM admin_task_items WHERE id=:i AND task_id=:t',
                    ['i' => $item_id, 't' => $task['id']]
                );
            }
            header('Location: task-edit.php?id=' . (int)$task['id'] . '#checklist');
            exit;
        }

        // ── Note actions ──────────────────────────────────────
        if ($action === 'note_add' && $task) {
            $body = trim((string)($_POST['body'] ?? ''));
            if ($body !== '') {
                db_insert('admin_task_notes', [
                    'task_id'     => (int)$task['id'],
                    'body'        => mb_substr($body, 0, 4000),
                    'author_id'   => (int)$me['id'],
                    'author_name' => trim(($me['first_name'] ?? '').' '.($me['last_name'] ?? '')) ?: $me['email'],
                ]);
            }
            header('Location: task-edit.php?id=' . (int)$task['id'] . '#notes');
            exit;
        }

        if ($action === 'note_delete' && $task) {
            $note_id = (int)($_POST['note_id'] ?? 0);
            $note = $note_id ? db_row(
                'SELECT * FROM admin_task_notes WHERE id=:i AND task_id=:t',
                ['i' => $note_id, 't' => $task['id']]
            ) : null;

            // Own note OR super admin
            if ($note && ($is_super || (int)$note['author_id'] === (int)$me['id'])) {
                db_exec('DELETE FROM admin_task_notes WHERE id=:i', ['i' => $note_id]);
            }
            header('Location: task-edit.php?id=' . (int)$task['id'] . '#notes');
            exit;
        }

        if ($action === 'save') {
            $title       = trim((string)($_POST['title']       ?? ''));
            $description = trim((string)($_POST['description'] ?? ''));
            $priority    = (string)($_POST['priority']         ?? 'normal');
            $status      = (string)($_POST['status']           ?? 'open');
            $due_date    = trim((string)($_POST['due_date']    ?? ''));
            $member_id   = (int)($_POST['member_id']           ?? 0) ?: null;
            $assigned_to = (int)($_POST['assigned_to']         ?? 0);

            if ($title === '') {
                $error = 'Title is required.';
            } elseif (!in_array($priority, ['low','normal','high','urgent'], true)) {
                $error = 'Invalid priority.';
            } elseif (!in_array($status, ['open','in_progress','done','cancelled'], true)) {
                $error = 'Invalid status.';
            } elseif ($due_date !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $due_date)) {
                $error = 'Invalid due date.';
            } else {
                // Permission: only super_admin can assign to others
                $assigning_to_other = ($assigned_to > 0 && $assigned_to !== (int)$me['id']);
                if ($assigning_to_other && !$is_super) {
                    $error = 'Only a super admin can assign tasks to other team members. ' .
                             'You can assign this task to yourself, or leave it unassigned.';
                } elseif ($assigned_to > 0) {
                    $a = db_row('SELECT id FROM admin_users WHERE id=:id AND active=1', ['id' => $assigned_to]);
                    if (!$a) {
                        $error = 'Selected assignee is not a valid admin user.';
                    }
                }

                if (!$error) {
                    $previous_assignee = $task ? (int)($task['assigned_to'] ?? 0) : 0;
                    $previous_status   = $task['status'] ?? null;

                    $payload = [
                        'title'       => mb_substr($title, 0, 200),
                        'description' => $description !== '' ? $description : null,
                        'priority'    => $priority,
                        'status'      => $status,
                        'due_date'    => $due_date !== '' ? $due_date : null,
                        'assigned_to' => $assigned_to ?: null,
                        'member_id'   => $member_id,
                    ];

                    if ($status === 'done' && $previous_status !== 'done') {
                        $payload['completed_at'] = date('Y-m-d H:i:s');
                    } elseif ($status !== 'done') {
                        $payload['completed_at'] = null;
                    }

                    if ($task) {
                        db_update('admin_tasks', (int)$task['id'], $payload);
                        $task_id = (int)$task['id'];
                    } else {
                        $payload['created_by'] = (int)$me['id'];
                        $task_id = db_insert('admin_tasks', $payload);

                        // Insert any checklist items submitted with the create form
                        $new_items = $_POST['new_items'] ?? [];
                        if (is_array($new_items)) {
                            $sort = 10;
                            foreach ($new_items as $label) {
                                $label = trim((string)$label);
                                if ($label === '') continue;
                                db_insert('admin_task_items', [
                                    'task_id'    => $task_id,
                                    'label'      => mb_substr($label, 0, 500),
                                    'checked'    => 0,
                                    'sort_order' => $sort,
                                ]);
                                $sort += 10;
                            }
                        }
                    }

                    // Completion email — fires when status transitions to 'done'
                    if ($task && $status === 'done' && $previous_status !== 'done') {
                        task_send_completion_email($task, $me);
                    }

                    // Email if newly assigned to someone other than the creator
                    $newly_assigned = ($assigned_to > 0)
                                   && ($assigned_to !== $previous_assignee)
                                   && ($assigned_to !== (int)$me['id']);

                    if ($newly_assigned) {
                        $assignee = db_row(
                            'SELECT first_name, last_name, email FROM admin_users WHERE id=:id',
                            ['id' => $assigned_to]
                        );
                        if ($assignee && !empty($assignee['email'])) {
                            $task_url = rtrim(SITE_URL, '/') . '/admin/task-edit.php?id=' . $task_id;
                            email_enqueue('task_assigned', $assignee['email'],
                                trim($assignee['first_name'].' '.$assignee['last_name']),
                                [
                                    'assignee_name' => trim($assignee['first_name'].' '.$assignee['last_name']) ?: 'team member',
                                    'assigner_name' => trim(($me['first_name'] ?? '').' '.($me['last_name'] ?? '')) ?: $me['email'],
                                    'task_title'    => $title,
                                    'description'   => $description,
                                    'priority'      => ucfirst($priority),
                                    'due_date'      => $due_date !== '' ? date('j F Y', strtotime($due_date)) : '',
                                    'task_url'      => $task_url,
                                ]
                            );
                            app_log("Task assignment email queued: task #{$task_id} to admin {$assigned_to}");
                        }
                    }

                    header('Location: task-edit.php?id=' . $task_id
                        . '&msg=' . urlencode($task ? 'Task updated.' : 'Task created.'));
                    exit;
                }
            }
        }
    }
}

// ── If we're here, we're rendering the form ─────────────────
// Re-fetch task after potential update, in case validation failed
// and we want to show the (uncommitted) values back to the user.
if ($id) {
    $task = db_row('SELECT * FROM admin_tasks WHERE id=:id', ['id' => $id]);
}

// Lookup data for form
$admin_options = $is_super
    ? db_all("SELECT id, first_name, last_name, email FROM admin_users WHERE active=1 ORDER BY first_name, last_name")
    : [$me]; // Non-super can only see themselves in the dropdown

// Load related member if any
$linked_member = null;
$linked_member_id = (int)($task['member_id'] ?? $prefill_member_id ?? 0);
if ($linked_member_id) {
    $linked_member = db_row(
        'SELECT id, first_name, last_name, business_name FROM members WHERE id=:id',
        ['id' => $linked_member_id]
    );
}

// Pre-fill values for new vs edit
$v_title       = htmlspecialchars($task['title']       ?? '');
$v_description = htmlspecialchars($task['description'] ?? '');
$v_priority    = $task['priority'] ?? 'normal';
$v_status      = $task['status']   ?? 'open';
$v_due_date    = $task['due_date'] ?? '';
$v_assigned_to = $task['assigned_to'] ?? (int)$me['id']; // default to me on new task

$creator = null;
if ($task) {
    $creator = db_row(
        'SELECT first_name, last_name FROM admin_users WHERE id=:id',
        ['id' => $task['created_by']]
    );
}

// Checklist items
$checklist = [];
$cl_done   = 0;
$cl_total  = 0;
$cl_pct    = 0;
if ($task) {
    $checklist = db_all(
        'SELECT * FROM admin_task_items WHERE task_id=:t ORDER BY sort_order, id',
        ['t' => $task['id']]
    );
    $cl_total = count($checklist);
    foreach ($checklist as $it) if ($it['checked']) $cl_done++;
    $cl_pct = $cl_total > 0 ? (int)round(($cl_done / $cl_total) * 100) : 0;
}

// Notes thread
$notes = [];
if ($task) {
    $notes = db_all(
        'SELECT * FROM admin_task_notes WHERE task_id=:t ORDER BY created_at ASC, id ASC',
        ['t' => $task['id']]
    );
}

// NOW it's safe to render — load chrome
$page_title = $task ? 'Edit task' : 'New task';
require __DIR__ . '/_guard.php';
?>

<style>
.task-form-wrap{max-width:780px;margin:0 auto;}
.task-form .row{margin-bottom:1.1rem;}
.task-form label{font-weight:600;font-size:.85rem;display:block;margin-bottom:.3rem;}
.task-form input[type="text"],
.task-form input[type="date"],
.task-form select,
.task-form textarea{
    width:100%;padding:.6rem .75rem;border:1px solid var(--line);border-radius:6px;font-size:.92rem;font-family:inherit;
}
.task-form textarea{min-height:120px;resize:vertical;}
.task-form .row-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem;}
@media(max-width:600px){.task-form .row-grid{grid-template-columns:1fr;}}
.task-form .hint{font-size:.78rem;color:var(--ink-muted);margin-top:.25rem;}

.task-meta{background:var(--surface-alt);border-radius:6px;padding:.85rem 1rem;font-size:.82rem;color:var(--ink-muted);margin-bottom:1.25rem;}
.task-meta strong{color:var(--ink);}

/* Form action footer (Save / Cancel) */
.form-actions{margin-top:1.5rem;}
.form-actions-left{display:flex;gap:.5rem;flex-wrap:wrap;}

/* Status action bar — sits below the form, very obvious */
.status-actions{
    margin-top:2rem;padding:1.25rem 1.5rem;
    background:var(--surface-alt);border:1px solid var(--line);border-radius:8px;
    display:flex;align-items:center;gap:1rem;flex-wrap:wrap;
}
.status-actions-label{font-weight:600;font-size:.9rem;color:var(--ink);}
.status-actions-buttons{display:flex;gap:.5rem;flex-wrap:wrap;}

.btn-status{
    padding:.55rem 1.1rem;border-radius:6px;border:1px solid;
    font-size:.88rem;font-weight:600;font-family:inherit;cursor:pointer;
    transition:.15s;
}
.btn-status-done{background:#16a34a;color:#fff;border-color:#16a34a;}
.btn-status-done:hover{background:#15803d;border-color:#15803d;}
.btn-status-reopen{background:#fff;color:#1e40af;border-color:#1e40af;}
.btn-status-reopen:hover{background:#dbeafe;}
.btn-status-progress{background:#fff;color:#92400e;border-color:#fde68a;}
.btn-status-progress:hover{background:#fef3c7;border-color:#f59e0b;}
.btn-status-cancel{background:#fff;color:#6b7280;border-color:#d1d5db;}
.btn-status-cancel:hover{background:#f3f4f6;}
.btn-status-delete{background:#fff;color:#991b1b;border-color:#fca5a5;}
.btn-status-delete:hover{background:#fee2e2;}

/* Notes thread */
.notes-thread{margin-bottom:1rem;}
.note{
    padding:.75rem .85rem;border:1px solid var(--line);border-radius:6px;
    margin-bottom:.6rem;background:#fff;
}
.note.is-own{background:#f8fafc;border-color:#cbd5e1;}
.note-header{
    display:flex;align-items:center;gap:.65rem;font-size:.82rem;margin-bottom:.45rem;
}
.note-header strong{color:var(--ink);}
.note-time{color:var(--ink-muted);}
.note-delete-form{margin:0 0 0 auto;}
.note-x{
    background:none;border:none;color:#9ca3af;font-size:1.05rem;cursor:pointer;
    padding:.05rem .35rem;border-radius:4px;line-height:1;
}
.note-x:hover{background:#fee2e2;color:#991b1b;}
.note-body{font-size:.92rem;line-height:1.5;color:var(--ink);white-space:pre-wrap;}

.note-add-form textarea{
    width:100%;padding:.6rem .75rem;border:1px solid var(--line);border-radius:6px;
    font-size:.9rem;font-family:inherit;resize:vertical;min-height:80px;
}

/* Checklist */
.cl-progress{background:#e5e7eb;border-radius:999px;height:8px;overflow:hidden;margin-bottom:1rem;}
.cl-progress-bar{height:100%;background:linear-gradient(90deg,#6366f1,#10b981);transition:width .35s ease;border-radius:999px;}
.cl-progress-bar.complete{background:#16a34a;}

.cl-all-done-hint{
    background:#ecfdf5;border:1px solid #6ee7b7;color:#065f46;
    padding:.6rem .9rem;border-radius:6px;font-size:.85rem;margin-bottom:1rem;
    display:flex;align-items:center;justify-content:space-between;gap:.75rem;flex-wrap:wrap;
}

.cl-list{list-style:none;padding:0;margin:0 0 1rem;}
.cl-item{
    display:flex;align-items:center;gap:.5rem;
    padding:.55rem .25rem;border-bottom:1px solid var(--line);font-size:.92rem;
}
.cl-item:last-child{border-bottom:none;}
.cl-item.is-checked .cl-label-text{
    text-decoration:line-through;color:var(--ink-muted);
}

.cl-toggle-form{flex:1;margin:0;}
.cl-checkbox-label{
    display:flex;align-items:center;gap:.6rem;cursor:pointer;font-weight:normal;margin:0;
}
.cl-checkbox-label input[type=checkbox]{
    width:18px;height:18px;cursor:pointer;flex-shrink:0;accent-color:#16a34a;
}
.cl-label-text{flex:1;line-height:1.35;}

.cl-by{font-size:.72rem;color:var(--ink-muted);white-space:nowrap;}

.cl-delete-form{margin:0;}
.cl-x{
    background:none;border:none;color:#9ca3af;font-size:1.1rem;cursor:pointer;
    padding:.15rem .35rem;border-radius:4px;line-height:1;
}
.cl-x:hover{background:#fee2e2;color:#991b1b;}

.cl-add-form{
    display:flex;gap:.5rem;align-items:center;
    padding-top:.5rem;border-top:1px dashed var(--line);
}
.cl-add-form input[type=text]{
    flex:1;padding:.5rem .65rem;border:1px solid var(--line);border-radius:6px;
    font-size:.9rem;font-family:inherit;
}

/* Checklist builder for new tasks */
.new-item-row{
    display:flex;gap:.5rem;align-items:center;margin-bottom:.5rem;
}
.new-item-row input[type=text]{
    flex:1;padding:.5rem .7rem;border:1px solid var(--line);border-radius:6px;
    font-size:.9rem;font-family:inherit;
}
.new-item-x{
    background:none;border:none;color:#9ca3af;font-size:1.3rem;cursor:pointer;
    padding:.15rem .55rem;border-radius:4px;line-height:1;
}
.new-item-x:hover{background:#fee2e2;color:#991b1b;}
</style>

<section class="section"><div class="container task-form-wrap">

<p style="margin:0 0 .75rem;">
    <a href="tasks.php" style="color:var(--ink-muted);text-decoration:none;font-size:.88rem;">← Back to tasks</a>
</p>

<h1 style="margin:0 0 1.25rem;"><?= $task ? 'Edit task' : 'New task' ?></h1>

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

<?php if ($task): ?>
    <div class="task-meta">
        <strong>Created</strong>
        <?= htmlspecialchars(date('j F Y · H:i', strtotime($task['created_at']))) ?>
        <?php if ($creator): ?>
            by <?= htmlspecialchars(trim($creator['first_name'].' '.$creator['last_name'])) ?>
        <?php endif; ?>
        <?php if (!empty($task['completed_at'])): ?>
            &nbsp;·&nbsp; <strong>Completed</strong>
            <?= htmlspecialchars(date('j F Y · H:i', strtotime($task['completed_at']))) ?>
        <?php endif; ?>
    </div>
<?php endif; ?>

<?php if ($task): ?>
<!-- ── Checklist ─────────────────────────────────────────── -->
<div id="checklist" class="card" style="padding:1.25rem 1.5rem;margin-bottom:1.5rem;">
    <div style="display:flex;justify-content:space-between;align-items:baseline;gap:1rem;flex-wrap:wrap;margin-bottom:.75rem;">
        <h3 style="margin:0;font-size:1.05rem;">Checklist</h3>
        <span style="font-size:.85rem;color:var(--ink-muted);">
            <?php if ($cl_total > 0): ?>
                <strong style="color:var(--ink);"><?= $cl_done ?></strong> of <strong style="color:var(--ink);"><?= $cl_total ?></strong> done
                · <?= $cl_pct ?>%
            <?php else: ?>
                No items yet
            <?php endif; ?>
        </span>
    </div>

    <?php if ($cl_total > 0): ?>
        <!-- Progress bar -->
        <div class="cl-progress">
            <div class="cl-progress-bar <?= $cl_pct === 100 ? 'complete' : '' ?>"
                 style="width:<?= $cl_pct ?>%;"></div>
        </div>

        <!-- All-done hint -->
        <?php if ($cl_pct === 100 && $task['status'] !== 'done' && $can_act): ?>
            <div class="cl-all-done-hint">
                🎉 All items checked! Ready to mark this task done?
                <form method="post" style="display:inline;margin-left:.5rem;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="set_status">
                    <input type="hidden" name="status" value="done">
                    <button type="submit" class="btn-status btn-status-done" style="padding:.3rem .85rem;font-size:.8rem;">
                        ✓ Mark task done
                    </button>
                </form>
            </div>
        <?php endif; ?>

        <!-- Items -->
        <ul class="cl-list">
            <?php foreach ($checklist as $it):
                $checked_user = null;
                if ($it['checked'] && !empty($it['checked_by'])) {
                    $checked_user = db_row(
                        'SELECT first_name, last_name FROM admin_users WHERE id=:id',
                        ['id' => $it['checked_by']]
                    );
                }
            ?>
                <li class="cl-item <?= $it['checked'] ? 'is-checked' : '' ?>">
                    <form method="post" class="cl-toggle-form">
                        <?= csrf_field() ?>
                        <input type="hidden" name="action" value="item_toggle">
                        <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
                        <label class="cl-checkbox-label">
                            <input type="checkbox"
                                   <?= $it['checked'] ? 'checked' : '' ?>
                                   <?= $can_act ? 'onchange="this.form.submit()"' : 'disabled' ?>>
                            <span class="cl-label-text"><?= htmlspecialchars($it['label']) ?></span>
                        </label>
                    </form>
                    <?php if ($it['checked'] && $checked_user): ?>
                        <span class="cl-by" title="<?= htmlspecialchars(date('j M Y H:i', strtotime($it['checked_at']))) ?>">
                            ✓ <?= htmlspecialchars(trim($checked_user['first_name'].' '.$checked_user['last_name'])) ?>
                        </span>
                    <?php endif; ?>
                    <?php if ($can_edit_content): ?>
                        <form method="post" class="cl-delete-form"
                              onsubmit="return confirm('Remove this item?');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="item_delete">
                            <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
                            <button type="submit" class="cl-x" title="Remove item">×</button>
                        </form>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <!-- Add item -->
    <?php if ($can_edit_content): ?>
    <form method="post" class="cl-add-form">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="item_add">
        <input type="text" name="label" placeholder="+ Add a checklist item…" maxlength="500" required>
        <button type="submit" class="btn btn-outline" style="padding:.45rem .9rem;font-size:.85rem;">Add</button>
    </form>
    <?php endif; ?>
</div>
<?php endif; ?>

<form method="post" class="task-form" <?= $can_edit_content ? '' : 'onsubmit="return false;"' ?>>
    <?= csrf_field() ?>
    <input type="hidden" name="action" value="save">

    <div class="row">
        <label for="title">Title *</label>
        <input type="text" id="title" name="title" required maxlength="200"
               value="<?= $v_title ?>"
               <?= $can_edit_content ? '' : 'readonly' ?>>
    </div>

    <div class="row">
        <label for="description">Description</label>
        <textarea id="description" name="description" maxlength="4000"
                  placeholder="Context, links, what success looks like…"
                  <?= $can_edit_content ? '' : 'readonly' ?>><?= $v_description ?></textarea>
    </div>

    <?php if (!$task && $can_edit_content): ?>
    <!-- Checklist builder for NEW tasks — items are submitted with the form -->
    <div class="row">
        <label>Checklist (optional)</label>
        <p class="hint" style="margin:.1rem 0 .5rem;">
            Add a list of items the assignee will tick off as they work through the task.
        </p>
        <div id="new-items-list"></div>
        <button type="button" id="new-items-add" class="btn btn-outline"
                style="font-size:.85rem;padding:.4rem .9rem;">+ Add item</button>
    </div>

    <script>
    (function () {
        var list = document.getElementById('new-items-list');
        var addBtn = document.getElementById('new-items-add');

        function addRow(value) {
            var row = document.createElement('div');
            row.className = 'new-item-row';
            row.innerHTML =
                '<input type="text" name="new_items[]" maxlength="500" ' +
                'placeholder="e.g. Send welcome email" value="' + (value || '').replace(/"/g, '&quot;') + '">' +
                '<button type="button" class="new-item-x" title="Remove">&times;</button>';
            row.querySelector('.new-item-x').addEventListener('click', function () {
                row.remove();
            });
            list.appendChild(row);
            // Focus the new input for fast entry
            row.querySelector('input').focus();
        }

        addBtn.addEventListener('click', function () { addRow(''); });

        // Allow pressing Enter inside an item field to add another
        list.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && e.target.matches('input[name="new_items[]"]')) {
                e.preventDefault();
                addRow('');
            }
        });

        // Spawn one empty row on load so the field is visible
        addRow('');
    })();
    </script>
    <?php endif; ?>

    <div class="row row-grid">
        <div>
            <label for="priority">Priority</label>
            <select id="priority" name="priority" <?= $can_edit_content ? '' : 'disabled' ?>>
                <?php foreach (['low','normal','high','urgent'] as $p): ?>
                    <option value="<?= $p ?>" <?= $v_priority===$p?'selected':'' ?>>
                        <?= ucfirst($p) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label for="due_date">Due date</label>
            <input type="date" id="due_date" name="due_date"
                   value="<?= htmlspecialchars($v_due_date ?? '') ?>"
                   <?= $can_edit_content ? '' : 'readonly' ?>>
        </div>
    </div>

    <div class="row row-grid">
        <div>
            <label for="status">Status</label>
            <select id="status" name="status" <?= $can_edit_content ? '' : 'disabled' ?>>
                <?php foreach (['open'=>'Open','in_progress'=>'In progress','done'=>'Done','cancelled'=>'Cancelled'] as $k=>$lbl): ?>
                    <option value="<?= $k ?>" <?= $v_status===$k?'selected':'' ?>>
                        <?= htmlspecialchars($lbl) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label for="assigned_to">Assigned to</label>
            <select id="assigned_to" name="assigned_to" <?= $can_edit_content ? '' : 'disabled' ?>>
                <option value="0">— Unassigned —</option>
                <?php foreach ($admin_options as $u):
                    $name = trim(($u['first_name'] ?? '').' '.($u['last_name'] ?? '')) ?: $u['email'];
                    $is_me = ((int)$u['id'] === (int)$me['id']);
                ?>
                    <option value="<?= (int)$u['id'] ?>"
                            <?= (int)$v_assigned_to===(int)$u['id']?'selected':'' ?>>
                        <?= htmlspecialchars($name) ?><?= $is_me ? ' (me)' : '' ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?php if (!$is_super): ?>
                <p class="hint">Only a super admin can assign tasks to other team members.</p>
            <?php else: ?>
                <p class="hint">Assigning to someone else will email them a notification.</p>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($linked_member): ?>
    <div class="row">
        <label>Linked member</label>
        <input type="hidden" name="member_id" value="<?= (int)$linked_member['id'] ?>">
        <div style="background:var(--surface-alt);padding:.6rem .85rem;border-radius:6px;font-size:.88rem;display:flex;justify-content:space-between;align-items:center;gap:.5rem;">
            <span>
                <?= htmlspecialchars($linked_member['business_name']) ?>
                <span class="muted" style="font-size:.78rem;">
                    (<?= htmlspecialchars(trim($linked_member['first_name'].' '.$linked_member['last_name'])) ?>)
                </span>
            </span>
            <a href="member-edit.php?id=<?= (int)$linked_member['id'] ?>" style="font-size:.78rem;">View →</a>
        </div>
    </div>
    <?php else: ?>
        <input type="hidden" name="member_id" value="">
    <?php endif; ?>

    <?php if ($can_edit_content): ?>
    <div class="form-actions">
        <div class="form-actions-left">
            <button type="submit" class="btn"><?= $task ? 'Save changes' : 'Create task' ?></button>
            <a href="tasks.php" class="btn btn-outline">Cancel</a>
        </div>
    </div>
    <?php endif; ?>
</form>

<?php if ($task && $can_act): ?>
    <!-- Status action bar — separate, big, obvious -->
    <div class="status-actions">
        <span class="status-actions-label">Mark this task as:</span>
        <div class="status-actions-buttons">
            <?php if ($task['status'] !== 'done'): ?>
                <form method="post" style="display:inline;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="set_status">
                    <input type="hidden" name="status" value="done">
                    <button type="submit" class="btn-status btn-status-done">
                        ✓ Done
                    </button>
                </form>
            <?php else: ?>
                <form method="post" style="display:inline;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="set_status">
                    <input type="hidden" name="status" value="open">
                    <button type="submit" class="btn-status btn-status-reopen">
                        ↻ Reopen
                    </button>
                </form>
            <?php endif; ?>

            <?php if ($task['status'] !== 'in_progress' && $task['status'] !== 'done'): ?>
                <form method="post" style="display:inline;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="set_status">
                    <input type="hidden" name="status" value="in_progress">
                    <button type="submit" class="btn-status btn-status-progress">
                        In progress
                    </button>
                </form>
            <?php endif; ?>

            <?php if ($task['status'] !== 'cancelled' && $task['status'] !== 'done'): ?>
                <form method="post" style="display:inline;"
                      onsubmit="return confirm('Cancel this task? You can reopen it later.');">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="set_status">
                    <input type="hidden" name="status" value="cancelled">
                    <button type="submit" class="btn-status btn-status-cancel">
                        Cancel task
                    </button>
                </form>
            <?php endif; ?>
        </div>

        <?php if ($task && ($is_super || (int)$task['created_by'] === (int)$me['id'])): ?>
            <form method="post" style="display:inline;margin-left:auto;"
                  onsubmit="return confirm('Delete this task permanently?');">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="delete">
                <button type="submit" class="btn-status btn-status-delete">
                    Delete task
                </button>
            </form>
        <?php endif; ?>
    </div>
<?php elseif ($task && !$can_act): ?>
    <p class="muted" style="font-size:.85rem;text-align:center;margin-top:1.5rem;">
        You don't have permission to act on this task.
        <a href="tasks.php">Back to tasks</a>
    </p>
<?php endif; ?>

<?php if ($task): ?>
<!-- ── Notes ────────────────────────────────────────────── -->
<div id="notes" class="card" style="padding:1.25rem 1.5rem;margin-top:1.5rem;">
    <h3 style="margin:0 0 .25rem;font-size:1.05rem;">Notes</h3>
    <p class="muted" style="margin:0 0 1rem;font-size:.82rem;">
        Discussion thread for this task. Visible to anyone who can view the task.
    </p>

    <?php if (empty($notes)): ?>
        <p style="color:var(--ink-muted);font-size:.88rem;font-style:italic;margin:.5rem 0 1rem;">
            No notes yet.
        </p>
    <?php else: ?>
        <div class="notes-thread">
            <?php foreach ($notes as $n):
                $is_own = ((int)$n['author_id'] === (int)$me['id']);
                $can_delete_note = $is_own || $is_super;
                $author_label = htmlspecialchars($n['author_name'] ?: 'Unknown');
            ?>
                <div class="note <?= $is_own ? 'is-own' : '' ?>">
                    <div class="note-header">
                        <strong><?= $author_label ?></strong>
                        <span class="note-time" title="<?= htmlspecialchars($n['created_at']) ?>">
                            <?= htmlspecialchars(date('j M Y · H:i', strtotime($n['created_at']))) ?>
                        </span>
                        <?php if ($can_delete_note): ?>
                            <form method="post" class="note-delete-form"
                                  onsubmit="return confirm('Delete this note?');">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="note_delete">
                                <input type="hidden" name="note_id" value="<?= (int)$n['id'] ?>">
                                <button type="submit" class="note-x" title="Delete note">×</button>
                            </form>
                        <?php endif; ?>
                    </div>
                    <div class="note-body"><?= nl2br(htmlspecialchars($n['body'])) ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if ($can_act): ?>
        <form method="post" class="note-add-form">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="note_add">
            <textarea name="body" required maxlength="4000"
                      placeholder="Write a note…" rows="3"></textarea>
            <div style="display:flex;justify-content:flex-end;margin-top:.5rem;">
                <button type="submit" class="btn btn-outline" style="padding:.45rem .9rem;font-size:.85rem;">Post note</button>
            </div>
        </form>
    <?php else: ?>
        <p class="muted" style="font-size:.82rem;font-style:italic;margin-top:.75rem;">
            Only the task creator or assignee can post notes.
        </p>
    <?php endif; ?>
</div>
<?php endif; ?>

</div></section>

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