<?php

namespace RtmMail;

use RtmMail\Mailing\Providers\SmtpHandler;

/**
 * Core - handles all plugin initialization
 */
class Core
{
    private static $pages;

    private $catcher;
    private $listener;
    private $migration;

    /**
     * __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';
        // Set dashboard variable to prevent 2 dashboard pages
        $dashboard = new Dashboard();

        // Set plugin pages
        self::$pages = [
            'main' => [ // Main page (Dashboard)
                'page' => $dashboard,
                'page_title' => __('WP Mail Logger - Dashboard', 'rtm-mail'),
                'menu_title' => 'WP Mail Logger',
                'capability' => $mail_capability,
                'menu_slug' => 'rtm-mail-dashboard',
                'icon_url' => 'dashicons-email-alt',
            ],
            'dashboard' => [ // Sub menu page (Dashboard)
                'page' => $dashboard,
                'parent_slug' => 'rtm-mail-dashboard',
                'page_title' => __('WP Mail Logger - Dashboard', 'rtm-mail'),
                'menu_title' => __('Dashboard', 'rtm-mail'),
                'capability' => $mail_capability,
                'menu_slug' => 'rtm-mail-dashboard',
            ],
            'overview' => [ // Sub menu page (Overview)
                'page' => new Overview(),
                'parent_slug' => 'rtm-mail-dashboard',
                'page_title' => __('WP Mail Logger - Overview', 'rtm-mail'),
                'menu_title' => __('Overview', 'rtm-mail'),
                'capability' => $mail_capability,
                'menu_slug' => 'rtm-mail-overview',
            ],
            'settings' => [ // Sub menu page (Settings)
                'page' => new Settings(),
                'parent_slug' => 'rtm-mail-dashboard',
                'page_title' => __('WP Mail Logger - Settings', 'rtm-mail'),
                'menu_title' => __('Settings', 'rtm-mail'),
                'capability' => 'manage_options',
                'menu_slug' => 'rtm-mail-settings',
            ],
            'mailsmtp' => [ // Sub menu page (Settings)
                'page' => new MailSMTP(),
                'parent_slug' => 'rtm-mail-dashboard',
                'page_title' => __('WP Mail Logger - Mail SMTP', 'rtm-mail'),
                'menu_title' => __('Mail SMTP', 'rtm-mail'),
                'capability' => 'manage_options',
                'menu_slug' => 'rtm-mail-mailsmtp',
            ],
            'events' => [ // Sub menu page (Debug Events)
                'page' => new Events(),
                'parent_slug' => 'rtm-mail-dashboard',
                'page_title' => __('WP Mail Logger - Debug Events', 'rtm-mail'),
                'menu_title' => __('Debug Events', 'rtm-mail'),
                'capability' => 'manage_options',
                'menu_slug' => 'rtm-mail-events',
            ],
            'details' => [ // Hidden sub menu page (Log details)
                'page' => new Details(),
                'parent_slug' => '',
                'page_title' => __('WP Mail Logger - Details', 'rtm-mail'),
                'menu_title' => __('Details', 'rtm-mail'),
                'capability' => $mail_capability,
                'menu_slug' => 'rtm-mail-details',
            ],
            'event_details' => [ // Hidden sub menu page (Event details)
                'page' => new EventDetails(),
                'parent_slug' => '',
                'page_title' => __('WP Mail Logger - Event Details', 'rtm-mail'),
                'menu_title' => __('Details', 'rtm-mail'),
                'capability' => 'manage_options',
                'menu_slug' => 'rtm-mail-event_details',
            ],
        ];

        // Instantiate the Catcher
        $this->catcher = new Catcher();

        // Instantiate error listener
        $this->listener = new EventListener();

        // Set custom Wonolog channel
        add_filter('wonolog.channels', function ($channels) {
            $channels[] = EventListener::CHANNEL_NAME;
            return $channels;
        });
        // Change wonolog folder
        add_filter('wonolog.default-handler-folder', function ($folder) {
            $upload = wp_upload_dir();
            return $upload['basedir'] . '/rtm-mail/logs';
        });

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

    /**
     * add_filters - all filters that need to be executed
     */
    private function add_filters()
    {
        // add the highest priority, so it's the last executed method
        add_filter('wp_mail', [$this->catcher, 'catch_mail'], PHP_INT_MAX);
        // register custom query vars
        add_filter('query_vars', [$this, 'set_custom_query_vars']);
        // register custom rewrite rules
        add_filter('generate_rewrite_rules', [$this, 'set_custom_rewrite_rules']);
        // Admin footer text
        add_filter('admin_footer_text', [$this, 'display_footer_text']);
    }

    /**
     * add_actions - all actions that need to be executed
     */
    private function add_actions()
    {
        add_action('admin_init', [$this, 'init']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('admin_menu', [$this, 'add_pages']);
        add_action('plugins_loaded', [$this, 'check_migrations']);
        add_action('admin_footer', [$this, 'display_footer']);
        add_action('wp_mail_failed', [$this->catcher, 'mail_error'], PHP_INT_MAX);
        add_action('rtm_mail_send_log', [$this->catcher, 'send_mail'], 10, 1);
        add_action('rtm_mail_send_caught_logs', [$this->catcher, 'send_caught_logs']);
        add_action('parse_request', [$this->catcher, 'set_read_request']);
        add_action('phpmailer_init', [$this, 'initSmtp'], PHP_INT_MAX);
        // Event listener hooks
        add_action('rtmmail_migration_failed', [$this->listener, 'migration_failed'], 10, 2);
        add_action('rtmmail_migration_success', [$this->listener, 'migration_success']);
        add_action('rtmmail_send_failed', [$this->listener, 'send_failed'], 10, 2);
        add_action('rtmmail_send_success', [$this->listener, 'send_success']);
        add_action('rtmmail_log_deleted', [$this->listener, 'log_deleted'], 10, 2);
        add_action('rtmmail_log_edited', [$this->listener, 'log_edited'], 10, 2);
        add_action('rtmmail_mail_caught', [$this->listener, 'mail_caught']);
        add_action('rtmmail_mail_queued', [$this->listener, 'mail_queued'], 10, 2);
        add_action('rtmmail_mail_queue_removed', [$this->listener, 'mail_queue_removed']);
        add_action('rtmmail_text_message_failed', [$this->listener, 'text_message_exception'], 10, 2);
    }

    /**** Hook Methods ****/

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

    /**
     * activate - callback for activation hook
     */
    public function activate()
    {
        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()
    {
        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 check_migrations()
    {
        // Check if the migration class is already set and checked
        if ($this->migration === null) {
            $this->migration = new Migration(RTM_MAIL_VERSION);
            $this->migration->check();
        }
    }

    /**
     * add_pages - add the pages to the administrator menu
     */
    public function add_pages()
    {
        foreach (self::$pages as $page => $page_data) {
            if ($page === 'main') {
                add_menu_page($page_data['page_title'], $page_data['menu_title'], $page_data['capability'], $page_data['menu_slug'], [$page_data['page'], 'display'], $page_data['icon_url']);
            } else {
                add_submenu_page($page_data['parent_slug'], $page_data['page_title'], $page_data['menu_title'], $page_data['capability'], $page_data['menu_slug'], [$page_data['page'], 'display']);
            }
        }
    }

    /**
     * display_footer - add RTM Business logo to footer
     */
    public function display_footer()
    {
        // Check if user is on one of the rtm-mail pages
        if ($this->page_check()) {
            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_PATH . 'assets/images/rtm-logo.png" alt="rtm-logo" /></a></div>';
            echo '</div>';
        }
    }

    /**
     * display_footer_text - change the admin footer text
     */
    public function display_footer_text($text)
    {
        // Check if user is on one of the rtm-mail pages
        if ($this->page_check()) {
            $text = sprintf(__('Thanks for using the WP Mail Logger Plugin! If you have any issues please <a href="%s" style="font-weight: 600" target="_blank">contact us</a>!', 'rtm-mail'), RTM_MAIL_PRO_SITE . '#contact');
        }
        return $text;
    }

    public function set_custom_query_vars($query_vars)
    {
        $query_vars[] = 'rtm_mail_read';
        $query_vars[] = 'log_id';
        $query_vars[] = 'address';

        return $query_vars;
    }

    public function set_custom_rewrite_rules($wp_rewrite)
    {
        $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;
    }

    /**
     * enqueue_scripts - enqueues the scripts needed for the plugin
     */
    public function enqueue_scripts()
    {
        // Only load scripts on WP Mail Logger pages
        if ($this->page_check()) {
            // Load fontawesome
            wp_enqueue_style('fontawesome', 'https://use.fontawesome.com/releases/v5.7.0/css/all.css');

            // Load intl-tel-input
            wp_enqueue_style('intlTelInput-css', 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css');
            wp_enqueue_script('intlTelInput-js', 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js', [], false, false);

            // Load custom styling css
            wp_enqueue_style('rtm-mail', RTM_MAIL_PLUGIN_PATH . 'assets/css/style.css');
            wp_register_script('rtm-mail', RTM_MAIL_PLUGIN_PATH . 'dist/bundle.js');
            wp_localize_script('rtm-mail', 'rtm_mail_translation', [
                'type_address' => __('Type an address', 'rtm-mail'),
                'status_sent' => __('Sent', 'rtm-mail'),
                'status_queued' => __('Queued', 'rtm-mail'),
                'time_days' => __('day(s)', 'rtm-mail'),
                'time_hours' => __('hour(s)', 'rtm-mail'),
                'time_minutes' => __('minute(s)', 'rtm-mail'),
                'time_seconds' => __('second(s)', 'rtm-mail'),
                'wp_locale' => get_locale(),
                'wp_timezone' => (str_starts_with(wp_timezone_string(), '+')
                    || str_starts_with(wp_timezone_string(), '-')
                    || is_numeric(substr(wp_timezone_string(), 0, 1))) ? 'UTC' . wp_timezone_string() : wp_timezone_string(),
            ]);
            wp_enqueue_script('rtm-mail');
        }
    }

    /**
     * page_check - Check if the user is on one of the plugins pages
     * @return bool
     */
    private function page_check()
    {
        // Loop through every available page
        foreach (self::$pages as $page_data) {
            // Return true if user is on one of the pages
            if ($page_data['page']->page_check()) {
                return true;
            }
        }
        // Return false when user is on none of the pages
        return false;
    }

    /**
     * render_page_header - renders the page header for every page
     */
    public static function render_page_header($current_page)
    {
?>
        <div class="navbar">
            <div class="nav-logo">
                <img src="<?php echo RTM_MAIL_PLUGIN_PATH; ?>assets/images/logo-icon.png" alt="wp-mail-logger logo"
                     class="logo-icon"/>
                <img src="<?php echo RTM_MAIL_PLUGIN_PATH; ?>assets/images/logo.png" alt="wp-mail-logger logo"
                     class="logo"/>
                <span class="nav-version">v<?php echo RTM_MAIL_VERSION; ?></span>
            </div>
            <a href="#" class="nav-link mobile-link-toggle"><i class="fas fa-bars"></i></a>
            <div class="nav-menu-links">
                <?php foreach (self::$pages as $page => $page_data) { ?>
                    <?php if (isset($page_data['parent_slug']) && !empty($page_data['parent_slug'])) { ?>
                        <?php if (current_user_can($page_data['capability'])) { ?>
                            <a href="<?php echo get_admin_url(); ?>admin.php?page=<?php echo $page_data['menu_slug']; ?>" class="nav-link <?php echo ($page === $current_page) ? 'nav-selected' : ''; ?>"><?php echo $page_data['menu_title']; ?></a>
                        <?php } ?>
                    <?php } ?>
                <?php } ?>
            </div>
        </div>
        <div class="navbar-mobile-container">
            <div class="navbar-mobile">
                <?php foreach (self::$pages as $page => $page_data) { ?>
                    <?php if (isset($page_data['parent_slug']) && !empty($page_data['parent_slug'])) { ?>
                        <?php if (current_user_can($page_data['capability'])) { ?>
                            <a href="<?php echo get_admin_url(); ?>admin.php?page=<?php echo $page_data['menu_slug']; ?>"
                               class="nav-link-mobile <?php echo ($page === $current_page) ? 'nav-mobile-selected' : ''; ?>"><?php echo $page_data['menu_title']; ?></a>
                        <?php } ?>
                    <?php } ?>
                <?php } ?>
            </div>
        </div>
<?php
    }

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

        $provider = $smtpSettings['smtp_provider'];

        if ($smtpEnabled && $provider === 'other') {
            $smtpHandler = SmtpHandler::getInstance();
            $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);
            }
        }
    }
}
