<?php
require_once __DIR__ . '/../includes/mj_v304_bootstrap.php';
header('Content-Type: application/json; charset=utf-8');
try {
    $userType = mjv304_is_admin() ? 'admin' : 'user';
    $userId = mjv304_is_admin() ? null : mjv304_current_user_id();
    if ($userType === 'user' && $userId <= 0) { throw new RuntimeException('Not logged in'); }
    $action = $_POST['action'] ?? 'list';
    if ($action === 'read') {
        mjv304_mark_notification_read((int)($_POST['id'] ?? 0), $userType, $userId);
    } elseif ($action === 'read_all') {
        if ($userType === 'admin') {
            mjv304_execute("UPDATE mj_notifications SET is_read=1, read_at=NOW() WHERE user_type='admin' AND is_read=0");
        } else {
            mjv304_execute("UPDATE mj_notifications SET is_read=1, read_at=NOW() WHERE user_type='user' AND user_id=? AND is_read=0", [$userId]);
        }
    }
    if ($userType === 'admin') {
        $items = mjv304_fetch_all("SELECT id,title,message,type,link,is_read,DATE_FORMAT(created_at,'%d %b %Y %H:%i') created_at FROM mj_notifications WHERE user_type='admin' ORDER BY created_at DESC,id DESC LIMIT 20");
        $unread = (int)mjv304_fetch_value("SELECT COUNT(*) FROM mj_notifications WHERE user_type='admin' AND is_read=0");
    } else {
        $items = mjv304_fetch_all("SELECT id,title,message,type,link,is_read,DATE_FORMAT(created_at,'%d %b %Y %H:%i') created_at FROM mj_notifications WHERE user_type='user' AND user_id=? ORDER BY created_at DESC,id DESC LIMIT 20", [$userId]);
        $unread = (int)mjv304_fetch_value("SELECT COUNT(*) FROM mj_notifications WHERE user_type='user' AND user_id=? AND is_read=0", [$userId]);
    }
    echo json_encode(['ok'=>true,'unread'=>$unread,'items'=>$items]);
} catch (Throwable $e) {
    http_response_code(200);
    echo json_encode(['ok'=>false,'error'=>$e->getMessage(),'unread'=>0,'items'=>[]]);
}
