<?php
// ============================================================
//  MediCore — Task Center API
//  File: api/tasks.php
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/notify.php';
require_login();
session_write_close();

ensure_topbar_tables();

header('Content-Type: application/json');

$body   = json_decode(file_get_contents('php://input'), true) ?? [];
$action = trim($body['action'] ?? '');

try {
    match ($action) {
        'list'          => api_list($body),
        'create'        => api_create($body),
        'update_status' => api_update_status($body),
        'mark_complete' => api_mark_complete($body),
        'delete'        => api_delete($body),
        'pending_count' => api_pending_count($body),
        'users'         => api_users($body),
        default         => fail('Unknown action')
    };
} catch (Throwable $e) {
    fail($e->getMessage());
}

// ── List ──────────────────────────────────────────────────────
// Admin/manager see every task; everyone else only sees what's
// assigned to them.
function api_list(array $b): void {
    $uid    = current_user_id();
    $isMgr  = is_admin() || current_user_role() === 'manager';
    $status = trim($b['status'] ?? '');

    $where  = [];
    $params = [];
    if (!$isMgr) { $where[] = 't.assigned_to = ?'; $params[] = $uid; }
    if ($status) { $where[] = 't.status = ?';      $params[] = $status; }
    $wSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    $page     = max(1, (int)($b['page'] ?? 1));
    $pageSize = max(5, min(100, (int)($b['page_size'] ?? 30)));
    $offset   = ($page - 1) * $pageSize;

    $total = (int) db_val("SELECT COUNT(*) FROM tasks t $wSql", $params);
    $rows  = db_rows(
        "SELECT t.*, u.name AS assignee_name, c.name AS creator_name
           FROM tasks t
      LEFT JOIN users u ON u.id = t.assigned_to
      LEFT JOIN users c ON c.id = t.created_by
           $wSql
       ORDER BY (t.status = 'completed'), FIELD(t.priority,'high','medium','low'),
                (t.due_date IS NULL), t.due_date ASC
          LIMIT $pageSize OFFSET $offset",
        $params
    );

    ok([
        'data'        => $rows,
        'page'        => $page,
        'total'       => $total,
        'total_pages' => (int) max(1, ceil($total / $pageSize)),
        'pending'     => (int) db_val(
            "SELECT COUNT(*) FROM tasks WHERE assigned_to = ? AND status != 'completed'", [$uid]
        ),
    ]);
}

// ── Create (admin/manager only) ─────────────────────────────────
function api_create(array $b): void {
    if (!is_admin() && current_user_role() !== 'manager') {
        fail('Only admins/managers can assign tasks.');
    }

    $title       = trim($b['title'] ?? '');
    $description = trim($b['description'] ?? '');
    $assignedTo  = (int)($b['assigned_to'] ?? 0);
    $priority    = trim($b['priority'] ?? 'medium');
    $dueDate     = trim($b['due_date'] ?? '');

    if (!$title)      fail('Title is required.');
    if (!$assignedTo) fail('Please assign this task to a user.');
    if (!in_array($priority, ['high','medium','low'])) $priority = 'medium';
    if ($dueDate && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dueDate)) $dueDate = '';

    $id = db_insert(
        "INSERT INTO tasks (title, description, assigned_to, priority, due_date, created_by)
         VALUES (?,?,?,?,?,?)",
        [$title, $description, $assignedTo, $priority, $dueDate ?: null, current_user_id()]
    );

    create_notification([$assignedTo], 'task_assigned', '✅',
        'New Task Assigned', $title, 'dashboard.php');

    ok(['id' => $id]);
}

// ── Update status ────────────────────────────────────────────
function api_update_status(array $b): void {
    $uid    = current_user_id();
    $id     = (int)($b['id'] ?? 0);
    $status = trim($b['status'] ?? '');
    if (!$id) fail('Missing id');
    if (!in_array($status, ['pending','in_progress','completed'])) fail('Invalid status');

    $task = db_row("SELECT assigned_to FROM tasks WHERE id = ?", [$id]);
    if (!$task) fail('Task not found');
    if ((int)$task['assigned_to'] !== $uid && !is_admin() && current_user_role() !== 'manager') {
        fail('You can only update tasks assigned to you.');
    }

    $completedAt = $status === 'completed' ? date('Y-m-d H:i:s') : null;
    db_run(
        "UPDATE tasks SET status = ?, completed_at = ? WHERE id = ?",
        [$status, $completedAt, $id]
    );
    ok();
}

function api_mark_complete(array $b): void {
    api_update_status(['id' => $b['id'] ?? 0, 'status' => 'completed']);
}

// ── Delete (admin/manager only) ─────────────────────────────────
function api_delete(array $b): void {
    if (!is_admin() && current_user_role() !== 'manager') {
        fail('Only admins/managers can delete tasks.');
    }
    $id = (int)($b['id'] ?? 0);
    if (!$id) fail('Missing id');
    db_run("DELETE FROM tasks WHERE id = ?", [$id]);
    ok();
}

function api_pending_count(array $b): void {
    $uid = current_user_id();
    ok(['pending' => (int) db_val(
        "SELECT COUNT(*) FROM tasks WHERE assigned_to = ? AND status != 'completed'", [$uid]
    )]);
}

function api_users(array $b): void {
    ok(['data' => db_rows("SELECT id, name, role FROM users WHERE is_active = 1 ORDER BY name")]);
}

function ok(array $extra = []): void {
    echo json_encode(array_merge(['success' => true], $extra));
    exit;
}
function fail(string $msg): never {
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}
