<?php

namespace EasyLinkAutomations\HTTP\Controllers;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Config;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

/**
 * Handles plugin settings retrieval and updates.
 */
final class SettingsController
{
    /**
     * Default settings structure.
     */
    private static function defaults(): array
    {
        return [
            'email_notifications' => false,
            'notification_email'  => get_option('admin_email', ''),
            'keep_logs'           => true,
            'log_retention_days'  => 30,
        ];
    }

    public function getSettings(Request $request): Response
    {
        $saved = Config::getOption('settings', []);
        $settings = array_merge(self::defaults(), $saved);

        return Response::success([
            'settings' => $settings,
            'version'  => Config::VERSION,
        ]);
    }

    public function updateSettings(Request $request): Response
    {
        $settings = $request->get('settings', []);

        // Decode JSON string if needed
        if (is_string($settings)) {
            $settings = json_decode($settings, true) ?? [];
        }

        // Sanitize settings
        $sanitized = [
            'email_notifications' => !empty($settings['email_notifications']),
            'notification_email'  => sanitize_email($settings['notification_email'] ?? get_option('admin_email', '')),
            'keep_logs'           => !empty($settings['keep_logs']),
            'log_retention_days'  => max(1, min(365, (int) ($settings['log_retention_days'] ?? 30))),
        ];

        Config::updateOption('settings', $sanitized);

        return Response::success([
            'message'  => __('Settings updated successfully', 'easylink-automations'),
            'settings' => $sanitized,
        ]);
    }
}
