<?php

namespace Licenzo\Services\Email;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Helper\Settings;

class Email
{

    protected $config = [];

    public function __construct($config = [])
    {
        $default = [
            'from_name'     => get_option('blogname', 'Support Team'),
            'from_email'    => get_option('admin_email', ''),
            'reply_to'      => '',
            'reply_to_name' => ''
        ];

        $this->config = wp_parse_args($config, $default);
    }

    public function send($to, $subject, $message, $headers = [])
    {
        // build wordPress email header from the config array
        $headers = $this->buildHeader($headers);
        return wp_mail($to, $subject, $message, $headers);
    }

    public static function fromDefault()
    {
        return new static(Settings::getEmailSettings());
    }

    public function buildHeader($headers = [])
    {

        $licenzoHeader = [];

        if(isset($this->config['from_name']) && isset($this->config['from_email'])) {
            $fromName = str_replace(["\r", "\n"], '', $this->config['from_name']);
            $fromEmail = str_replace(["\r", "\n"], '', $this->config['from_email']);
            $licenzoHeader[] = 'From: ' . $fromName . ' <' . $fromEmail . '>';
        }

        if(isset($this->config['reply_to']) && isset($this->config['reply_to_name'])) {
            $replyToName = str_replace(["\r", "\n"], '', $this->config['reply_to_name']);
            $replyTo = str_replace(["\r", "\n"], '', $this->config['reply_to']);
            $licenzoHeader[] = 'Reply-To: ' . $replyToName . ' <' . $replyTo . '>';
        }

        return wp_parse_args($licenzoHeader, $headers);

    }
}
