<?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);
$requestedDate = trim((string) ($payload['date'] ?? date('Y-m-d')));
$date = DateTime::createFromFormat('!Y-m-d', $requestedDate);
if ($userId <= 0 || !$date || $date->format('Y-m-d') !== $requestedDate) {
    respond(422, ['success' => false, 'message' => 'Permintaan Team Pulse tidak sah.']);
}

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

mysqli_stmt_bind_param($userStmt, 'i', $userId);
mysqli_stmt_execute($userStmt);
$userResult = mysqli_stmt_get_result($userStmt);
$requester = $userResult ? mysqli_fetch_assoc($userResult) : null;
if (!$requester) {
    respond(403, ['success' => false, 'message' => 'Akaun tidak dibenarkan.']);
}

$department = trim((string) ($requester['department'] ?? ''));
if ($department === '') {
    respond(200, [
        'success' => true,
        'department' => '',
        'date' => $requestedDate,
        'members' => [],
    ]);
}

$membersStmt = mysqli_prepare(
    $conn,
    'SELECT id, fullname, short_name, 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 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'] ?? ''),
        'position' => (string) ($row['position'] ?? ''),
        'profileImage' => (string) ($row['profile_photo'] ?? ''),
        'events' => [],
    ];
}

if ($members !== []) {
    $startAt = $date->format('Y-m-d 00:00:00');
    $endAt = $date->format('Y-m-d 23:59:59');
    $eventsStmt = mysqli_prepare(
        $conn,
        'SELECT ce.*
         FROM calendar_events ce
         INNER JOIN users u ON u.id = ce.user_id
         WHERE u.department = ?
           AND u.status = "approved"
           AND ce.deleted_at IS NULL
           AND ce.start_at <= ?
           AND COALESCE(ce.end_at, ce.start_at) >= ?
         ORDER BY ce.start_at ASC, ce.id ASC'
    );
    if (!$eventsStmt) {
        respond(500, ['success' => false, 'message' => 'Ralat sistem semasa membaca aktiviti pasukan.']);
    }

    mysqli_stmt_bind_param($eventsStmt, 'sss', $department, $endAt, $startAt);
    mysqli_stmt_execute($eventsStmt);
    $eventsResult = mysqli_stmt_get_result($eventsStmt);

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

        $type = (string) ($event['event_type'] ?? 'event');
        $privateAvailability = in_array($type, ['leave', 'time_off'], true);
        $members[$memberIndexes[$memberId]]['events'][] = [
            'id' => (int) ($event['id'] ?? 0),
            'userId' => $memberId,
            'type' => $type,
            'title' => $privateAvailability
                ? ($type === 'leave' ? 'Cuti Rehat' : 'Time Off')
                : (string) ($event['title'] ?? ''),
            'description' => $privateAvailability ? '' : (string) ($event['description'] ?? ''),
            'location' => $privateAvailability ? '' : (string) ($event['location'] ?? ''),
            'startAt' => (string) ($event['start_at'] ?? ''),
            'endAt' => (string) ($event['end_at'] ?? ''),
            'isFullDay' => ((int) ($event['is_full_day'] ?? 0)) === 1,
            'priority' => '',
            'status' => '',
            'reason' => '',
            'participants' => [],
            'dateLabel' => substr((string) ($event['start_at'] ?? ''), 0, 10),
            'timeLabel' => '',
        ];
    }
}

respond(200, [
    'success' => true,
    'message' => 'Team Pulse berjaya dimuatkan.',
    'department' => $department,
    'date' => $requestedDate,
    'members' => $members,
]);
