<?php

namespace RtmMail\Pages;

use RtmMail\Cryptor;
use RtmMail\Mailing\Providers\SmtpHandler;

class MailSMTP extends BasePage
{
    protected string $slug = 'mailsmtp';

    public function __construct()
    {
        parent::__construct(
            pageId: 'rtm-mail-mailsmtp',
            menuSlug: 'rtm-mail-mailsmtp',
            title: __('Mail SMTP', 'rtm-mail'),
            parent: 'rtm-mail-dashboard',
            capability: 'manage_options',
            position: 5
        );
    }

    public function doEnqueue(): void
    {
        parent::doEnqueue();
        wp_enqueue_script('mail-smtp-script', RTM_MAIL_PLUGIN_URL . 'dist/mailsmtp.js', [], false, true);
    }

    public function renderPage(): void
    {
        // Fetch encryption key
        $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);
        }

        // Fetch current SMTP settings and decrypt the password
        $settings = get_option('rtm_mail_smtp_settings');
        $smtp_enabled = $settings['smtp_enabled'] ?? false;
        $smtp_settings_decrypted_password = !empty($settings['smtp_settings']['other']['other_smtp_password'])
            ? Cryptor::decrypt($settings['smtp_settings']['other']['other_smtp_password'], $encryption_key)
            : '';

        global $handlers;
        $handlers = [
            'other' => [
                'title' => __('Default SMTP'),
                'image' => '',
                'fields' => SmtpHandler::getFields()
            ],
        ];

        include RTM_MAIL_PLUGIN_PATH . 'src/Views/' . $this->slug . '.php';
    }
}
