<?php

namespace RtmMail\Actions\Handlers;

use RtmMail\Cryptor;

class SaveSmtpSettingsAction extends AbstractActionHandler
{
    public function __construct()
    {
        parent::__construct('save_settings', 'rtm_mail_save_smtp');
    }

    /**
     * Handles the action of saving SMTP settings.
     *
     * @param array $data The SMTP settings data.
     * @return array The result of the operation.
     */
    public function handleAction(array $data = []): array
    {
        if (! $this->verifyNonce()) {
            return [
                'success' => false,
                'message' => __('Nonce verification failed', 'rtm-mail'),
            ];
        }

        $encryption_key = get_option('rtm_mail_smtp_key', false);
        if (empty($encryption_key)) {
            $encryption_key = wp_salt();
            update_option('rtm_mail_smtp_key', $encryption_key);
        }

        $smtp_settings = [
            'smtp_enabled'  => filter_var($data['smtp_enabled'] ?? false, FILTER_VALIDATE_BOOLEAN),
            'smtp_provider' => $data['smtp_provider'] ?? '',
        ];

        $settings = $data['smtp_setting'] ?? [];
        foreach ($settings as $type => $setting) {
            foreach ($setting as $key => $option) {
                $settings[$type][$key] = str_contains($key, 'password') ? Cryptor::encrypt($option, $encryption_key) : $option;
            }
        }

        $smtp_settings['smtp_settings'] = $settings;

        // Save to option table
        update_option('rtm_mail_smtp_settings', $smtp_settings);

        return [
            'success' => true,
            'message' => __('Settings successfully saved!', 'rtm-mail'),
        ];
    }
}
