<?php
// ajax/jobcards_list.ajax.php
// Modes:
//   scope=all                          → dev: returns grouped object { open, active, completed, other }
//   team_id=X & status=active|completed → driver: returns JSON array
//   team_id=X & status=active & count_only=1 → driver: returns plain integer count
include $_SERVER['DOCUMENT_ROOT'] . "/root.class.php";
include $_SERVER['DOCUMENT_ROOT'] . "/app/test/classes/dashboard.class.php";

header('Content-Type: application/json');

$db   = new db_safeguard();
$dash = new DashboardData($db);

$scope      = $_GET['scope']      ?? '';
$team_id    = isset($_GET['team_id']) ? intval($_GET['team_id']) : 0;
$status     = $_GET['status']     ?? 'active';
$count_only = !empty($_GET['count_only']);

// ── DEV: all jobcards grouped ────────────────────────────
if ($scope === 'all') {
    echo json_encode($dash->allJobcardsGrouped());
    exit;
}

// ── DRIVER: count only ───────────────────────────────────
if ($count_only && $team_id) {
    // Override content type for plain text response
    header('Content-Type: text/plain');
    $rows = $dash->teamJobcards($team_id, $status);
    echo count($rows);
    exit;
}

// ── DRIVER: full list ────────────────────────────────────
if ($team_id) {
    echo json_encode($dash->teamJobcards($team_id, $status));
    exit;
}

echo json_encode([]);