<?php
// =============================================================
//  POST /api/v1/notices/delete_comment
//
//  Mobile equivalent of app/notice_ajax.php's delete_comment action —
//  any authenticated account (staff/nurse/student) may delete their own
//  comment; Admin may delete any comment. Not staff-gated, matching the
//  desktop, since students and nurses can comment too (notices/comment.php).
//
//  Body: { "comment_id": NN }
// =============================================================

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

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

$body      = Api::body();
$commentId = (int)($body['comment_id'] ?? 0);
if (!$commentId) Api::error(422, 'ValidationError', 'comment_id is required');

if ($isAdmin) {
    $stmt = $conn->prepare('DELETE FROM notice_comments WHERE id = ?');
    $stmt->bind_param('i', $commentId);
} else {
    $stmt = $conn->prepare('DELETE FROM notice_comments WHERE id = ? AND commenter_id = ? AND commenter_type = ?');
    $stmt->bind_param('iis', $commentId, $userId, $readerType);
}
$stmt->execute();
$deleted = $stmt->affected_rows > 0;
$stmt->close();

if (!$deleted) Api::error(404, 'NotFound', 'Comment not found or permission denied.');

Api::success(['message' => 'Comment deleted.']);
