<?php
// ============================================================
//  MediCore — Notifications API
//  File: api/notifications.php
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/notify.php';
require_login();
session_write_close();

ensure_topbar_tables();

header('Content-Type: application/json');

$body   = json_decode(file_get_contents('php://input'), true) ?? [];
$action = trim($body['action'] ?? '');

try {
    match ($action) {
        'list'           => api_list($body),
        'unread_count'   => api_unread_count($body),
        'mark_read'      => api_mark_read($body),
        'mark_all_read'  => api_mark_all_read($body),
        'delete'         => api_delete($body),
        default          => fail('Unknown action')
    };
} catch (Throwable $e) {
    fail($e->getMessage());
}

// ── List (paginated) ─────────────────────────────────────────
function api_list(array $b): void {
    $uid = current_user_id();

    $unreadOnly = !empty($b['unread_only']);
    $where  = ['user_id = ?'];
    $params = [$uid];
    if ($unreadOnly) $where[] = 'is_read = 0';
    $wSql = implode(' AND ', $where);

    $page     = max(1, (int)($b['page'] ?? 1));
    $pageSize = max(5, min(100, (int)($b['page_size'] ?? 20)));
    $offset   = ($page - 1) * $pageSize;

    $total = (int) db_val("SELECT COUNT(*) FROM notifications WHERE $wSql", $params);
    $rows  = db_rows(
        "SELECT id, type, icon, title, message, link, is_read, created_at
           FROM notifications
          WHERE $wSql
       ORDER BY created_at DESC
          LIMIT $pageSize OFFSET $offset",
        $params
    );

    ok([
        'data'        => $rows,
        'page'        => $page,
        'total'       => $total,
        'total_pages' => (int) max(1, ceil($total / $pageSize)),
        'unread'      => (int) db_val("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0", [$uid]),
    ]);
}

// ── Unread count only (cheap, for badge polling) ────────────────
function api_unread_count(array $b): void {
    $uid = current_user_id();
    ok(['unread' => (int) db_val(
        "SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0", [$uid]
    )]);
}

// ── Mark one as read ──────────────────────────────────────────
function api_mark_read(array $b): void {
    $uid = current_user_id();
    $id  = (int)($b['id'] ?? 0);
    if (!$id) fail('Missing id');

    db_run(
        "UPDATE notifications SET is_read = 1, read_at = NOW()
          WHERE id = ? AND user_id = ?",
        [$id, $uid]
    );
    ok();
}

// ── Mark all as read ──────────────────────────────────────────
function api_mark_all_read(array $b): void {
    $uid = current_user_id();
    db_run(
        "UPDATE notifications SET is_read = 1, read_at = NOW()
          WHERE user_id = ? AND is_read = 0",
        [$uid]
    );
    ok();
}

// ── Delete / dismiss ────────────────────────────────────────────
function api_delete(array $b): void {
    $uid = current_user_id();
    $id  = (int)($b['id'] ?? 0);
    if (!$id) fail('Missing id');

    db_run("DELETE FROM notifications WHERE id = ? AND user_id = ?", [$id, $uid]);
    ok();
}

function ok(array $extra = []): void {
    echo json_encode(array_merge(['success' => true], $extra));
    exit;
}
function fail(string $msg): never {
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}
