<?php

namespace RtmMail\Actions\Handlers;

use RtmMail\Logger;
use RtmMail\Utils\LoggerUtils;

class SaveGeneralSettingsAction extends AbstractActionHandler
{

    public function __construct()
    {
        parent::__construct('save_settings', 'rtm_mail_save_settings');
    }

    public function handleAction($settings = []): array
    {
        if (! $this->verifyNonce()) {
            return [
                'success' => false,
                'message' => __('Invalid nonce!', 'rtm-mail'),
            ];
        }

        // Retrieve the previous settings to check for changes later
        $prev_settings = get_option('rtm_mail_settings', []);

        // Extract each setting from the passed $settings array, using sensible defaults where necessary.
        $block_mails          = $settings['block_mails'] ?? false;
        $edit_mails           = $settings['edit_mails'] ?? false;
        $sender_options       = $settings['sender_options'] ?? [ 'title' => '', 'address' => '' ];
        $mail_capability      = $settings['mail_capability'] ?? '';
        $cron_schedule        = $settings['mail_cron_schedule'] ?? '';
        $clear_deleted_events = $settings['clear_deleted_events'] ?? false;
        $cron_enabled         = $settings['mail_cron_enabled'] ?? false; // Make sure to include this in your AJAX submission

        // Processing 'option_email' and 'outgoing_type' into a structured array of addresses
        $addresses = [];
        if (! empty($settings['option_email']) && is_array($settings['option_email'])) {
            foreach ($settings['option_email'] as $index => $address) {
                if (! empty($address)) { // Ensure the address is not empty
                    $addresses[] = [
                        'address' => sanitize_text_field($address),
                        'type'    => $settings['outgoing_type'][ $index ] ?? '',
                    ];
                }
            }
        }

        // Check for changes in cron settings to manage scheduled events accordingly
        if ($cron_enabled !== ( $prev_settings['mail_cron_enabled'] ?? false ) || $cron_schedule !== ( $prev_settings['mail_cron_schedule'] ?? 'hourly' )) {
            wp_clear_scheduled_hook('rtm_mail_send_caught_logs');
            if ($cron_enabled) {
                wp_schedule_event(time(), $cron_schedule, 'rtm_mail_send_caught_logs');
            }
        }

        // Consolidate all settings into an array to save
        $updated_settings = [
            'block_mails'          => $block_mails,
            'edit_mails'           => $edit_mails,
            'addresses'            => $addresses,
            'sender_options'       => $sender_options,
            'mail_capability'      => $mail_capability,
            'clear_deleted_events' => $clear_deleted_events,
            'mail_cron_enabled'    => $cron_enabled,
            'mail_cron_schedule'   => $cron_schedule,
        ];

        // Update the settings in the database
        update_option('rtm_mail_settings', $updated_settings);

        // Optional: Log the change
        $user = LoggerUtils::getUser();
        Logger::info(
            "Settings saved",
            "{$user} has changed the settings of the plugin",
            'SaveGeneralSettingsAction::handleAction',
            'Settings',
            [
                "user"             => $user,
                "changed_settings" => array_diff_assoc($updated_settings, $prev_settings)
            ]
        );

        // Return a success response
        return [
            'success' => true,
            'message' => __('Settings updated successfully!', 'rtm-mail'),
        ];
    }
}
