<?php
/**
 * Notifications settings controller.
 *
 * @package FleekDash\Controllers
 */

namespace FleekDash\Controllers;

use FleekDash\Core\UpdateChecker;
use FleekDash\Core\UpdatePreferences;
use FleekDash\Services\ResponseService;
use WP_REST_Request;

defined('ABSPATH') || exit;

if (!class_exists(UpdateChecker::class)) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/UpdateChecker.php';
}

class NotificationsSettingsController
{
    public function getSettings(WP_REST_Request $_request) // NOSONAR php:S1172 - WP REST callback signature
    {
        $response = null;

        try {
            $settings = UpdatePreferences::getSettings();
            $response = ResponseService::success('Notification settings retrieved successfully', $settings);
        } catch (\Throwable $exception) {
            $response = ResponseService::error(
                'Failed to retrieve notification settings',
                ['error' => $exception->getMessage()],
                500
            );
        }

        return $response;
    }

    public function updateSettings(WP_REST_Request $request)
    {
        $response = null;

        try {
            $payload = $request->get_json_params();
            $settings = UpdatePreferences::getSettings();
            $canUpdate = \is_array($payload);

            if ($canUpdate) {
                if (\array_key_exists('receive_prerelease_updates', $payload)) {
                    $settings['receive_prerelease_updates'] = (bool) $payload['receive_prerelease_updates'];
                }

                if (\array_key_exists('blocked_plugin_updates', $payload) && \is_array($payload['blocked_plugin_updates'])) {
                    $settings['blocked_plugin_updates'] = $payload['blocked_plugin_updates'];
                }

                $savedSettings = UpdatePreferences::saveSettings($settings);
                UpdateChecker::clearCachedUpdatePayloads();
                \delete_site_transient('update_plugins');
                $response = ResponseService::success('Notification settings updated successfully', $savedSettings);
            } else {
                $response = ResponseService::error('Invalid notification settings payload', null, 400);
            }
        } catch (\Throwable $exception) {
            $response = ResponseService::error(
                'Failed to update notification settings',
                ['error' => $exception->getMessage()],
                500
            );
        }

        return $response;
    }
}
