<?php
// =============================================================
//  POST /api/v1/notices/pin
//
//  Mobile equivalent of app/notice_ajax.php's pin_notice action —
//  Admin/Chief_Preceptor only, any notice (pinning isn't an ownership
//  concept, unlike edit/delete/archive).
//
//  Body: { "notice_id": NN, "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']);

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

$stmt = $conn->prepare('UPDATE notices SET is_pinned = ? WHERE id = ? AND status != \'deleted\'');
$stmt->bind_param('ii', $pinned, $noticeId);
$stmt->execute();
$changed = $stmt->affected_rows > 0;
$stmt->close();

// affected_rows is also 0 when the notice is already in the requested pin
// state — fall back to an existence check so a repeat call (e.g. a retried
// tap) doesn't report a false 404.
if (!$changed) {
    $chk = $conn->prepare('SELECT id FROM notices WHERE id = ? AND status != \'deleted\'');
    $chk->bind_param('i', $noticeId);
    $chk->execute();
    if (!$chk->get_result()->fetch_assoc()) {
        $chk->close();
        Api::error(404, 'NotFound', 'Notice not found.');
    }
    $chk->close();
}

Api::success(['pinned' => (bool)$pinned]);
