<?php

namespace RtmMail\Mailing;

abstract class MailHandler
{
    protected $settings;
    protected $smtpSettings;
    protected $attributes;
    protected $logId;

    public function __construct($type)
    {
        $this->settings = get_option('rtm_mail_settings');
        $this->smtpSettings = get_option('rtm_mail_smtp_settings')['smtp_settings'][$type];

        $this->attributes = [];
    }

    abstract public function send();

    abstract public static function getFields();

    public function setLogId($logId)
    {
        $this->logId = $logId;
    }

    public function getSmtpSettings()
    {
        return $this->smtpSettings;
    }

    public function addAttachment($path, $name = '')
    {
        $name = !empty($name) ? $name : basename($path);
        if (file_exists($path)) {
            $this->attributes['attachments'][] = [
                'path' => $path,
                'name' => $name
            ];
        }
    }

    public function setBody($body, $contentType = 'text/html')
    {
        $contentType = strtolower($contentType);
        $this->attributes['charset'] = 'UTF-8';
        $this->attributes['contentType'] = strtolower($contentType);
        $this->attributes['isHtml'] = $contentType === 'text/html';
        $this->attributes['body'] = $body;
    }

    public function setSubject($subject)
    {
        $this->attributes['subject'] = $subject;
    }

    public function addAddress($address, $type = 'to')
    {
        $type = strtolower($type);
        $this->attributes['addresses'][$type][] = $address;
    }

    public function setFrom($name = '', $address = '')
    {
        $this->attributes['sender_email'] = !empty($address) ? $address : $this->settings['sender_options']['address'];
        if (empty($this->attributes['sender_email'])) {
            $this->attributes['sender_email'] = get_option('admin_email');
        }
        $this->attributes['sender_title'] = !empty($name) ? $name : $this->settings['sender_options']['title'];
        if (empty($this->attributes['sender_title'])) {
            $this->attributes['sender_title'] = get_bloginfo('name');
        }
    }
}
