<?php
// Notifications controller — reads from notification_inbox
$u = require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();

if ($method === 'GET') {
    if (hv4_table_exists('notification_inbox')) {
        $s = db()->prepare('SELECT * FROM notification_inbox WHERE user_id = ? OR user_id IS NULL ORDER BY created_at DESC LIMIT 50');
        $s->execute([$u['id']]);
    } else {
        // fallback to old notifications table
        $s = db()->prepare('SELECT * FROM notifications WHERE user_id IS NULL OR user_id=? ORDER BY created_at DESC LIMIT 50');
        $s->execute([$u['id']]);
    }
    json_ok($s->fetchAll());
}

csrf_check();

if ($method === 'PUT') {
    // Mark all as read
    if (hv4_table_exists('notification_inbox')) {
        db()->prepare('UPDATE notification_inbox SET read_at = NOW() WHERE (user_id = ? OR user_id IS NULL) AND read_at IS NULL')->execute([$u['id']]);
    } else {
        db()->prepare('UPDATE notifications SET is_read=1 WHERE (user_id IS NULL OR user_id=?)')->execute([$u['id']]);
    }
    json_ok([], 'All marked as read');
}

json_error('Method not allowed', 405);
