<?php
require_once '../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/Logger.php'; // COVERAGE
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$action = $_GET['action'] ?? 'list';
$b      = json_decode(file_get_contents('php://input'), true) ?? [];

if ($action === 'list') {
    try {
        $st = db()->prepare(
            'SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 50'
        );
        $st->execute([$u['id']]);
        $notes = $st->fetchAll();
        $unread = (int)db()->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0')->execute([$u['id']]) ?: 0;
        $unread_st = db()->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0');
        $unread_st->execute([$u['id']]);
        $unread = (int)$unread_st->fetchColumn();
        json_response(['success' => true, 'notifications' => $notes, 'unread' => $unread]);
    } catch (Throwable $e) {
        json_response(['success' => true, 'notifications' => [], 'unread' => 0]);
    }
}

if ($action === 'mark_read') {
    try {
        db()->prepare('UPDATE notifications SET is_read = 1 WHERE user_id = ?')->execute([$u['id']]);
        json_response(['success' => true]);
    } catch (Throwable $e) {
        json_response(['success' => false]);
    }
}

if ($action === 'update_prefs') {
    $prefs = [
        'notify_pulse'   => (int)($b['notify_pulse']   ?? 1),
        'notify_family'  => (int)($b['notify_family']  ?? 1),
        'notify_market'  => (int)($b['notify_market']  ?? 1),
        'notify_academy' => (int)($b['notify_academy'] ?? 1),
    ];
    try {
        db()->prepare('UPDATE users SET notify_pulse=?, notify_family=?, notify_market=?, notify_academy=? WHERE id=?')
            ->execute(array_values($prefs) + [$u['id']]);
        json_response(['success' => true, 'message' => 'تم حفظ تفضيلات الإشعارات']);
    } catch (Throwable $e) {
        json_response(['success' => false]);
    }
}

Kernel::fail('unknown_action', '', 400);
