<?php

namespace RtmMail;

use RtmMailVendor\Dependencies\PHPMailer\PHPMailer;
use RtmMail\AjaxAction\DeleteLogAjaxAction;
use RtmMail\AjaxAction\DeleteMultipleAjaxAction;
use RtmMail\AjaxAction\DkimLookupAjaxAction;
use RtmMail\AjaxAction\EditLogAjaxAction;
use RtmMail\AjaxAction\QueueLogsAjaxAction;
use RtmMail\AjaxAction\RemoveQueueAjaxAction;
use RtmMail\AjaxAction\ResendMailAjaxAction;
use RtmMail\AjaxAction\SaveGeneralSettingsAjaxAction;
use RtmMail\AjaxAction\SaveSmtpSettingsAjaxAction;
use RtmMail\AjaxAction\SendLogAjaxAction;
use RtmMail\AjaxAction\SendMultipleAjaxAction;
use RtmMail\AjaxAction\SpfLookupAjaxAction;
use RtmMail\AjaxAction\TestMailAjaxAction;
use RtmMail\AjaxAction\TestSmtpSettingsAjaxAction;
use RtmMail\Mailing\Providers\SmtpHandler;
use RtmMail\Pages\Dashboard;
use RtmMail\Pages\Details;
use RtmMail\Pages\EventDetails;
use RtmMail\Pages\Events;
use RtmMail\Pages\MailSMTP;
use RtmMail\Pages\Overview;
use RtmMail\Pages\Settings;
use RtmMailVendor\Dependencies\WordpressModels\Page\AbstractPage;
use RtmMailVendor\Dependencies\WordpressModels\Traits\SingletonTrait;

/**
 * Core - handles all plugin initialization
 */
class Core
{
    use SingletonTrait;

    /**
     * @var array<string, AbstractPage>
     */
    private array $pages;

    private CustomMailer $customMailer;
    private ?Migration $migration = null; //
    private LogHandler $logHandler;


    /**
     * __construct - methods that need to be executed on object creation
     */
    public function __construct()
    {
        $settings        = get_option('rtm_mail_settings') ?? [];
        $mail_capability = $settings['mail_capability'] ?? 'manage_options';

        $this->customMailer = new CustomMailer();

        //Outside navbar
        new Details($mail_capability);
        new EventDetails();

        $pagesArray = [
            new Dashboard($mail_capability),
            new Overview($mail_capability),
            new Settings(),
            new MailSMTP(),
            new Events(),
        ];
        // reg ajax handlers
        $this->registerAjaxHandlers();

        $this->pages = array_reduce(
            $pagesArray,
            function (array $carry, AbstractPage $page) {
                $carry[ $page->getPageId() ] = $page;

                return $carry;
            },
            []
        );

        // Initialize Logger
        $this->logHandler = new LogHandler();

        $this->mailer = new Mailer();

        // Apply all filters
        $this->addFilters();
        // Add all actions for initialization
        $this->addActions();
    }

    /**
     * add_filters - all filters that need to be executed
     */
    private function addFilters(): void
    {
        add_filter('query_vars', [ $this, 'setCustomQueryVars' ]);
        add_filter('generate_rewrite_rules', [ $this, 'setCustomRewriteRules' ]);
        add_filter('admin_footer_text', [ $this, 'displayFooterText' ]);
    }

    /**
     * add_actions - all actions that need to be executed
     */
    private function addActions(): void
    {
        add_action('admin_init', [ $this, 'init' ]);
        add_action('plugins_loaded', [ $this, 'checkMigrations' ]);
        add_action('admin_footer', [ $this, 'displayFooter' ]);
        add_action('wp_mail_failed', [ $this->customMailer, 'mailError' ], PHP_INT_MAX);
        add_action('rtm_mail_send_log', [ $this->customMailer, 'sendMail' ], 10, 1);
        add_action('rtm_mail_send_caught_logs', [ $this->customMailer, 'sendCaughtLogs' ]);
        add_action('parse_request', [ $this->customMailer, 'setReadRequest' ]);
        add_action('phpmailer_init', [ $this, 'initSmtp' ], PHP_INT_MAX);
        add_action('rtm-mail.log', [ $this->logHandler, 'write' ]);

    }

    /**
     * init - initialize plugin
     */
    public function init(): void
    {
        load_plugin_textdomain('rtm-mail', false, RTM_MAIL_PLUGIN_PATH . '/assets/languages');
    }

    /**
     * activate - callback for activation hook
     */
    public function activate(): void
    {
        if (class_exists('WPMailSMTP\Core')) {
            add_action('admin_notices', function () {
                echo '<div class="notice notice-warning"> ';
                echo '<p><strong>WP Mail Logger: </strong>';
                echo __('You are currently using <code>WP-Mail-SMTP</code> which may conflict with the sender options in this plugin.', 'rtm-mail');
                echo '</p>';
                echo '</div>';
            });
        }
        update_option('rtm_mail_settings', [
            'block_mails'          => false,
            'edit_mails'           => true,
            'clear_deleted_events' => true,
            'mail_capability'      => 'manage_options',
            'addresses'            => [],
            'sender_options'       => [
                'title'   => '',
                'address' => '',
            ],
        ]);

        update_option('rtm_mail_smtp_settings', [
            'smtp_enabled'   => false,
            'host'           => '',
            'encryption'     => 'none',
            'port'           => 0,
            'authentication' => true,
            'username'       => '',
            'password'       => '',
        ]);

        // Check for migrations when starting the plugin
        $this->migration = new Migration();
        $this->migration->check();
    }

    /**
     * deactivate - callback for deactivation hook
     */
    public function deactivate(): void
    {
        delete_option('rtm_mail_settings');
        wp_clear_scheduled_hook('rtm_mail_send_caught_logs');
        wp_clear_scheduled_hook('rtm_mail_send_log');
    }

    /**
     * check_migrations - Check for update changes
     */
    public function checkMigrations(): void
    {
        if ($this->migration === null) {
            $this->migration = new Migration(RTM_MAIL_VERSION);
        }
        $this->migration->check();
    }

    /**
     * display_footer - add RTM Business logo to footer
     */
    public function displayFooter(): void
    {
        // Check if user is on one of the rtm-mail pages

        echo '<div class="rtm-mail-footer">';
        echo '<div class="rtm-mail-logo"><a href="https://www.rtmbusiness.nl/?utm_source=rtm-mail-plugin&utm_medium=footer&utm_campaign=mail-plugin" target="_blank"><img src="' . RTM_MAIL_PLUGIN_URL . 'assets/images/rtm-logo.png" alt="rtm-logo" /></a></div>';
        echo '</div>';
    }

    /**
     * display_footer_text - change the admin footer text
     */
    public function displayFooterText(string $text): string
    {
        return sprintf(__('Thanks for using WP Mail Logger Plugin!', 'rtm-mail'), RTM_MAIL_PRO_SITE . '#contact');
    }

    public function setCustomQueryVars(array $query_vars): array
    {
        $query_vars[] = 'rtm_mail_read';
        $query_vars[] = 'log_id';
        $query_vars[] = 'address';

        return $query_vars;
    }

    public function setCustomRewriteRules($wp_rewrite): array
    {
        $custom_rule       = [
            '^trackmail/([^/]+)/([^/]+)/?$' => 'index.php?rtm_mail_read=success&log_id=$matches[1]&address=$matches[2]',
        ];
        $wp_rewrite->rules = $custom_rule + $wp_rewrite->rules;

        return $wp_rewrite->rules;
    }


    /**
     * render_page_header - renders the page header for every page
     */


    public function initSmtp($phpMailer): void
    {
        $smtpSettings = get_option('rtm_mail_smtp_settings', []);
        $smtpEnabled  = $smtpSettings['smtp_enabled'] ?? false;

        if (! $smtpEnabled || ( $smtpSettings['smtp_provider'] ?? '' ) !== 'other') {
            return;
        }

        $smtpHandler = SmtpHandler::instance();
        $settings    = $smtpHandler->getSmtpSettings();

        $encryption_key = get_option('rtm_mail_smtp_key', false);

        $phpMailer->isSMTP();
        $phpMailer->Host = $settings['other_smtp_host'];
        $phpMailer->Port = $settings['other_smtp_port'];

        if ($settings['other_smtp_encryption'] !== 'none') {
            $phpMailer->SMTPSecure = $settings['other_smtp_encryption'];
        }

        if ($settings['other_smtp_authentication']) {
            if (empty($encryption_key)) {
                $encryption_key = wp_salt();
                update_option('rtm_mail_smtp_key', $encryption_key);
            }

            $phpMailer->SMTPAuth = true;
            $phpMailer->Username = $settings['other_smtp_username'];
            $phpMailer->Password = Cryptor::decrypt($settings['other_smtp_password'], $encryption_key);
        }
    }

    /**
     * @return array<string, AbstractPage>
     */
    public function getPages(): array
    {
        return $this->pages;
    }

    private function registerAjaxHandlers(): void
    {
        // Instantiate the AJAX action handlers
        $deleteLogHandler           = new DeleteLogAjaxAction();
        $sendTestMailHandler        = new TestMailAjaxAction();
        $queueLogsHandler           = new QueueLogsAjaxAction();
        $dequeueLogsHandler         = new RemoveQueueAjaxAction();
        $deleteMultipleHandler      = new DeleteMultipleAjaxAction();
        $sendMultipleHandler        = new SendMultipleAjaxAction();
        $sendLogHandler             = new SendLogAjaxAction();
        $resendMailHandler          = new ResendMailAjaxAction();
        $saveGeneralSettingsHandler = new SaveGeneralSettingsAjaxAction();
        $saveSmtpSettingsHandler    = new SaveSmtpSettingsAjaxAction();
        $editLogHandler             = new EditLogAjaxAction();
        $testSmtpSettingHandler     = new TestSmtpSettingsAjaxAction();
        $testDnsHandler = new SpfLookupAjaxAction();
        $testDkimHandler = new DkimLookupAjaxAction();

        // Register AJAX actions, passing the handler methods as callbacks
        add_action('wp_ajax_delete_log', [ $deleteLogHandler, 'handleAction' ]);
        add_action('wp_ajax_test_mail', [ $sendTestMailHandler, 'handleAction' ]);
        add_action('wp_ajax_queue_logs', [ $queueLogsHandler, 'handleAction' ]);
        add_action('wp_ajax_dequeue_logs', [ $dequeueLogsHandler, 'handleAction' ]);
        add_action('wp_ajax_delete_log_rows', [ $deleteMultipleHandler, 'handleAction' ]);
        add_action('wp_ajax_send_log_rows', [ $sendMultipleHandler, 'handleAction' ]);
        add_action('wp_ajax_resend_mail', [ $resendMailHandler, 'handleAction' ]);
        add_action('wp_ajax_save_settings', [ $saveGeneralSettingsHandler, 'handleAction' ]);
        add_action('wp_ajax_savesmtp_settings', [ $saveSmtpSettingsHandler, 'handleAction' ]);
        add_action('wp_ajax_edit_log', [ $editLogHandler, 'handleAction' ]);
        add_action('wp_ajax_test_smtp_settings', [ $testSmtpSettingHandler, 'handleAction' ]);
        add_action('wp_ajax_test_dns_settings', [$testDnsHandler, 'handleAction']);
        add_action('wp_ajax_test_dkim_settings', [$testDkimHandler, 'handleAction']);
    }
}
