<?php
// =============================================================
//  GET  /api/v1/notices/comment?notice_id=NN   — list comments
//  POST /api/v1/notices/comment  { "notice_id": NN, "body": "..." }  — post one
//
//  Mirrors app/notice_ajax.php's get_comments/post_comment actions.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

$account    = api_authenticate();
$table      = $account->getTable();
$readerType = match ($table) {
    'users'             => 'staff',
    'rotation_nurses'   => 'nurse',
    'clinical_students' => 'student',
};
$userId = $account->getId();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $noticeId = (int)($_GET['notice_id'] ?? 0);
    if (!$noticeId) Api::error(422, 'ValidationError', 'notice_id is required');

    $stmt = $conn->prepare("
        SELECT id, commenter_id, commenter_type, commenter_name, commenter_role, body, created_at
        FROM notice_comments WHERE notice_id = ? ORDER BY created_at ASC
    ");
    $stmt->bind_param('i', $noticeId);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    foreach ($rows as &$r) {
        $r['is_mine'] = ((int)$r['commenter_id'] === $userId && $r['commenter_type'] === $readerType);
    }
    unset($r);

    Api::success(['comments' => $rows]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body     = Api::body();
    $noticeId = (int)($body['notice_id'] ?? 0);
    $text     = trim((string)($body['body'] ?? ''));

    if (!$noticeId || $text === '') Api::error(422, 'ValidationError', 'notice_id and body are required');
    if (mb_strlen($text) > 2000) Api::error(422, 'ValidationError', 'Comment too long (max 2000 chars)');

    $roleLabel = $readerType === 'staff'
        ? str_replace('_', ' ', $account->getUserType())
        : ($readerType === 'nurse' ? 'Rotation Nurse' : 'Clinical Student');
    $fullName = $account->getFullName();

    $stmt = $conn->prepare("
        INSERT INTO notice_comments (notice_id, commenter_id, commenter_type, commenter_name, commenter_role, body, created_at)
        VALUES (?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->bind_param('iissss', $noticeId, $userId, $readerType, $fullName, $roleLabel, $text);
    $stmt->execute();
    $commentId = $conn->insert_id;
    $stmt->close();

    Api::success([
        'comment_id'     => $commentId,
        'commenter_name' => $fullName,
        'role'           => $roleLabel,
        'body'           => $text,
    ], [], 201);
}

Api::error(405, 'MethodNotAllowed', 'Use GET or POST');
