<?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;
}

function parseDate(string $value): ?DateTime
{
    $date = DateTime::createFromFormat('!Y-m-d', trim($value));
    return $date && $date->format('Y-m-d') === trim($value) ? $date : null;
}

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);
$startDate = parseDate((string) ($payload['start_date'] ?? date('Y-m-d')));
$endDate = parseDate((string) ($payload['end_date'] ?? date('Y-m-d')));

if ($userId <= 0 || !$startDate || !$endDate || $endDate < $startDate) {
    respond(422, ['success' => false, 'message' => 'Permintaan jadual pasukan tidak sah.']);
}

$rangeDays = (int) $startDate->diff($endDate)->format('%a') + 1;
if ($rangeDays > 42) {
    respond(422, ['success' => false, 'message' => 'Julat jadual maksimum ialah 42 hari.']);
}

$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' => '',
        'startDate' => $startDate->format('Y-m-d'),
        'endDate' => $endDate->format('Y-m-d'),
        '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'] ?? ''),
        'events' => [],
    ];
}

if ($members !== []) {
    $rangeStart = $startDate->format('Y-m-d 00:00:00');
    $rangeEnd = $endDate->format('Y-m-d 23:59:59');
    $eventsStmt = mysqli_prepare(
        $conn,
        'SELECT ce.id, ce.user_id, ce.event_type, ce.title, ce.description,
                ce.location, ce.start_at, ce.end_at, ce.due_date, ce.manday,
                ce.is_full_day, 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.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 jadual pasukan.']);
    }

    mysqli_stmt_bind_param($eventsStmt, 'sss', $department, $rangeEnd, $rangeStart);
    mysqli_stmt_execute($eventsStmt);
    $eventsResult = mysqli_stmt_get_result($eventsStmt);

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

        $type = strtolower(trim((string) ($event['event_type'] ?? 'event')));
        $privateAvailability = in_array($type, ['leave', 'time_off'], true);
        $members[$memberIndexes[$ownerId]]['events'][] = [
            'id' => (int) ($event['id'] ?? 0),
            'userId' => $ownerId,
            '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'] ?? ''),
            'dueDate' => (string) ($event['due_date'] ?? ''),
            'manday' => (int) ($event['manday'] ?? 0),
            'isFullDay' => ((int) ($event['is_full_day'] ?? 0)) === 1,
            'priority' => strtolower((string) ($event['priority'] ?? '')),
            'status' => (string) ($event['status'] ?? ''),
            'createdAt' => (string) ($event['created_at'] ?? ''),
        ];
    }
}

respond(200, [
    'success' => true,
    'message' => 'Jadual pasukan berjaya dimuatkan.',
    'department' => $department,
    'startDate' => $startDate->format('Y-m-d'),
    'endDate' => $endDate->format('Y-m-d'),
    'members' => $members,
]);
