<?php
// =============================================================
//  POST /api/v1/notices/update
//
//  Mobile equivalent of app/notice_ajax.php's update_notice action.
//  Same gate as notices/create.php (Admin/Chief_Preceptor/Preceptor —
//  the only roles that can ever own a notice, since only they can post
//  one) plus per-notice ownership: Admin/Chief_Preceptor can edit any
//  notice, Preceptor only their own. Non-admin callers silently keep the
//  notice's existing pin state — pinning is Admin/Chief_Preceptor-only.
//
//  Body: { "notice_id": NN, "title": "...", "body": "...",
//          "audience"?: "...", "priority"?: "...", "expires"?: "YYYY-MM-DD",
//          "pinned"?: bool }
// =============================================================

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']);
$usertype = $account->getUserType();
$isAdmin  = in_array($usertype, ['Admin', 'Chief_Preceptor'], true);
$userId   = $account->getId();

$body     = Api::body();
$noticeId = (int)($body['notice_id'] ?? 0);
$title    = trim((string)($body['title'] ?? ''));
$noticeBody = trim((string)($body['body'] ?? ''));
$audience = trim((string)($body['audience'] ?? 'both'));
$priority = trim((string)($body['priority'] ?? 'normal'));
$expires  = trim((string)($body['expires'] ?? '')) ?: null;

if (!$noticeId) Api::error(422, 'ValidationError', 'notice_id is required');
if ($title === '' || $noticeBody === '') {
    Api::error(422, 'ValidationError', 'Title and body are required');
}
if (!in_array($audience, ['nurses', 'students', 'both', 'staff'], true)) $audience = 'both';
if (!in_array($priority, ['normal', 'important', 'urgent'], true)) $priority = 'normal';
if ($expires !== null && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $expires)) {
    Api::error(422, 'ValidationError', 'expires must be YYYY-MM-DD');
}

$chk = $conn->prepare("SELECT posted_by, is_pinned FROM notices WHERE id = ? AND status != 'deleted'");
$chk->bind_param('i', $noticeId);
$chk->execute();
$existing = $chk->get_result()->fetch_assoc();
$chk->close();

if (!$existing) Api::error(404, 'NotFound', 'Notice not found.');
if (!$isAdmin && (int)$existing['posted_by'] !== $userId) {
    Api::error(403, 'Forbidden', 'You can only edit your own notices.');
}

$pinned = $isAdmin && !empty($body['pinned']) ? 1 : (int)$existing['is_pinned'];
if (!$isAdmin) {
    // Non-admin callers never change pin state either way — keep it as-is
    // regardless of what they sent.
    $pinned = (int)$existing['is_pinned'];
}

$stmt = $conn->prepare("
    UPDATE notices SET
        title = ?, body = ?, audience = ?, priority = ?, is_pinned = ?, expires_at = ?, updated_at = NOW()
    WHERE id = ?
");
$stmt->bind_param('ssssisi', $title, $noticeBody, $audience, $priority, $pinned, $expires, $noticeId);
$stmt->execute();
$stmt->close();

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