<?php
// =============================================================
//  POST /api/v1/notices/create
//
//  Mobile equivalent of app/notice_ajax.php's post_notice action — same
//  audience/priority validation, same department/unit auto-scoping for
//  Preceptor/Nurse_Manager/In_Charge, same email blast via
//  resolveNoticeRecipients()/EmailServiceProvider. Attachment upload
//  isn't supported here yet (multipart handling is a mobile-side/API
//  design decision better made alongside the Flutter client than guessed
//  at now) — text notices only for this pass.
//
//  Body: { "title": "...", "body": "...", "audience"?: "nurses"|"students"|"both"|"staff",
//          "priority"?: "normal"|"important"|"urgent", "expires"?: "YYYY-MM-DD", "pinned"?: bool }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/notice_helpers.php';
require_once __DIR__ . '/../../../include/account_helpers.php';
require_once __DIR__ . '/../../../services/EmailServiceProvider.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);

$body     = Api::body();
$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;
$pinned   = ($isAdmin && !empty($body['pinned'])) ? 1 : 0;

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');
}

$scopeDept  = null;
$scopeUnits = null;
if (in_array($usertype, ['Preceptor', 'Nurse_Manager'], true)) {
    $scopeDept = !empty($_SESSION['department_id']) ? (int)$_SESSION['department_id'] : null;
} elseif ($usertype === 'In_Charge') {
    $units = array_filter(array_map('intval', (array)($_SESSION['unit_ids'] ?? [])));
    $scopeUnits = !empty($units) ? implode(',', $units) : null;
}

$roleLabel = str_replace('_', ' ', $usertype);
$fullName  = $account->getFullName();
$userId    = $account->getId();

$stmt = $conn->prepare("
    INSERT INTO notices
        (title, body, audience, scope_dept_id, scope_unit_ids, priority,
         is_pinned, posted_by, posted_by_name, posted_by_role, expires_at, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())
");
$stmt->bind_param(
    // title(s) body(s) audience(s) scope_dept_id(i) scope_unit_ids(s) priority(s)
    // is_pinned(i) posted_by(i) posted_by_name(s) posted_by_role(s) expires_at(s)
    'sssissiisss',
    $title, $noticeBody, $audience, $scopeDept, $scopeUnits, $priority,
    $pinned, $userId, $fullName, $roleLabel, $expires
);
$stmt->execute();
$noticeId = $conn->insert_id;
$stmt->close();

try {
    $recipients = resolveNoticeRecipients($conn, $audience, $scopeDept, $scopeUnits);
    if (!empty($recipients)) {
        $heading  = ($priority === 'urgent' ? '[URGENT] ' : ($priority === 'important' ? '[Important] ' : '')) . $title;
        $bodyHtml = accountEmailTemplate($heading, [
            nl2br(htmlspecialchars($noticeBody)),
            "Posted by <strong>{$fullName}</strong> ({$roleLabel})",
            'View it on the Notice Board at <a href="' . htmlspecialchars(env('APP_URL', 'https://nrms.sthportal.com')) . '/login">' . htmlspecialchars(preg_replace('#^https?://#', '', env('APP_URL', 'nrms.sthportal.com'))) . '</a>.',
        ]);
        (new EmailServiceProvider())->sendBulkEmail($recipients, 'STH NRMS Notice: ' . $title, $bodyHtml);
    }
} catch (Exception $e) {
    error_log('API notice email blast error: ' . $e->getMessage());
}

Api::success(['notice_id' => $noticeId, 'message' => 'Notice posted successfully.'], [], 201);
