<?php
// =============================================================
//  POST /api/v1/notices/delete
//
//  Mobile equivalent of app/notice_ajax.php's delete_notice action.
//  Any staff role may call this (matching the desktop's own broad
//  is_staff gate), but only Admin/Chief_Preceptor can delete any
//  notice — everyone else can only delete their own. In practice only
//  Admin/Chief_Preceptor/Preceptor can ever own a notice (see
//  notices/create.php's own gate), so this is never reachable for a
//  Nurse_Manager/In_Charge account beyond a clean 403.
//
//  Body: { "notice_id": NN }
// =============================================================

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

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

$account = api_authenticate();
api_require_staff_role($account, ['Admin', 'Chief_Preceptor', 'Preceptor', 'Nurse_Manager', 'In_Charge']);
$usertype = $account->getUserType();
$isAdmin  = in_array($usertype, ['Admin', 'Chief_Preceptor'], true);
$userId   = $account->getId();

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

if ($isAdmin) {
    $stmt = $conn->prepare('DELETE FROM notices WHERE id = ?');
    $stmt->bind_param('i', $noticeId);
} else {
    $stmt = $conn->prepare('DELETE FROM notices WHERE id = ? AND posted_by = ?');
    $stmt->bind_param('ii', $noticeId, $userId);
}
$stmt->execute();
$deleted = $stmt->affected_rows > 0;
$stmt->close();

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

$conn->query("DELETE FROM notice_reads WHERE notice_id = {$noticeId}");
$conn->query("DELETE FROM notice_comments WHERE notice_id = {$noticeId}");

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