<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

ob_start();

function respond(int $statusCode, array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($statusCode);
    echo json_encode($payload);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    respond(204, []);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, ['success' => false, 'message' => 'Method tidak dibenarkan.']);
}

require_once __DIR__ . '/../db.php';

$raw = file_get_contents('php://input');
$payload = json_decode($raw ?: '', true);
if (!is_array($payload)) {
    $payload = $_POST;
}

$userId = (int) ($payload['user_id'] ?? 0);
if ($userId <= 0) {
    respond(422, ['success' => false, 'message' => 'Pengguna tidak sah.']);
}

$requesterStmt = mysqli_prepare(
    $conn,
    'SELECT id, department
     FROM users
     WHERE id = ? AND status = "approved"
     LIMIT 1'
);
if (!$requesterStmt) {
    respond(500, ['success' => false, 'message' => 'Ralat sistem semasa membaca pengguna.']);
}

mysqli_stmt_bind_param($requesterStmt, 'i', $userId);
mysqli_stmt_execute($requesterStmt);
$requesterResult = mysqli_stmt_get_result($requesterStmt);
$requester = $requesterResult ? mysqli_fetch_assoc($requesterResult) : null;

if (!$requester) {
    respond(403, ['success' => false, 'message' => 'Akaun tidak dibenarkan.']);
}

$department = trim((string) ($requester['department'] ?? ''));
if ($department === '') {
    respond(200, [
        'success' => true,
        'message' => 'Bahagian pengguna belum ditetapkan.',
        'department' => '',
        'members' => [],
    ]);
}

$membersStmt = mysqli_prepare(
    $conn,
    'SELECT id, fullname, short_name, email, department, position, profile_photo
     FROM users
     WHERE department = ? AND status = "approved"
     ORDER BY fullname ASC'
);
if (!$membersStmt) {
    respond(500, ['success' => false, 'message' => 'Ralat sistem semasa membaca ahli pasukan.']);
}

mysqli_stmt_bind_param($membersStmt, 's', $department);
mysqli_stmt_execute($membersStmt);
$membersResult = mysqli_stmt_get_result($membersStmt);

$members = [];
$memberIndexes = [];
while ($row = $membersResult ? mysqli_fetch_assoc($membersResult) : null) {
    $memberId = (int) ($row['id'] ?? 0);
    $memberIndexes[$memberId] = count($members);
    $members[] = [
        'id' => $memberId,
        'fullname' => (string) ($row['fullname'] ?? ''),
        'shortName' => (string) ($row['short_name'] ?? ''),
        'email' => (string) ($row['email'] ?? ''),
        'department' => (string) ($row['department'] ?? ''),
        'position' => (string) ($row['position'] ?? ''),
        'profilePhoto' => (string) ($row['profile_photo'] ?? ''),
        'tasks' => [],
    ];
}

if ($members !== []) {
    $tasksStmt = mysqli_prepare(
        $conn,
        'SELECT ce.id, ce.user_id, ce.title, ce.description, ce.start_at, ce.end_at,
                ce.due_date, ce.manday, ce.priority, ce.status, ce.created_at
         FROM calendar_events ce
         INNER JOIN users owner ON owner.id = ce.user_id
         WHERE owner.department = ?
           AND owner.status = "approved"
           AND ce.event_type = "task"
           AND ce.deleted_at IS NULL
         ORDER BY
           CASE LOWER(COALESCE(ce.status, ""))
             WHEN "ongoing" THEN 1
             WHEN "in_progress" THEN 1
             WHEN "dump" THEN 2
             WHEN "completed" THEN 3
             WHEN "complete" THEN 3
             ELSE 4
           END,
           COALESCE(ce.due_date, DATE(ce.end_at), DATE(ce.start_at)) ASC,
           ce.updated_at DESC,
           ce.id DESC'
    );
    if (!$tasksStmt) {
        respond(500, ['success' => false, 'message' => 'Ralat sistem semasa membaca task pasukan.']);
    }

    mysqli_stmt_bind_param($tasksStmt, 's', $department);
    mysqli_stmt_execute($tasksStmt);
    $tasksResult = mysqli_stmt_get_result($tasksStmt);

    while ($task = $tasksResult ? mysqli_fetch_assoc($tasksResult) : null) {
        $ownerId = (int) ($task['user_id'] ?? 0);
        if (!array_key_exists($ownerId, $memberIndexes)) {
            continue;
        }

        $status = strtolower(trim((string) ($task['status'] ?? 'dump')));
        if (in_array($status, ['ongoing', 'in_progress', 'in progress'], true)) {
            $status = 'ongoing';
        } elseif (in_array($status, ['completed', 'complete', 'done'], true)) {
            $status = 'completed';
        } else {
            $status = 'dump';
        }

        $members[$memberIndexes[$ownerId]]['tasks'][] = [
            'id' => (int) ($task['id'] ?? 0),
            'userId' => $ownerId,
            'title' => (string) ($task['title'] ?? ''),
            'description' => (string) ($task['description'] ?? ''),
            'startAt' => (string) ($task['start_at'] ?? ''),
            'endAt' => (string) ($task['end_at'] ?? ''),
            'dueDate' => (string) ($task['due_date'] ?? ''),
            'manday' => (int) ($task['manday'] ?? 0),
            'priority' => strtolower((string) ($task['priority'] ?? '')),
            'status' => $status,
            'createdAt' => (string) ($task['created_at'] ?? ''),
        ];
    }
}

respond(200, [
    'success' => true,
    'message' => 'Task pasukan berjaya dimuatkan.',
    'department' => $department,
    'members' => $members,
]);
