<?php

namespace RtmMail\Mailing\Providers;

use Exception;
use RtmMail\Catcher;
use RtmMail\Cryptor;
use RtmMail\Helpers\LogHelper;
use RtmMail\Mailing\MailHandler;

class SmtpHandler extends MailHandler
{

    protected static $instance = null;
    private $phpMailer;

    public function __construct()
    {
        parent::__construct('other');
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function setMailer($phpMailer)
    {
        $this->phpMailer = $phpMailer;
    }

    public function send()
    {
        $receiverStatus = [];
        $success = [];

        $this->phpMailer->CharSet = $this->attributes['charset'];
        $this->phpMailer->isSMTP();

        $this->phpMailer->ContentType = $this->attributes['contentType'];
        $this->phpMailer->isHTML($this->attributes['isHtml']);

        $this->phpMailer->Host = $this->smtpSettings['other_smtp_host'];
        $this->phpMailer->Port = $this->smtpSettings['other_smtp_port'];

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

        if ($this->smtpSettings['other_smtp_authentication']) {
            if (empty($encryption_key)) {
                $encryption_key = wp_salt();
                update_option('rtm_mail_smtp_key', $encryption_key);
            }

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

        $this->phpMailer->Subject = $this->attributes['subject'];

        foreach ($this->attributes['addresses']['to'] as $address) {
            $this->phpMailer->setFrom($this->attributes['sender_email'], $this->attributes['sender_title']);
            $this->phpMailer->addAddress($address);
            if (isset($this->attributes['addresses']['cc'])) {
                foreach ($this->attributes['addresses']['cc'] as $cc_address) {
                    $this->phpMailer->addCC($cc_address);
                }
            }
            if (isset($this->attributes['addresses']['bcc'])) {
                foreach ($this->attributes['addresses']['bcc'] as $bcc_address) {
                    $this->phpMailer->addBCC($bcc_address);
                }
            }

            $this->attributes['body'] .= '<img src="' . Catcher::get_track_url($this->logId, $address)  . '" style="display:none;" />';
            $this->phpMailer->Body = $this->attributes['body'];

            if (isset($this->attributes['attachments'])) {
                foreach ($this->attributes['attachments'] as $attachment) {
                    $this->phpMailer->addAttachment($attachment['path'], $attachment['name']);
                }
            }

            try {
                $this->phpMailer->send();
                $receiverStatus[$address] = ['opened' => false, 'sent' => true];
                $success[] = true;
            } catch (Exception $ex) {
                do_action('rtmmail_send_failed', $this->logId, $this->phpMailer->ErrorInfo);
                $receiverStatus[$address] = ['opened' => false, 'sent' => false];
                $success[] = false;
            }
            $this->phpMailer->clearAddresses();
        }
        $this->phpMailer->smtpClose();
        LogHelper::update($this->logId, ['receiver_status' => json_encode($receiverStatus)]);

        if (in_array(true, $success, true)) {
            // Set status on sent and redirect to the log details page
            LogHelper::update($this->logId, ['status' => 'sent', 'sent' => date('Y-m-d H:i:s', time())]);
            do_action('rtmmail_send_success', $this->logId);
            return 'success';
        } else {
            // Set the status to failed and redirect to the log details page
            LogHelper::update($this->logId, ['status' => 'failed', 'sent' => null]);
            do_action('rtmmail_send_failed', $this->logId, $this->phpMailer->ErrorInfo);
            Catcher::send_text_message($this->logId);
            return $this->phpMailer->ErrorInfo;
        }
    }

    public static function getFields()
    {
        return [
            'other_smtp_host' => [
                'type' => 'text',
                'label' => __('Host', 'rtm-mail'),
                'description' => __('The host URL of the SMTP Mail server where you can authenticate and send mails from.', 'rtm-mail'),
                'key' => 'other_smtp_host',
                'placeholder' => __('Ex. smtp.gmail.com'),
                'default' => '',
            ],
            'other_smtp_encryption' => [
                'type' => 'radio',
                'label' => __('Encryption', 'rtm-mail'),
                'description' => __('Choose the different type of encryption, choose what your smtp host recommends. Often this is SSL or TLS', 'rtm-mail'),
                'key' => 'other_smtp_encryption',
                'default' => 'none',
                'options' => [
                    [
                        'value' => 'none',
                        'label' => __('None', 'rtm-mail')
                    ],
                    [
                        'value' => 'ssl',
                        'label' => __('SSL', 'rtm-mail')
                    ],
                    [
                        'value' => 'tls',
                        'label' => __('TLS', 'rtm-mail')
                    ],
                ]
            ],
            'other_smtp_port' => [
                'type' => 'number',
                'label' => __('Port', 'rtm-mail'),
                'description' => __('The port of your SMTP host.', 'rtm-mail'),
                'key' => 'other_smtp_port',
                'default' => 0,
            ],
            'other_smtp_authentication' => [
                'type' => 'checkbox',
                'label' => __('Authentication', 'rtm-mail'),
                'description' => __('Enable or disable authentication for the smtp host.', 'rtm-mail'),
                'key' => 'other_smtp_authentication',
                'default' => false,
            ],
            'other_smtp_username' => [
                'type' => 'text',
                'label' => __('Username', 'rtm-mail'),
                'description' => __('Username of your SMTP Host', 'rtm-mail'),
                'key' => 'other_smtp_username',
                'placeholder' => __('Ex. example@gmail.com'),
                'default' => '',
            ],
            'other_smtp_password' => [
                'type' => 'password',
                'label' => __('Password', 'rtm-mail'),
                'description' => __('Password of your SMTP Host. (This password is encrypted in the database)', 'rtm-mail'),
                'key' => 'other_smtp_password',
                'default' => '',
            ],
        ];
    }
}