<?php
// =============================================================
//  POST /api/v1/notices/archive
//
//  Mobile equivalent of app/notice_ajax.php's archive_notice action —
//  toggles a notice between 'active' and 'archived' (soft, reversible;
//  distinct from notices/delete.php which is permanent). Same gating as
//  notices/delete.php: any staff role may call this, but only
//  Admin/Chief_Preceptor can archive/restore any notice, others only
//  their own.
//
//  Body: { "notice_id": NN, "status": "active"|"archived" }
// =============================================================

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);
$status   = ((string)($body['status'] ?? 'archived')) === 'active' ? 'active' : 'archived';
if (!$noticeId) Api::error(422, 'ValidationError', 'notice_id is required');

// Ownership check via a SELECT first, same as notices/update.php — an
// UPDATE's affected_rows is 0 both when the row doesn't match (not
// found/not owned) AND when it already holds the target status, so it
// can't distinguish "denied" from "already there" on its own.
$chk = $conn->prepare('SELECT posted_by 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 archive your own notices.');
}

$stmt = $conn->prepare('UPDATE notices SET status = ? WHERE id = ?');
$stmt->bind_param('si', $status, $noticeId);
$stmt->execute();
$stmt->close();

Api::success(['status' => $status, 'message' => $status === 'archived' ? 'Archived.' : 'Restored.']);
