<?php
// =============================================================
//  GET /api/v1/notices/list?archived=1
//
//  Non-expired notices visible to the authenticated account — same
//  audience rule app/notice_ajax.php's get_unread action uses: staff
//  see everything, nurses see audience IN ('nurses','both'), students see
//  audience IN ('students','both'). Same shape app/nurse/notice_board.php
//  and app/student/notice_board.php list, plus each notice's comment
//  count and whether the caller has read it yet.
//
//  `?archived=1` switches from active to archived notices — mirrors
//  app/notice_board.php's own toggle. Staff-only: archived management is
//  a staff concept (app/notice_board.php is the only desktop page with
//  this toggle at all), so it's silently ignored for nurse/student
//  readers, who always see active notices regardless of the query param.
//
//  Each row also carries posted_by/can_edit/can_delete/can_archive/
//  can_pin so the client can show the right management actions without
//  re-deriving the ownership+role rule notices/update.php,
//  notices/delete.php, notices/archive.php, and notices/pin.php each
//  enforce server-side anyway — computed here once, matching them exactly.
// =============================================================

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

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

$account = api_authenticate();
$table   = $account->getTable();
$userId  = $account->getId();

$readerType = match ($table) {
    'users'             => 'staff',
    'rotation_nurses'   => 'nurse',
    'clinical_students' => 'student',
};
$audienceFilter = match ($readerType) {
    'staff'   => "'staff','nurses','students','both'",
    'nurse'   => "'nurses','both'",
    'student' => "'students','both'",
};

$isAdmin      = $readerType === 'staff' && in_array($account->getUserType(), ['Admin', 'Chief_Preceptor'], true);
$showArchived = $readerType === 'staff' && !empty($_GET['archived']);
$statusFilter = $showArchived ? 'archived' : 'active';

$sql = "
    SELECT n.id, n.title, n.body, n.audience, n.priority, n.is_pinned, n.attachment,
           n.posted_by, n.posted_by_name, n.posted_by_role, n.expires_at, n.created_at,
           EXISTS (
               SELECT 1 FROM notice_reads nr
               WHERE nr.notice_id = n.id AND nr.reader_id = ? AND nr.reader_type = ?
           ) AS is_read,
           (SELECT COUNT(*) FROM notice_comments nc WHERE nc.notice_id = n.id) AS comment_count
    FROM notices n
    WHERE n.audience IN ({$audienceFilter})
      AND n.status = ?
      AND (n.expires_at IS NULL OR n.expires_at >= CURDATE())
    ORDER BY n.is_pinned DESC, n.created_at DESC
    LIMIT 200
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iss', $userId, $readerType, $statusFilter);
$stmt->execute();
$notices = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

foreach ($notices as &$n) {
    $n['is_read']       = (bool)$n['is_read'];
    $n['is_pinned']      = (bool)$n['is_pinned'];
    $n['comment_count'] = (int)$n['comment_count'];
    $canManage           = $isAdmin || (int)$n['posted_by'] === $userId;
    $n['can_edit']       = $canManage;
    $n['can_delete']     = $canManage;
    $n['can_archive']    = $canManage;
    $n['can_pin']        = $isAdmin;
    unset($n['posted_by']); // internal only — not needed once the flags above are derived
}
unset($n);

$unread = count(array_filter($notices, fn($n) => !$n['is_read']));

Api::success(['notices' => $notices, 'unread_count' => $unread, 'showing_archived' => $showArchived]);
