<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../services/notifications/NotificationService.php';

require_login();
header('Content-Type: application/json; charset=utf-8');

try {
    $service = new NotificationService(db());
    $userId = current_user_id();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $eventType = trim($_POST['event_type'] ?? '');
        $emailEnabled = isset($_POST['email_enabled']) && (string)$_POST['email_enabled'] === '1';
        $ok = $service->setEmailPreference($userId, $eventType, $emailEnabled);
        echo json_encode(['success' => $ok, 'preferences' => $service->preferences($userId)], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    echo json_encode(['success' => true, 'preferences' => $service->preferences($userId)], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
