<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Library for sending mail with admin part which includes settings
 */
class emailmng
{

    const SMTP_PROTOCOL = 'smtp';
    
    const SMTP_PORT = '25';
    const DEFAULT_MAIL_TYPE = '2';
    const DEFAULT_PRIORITY = '3';
    const DEFAULT_WRAPCHARS = '76';

    protected $email;
    protected $template_data;
    protected $CI;
    protected $default_config = [
        'protocol'     => 'mail',
        'charset'      => 'utf8',
        'mailtype'     => 'html',
        'sender_email' => 'test@email.test',
        'sender_name'  => 'test'
    ];

    public function __construct()
    {
        $this->CI = &get_instance();
        $this->email = $this->CI->load->library('email');
        $configuration = $this->get_config();
        $this->email->initialize($configuration);

        if (!empty($configuration['sender_email'])) {
            $this->email->from($configuration['sender_email'], $configuration['sender_name']);
        }

        return $this;
    }

    /**
     * Magic function call for class Email
     * @param string $method
     * @param array $arguments
     * @return type
     */
    public function __call($method = '', $arguments = [])
    {
        if (method_exists($this->email, $method)) {

            return call_user_func_array([$this->email, $method], $arguments);
        } else {
            show_error('The ' . $method . ' does not exist!');
        }
    }

    /**
     * Prepare and send template
     * $args - parametrs for replace paterns in template
     * @param string $code
     * @param array $args
     * @return $this
     */
    public function send_template($code, $subject_args = [], $message_args = [])
    {
        $this->CI->load->library('parser');
        $this->CI->load->model('emailmng/template_tmodel');
        if ($this->CI->template_tmodel->fetch_by_code($code)) {
            $template_data = $this->CI->template_tmodel->fetch_by_code($code);
            $this->email->set_mailtype(($template_data['mailtype'] == self::DEFAULT_MAIL_TYPE) ? 'text' : 'html');
            $parser = new CI_Parser();
            $parser->set_delimiters('[[', ']]');
            $this->email->subject($parser->parse_string($template_data['subject'], $subject_args, true));
            $this->email->message($parser->parse_string($template_data['message'], $message_args, true));

            if (!empty($template_data['copy_to'])) {

                return $this->email->cc($template_data['copy_to']);
            }

            if (!empty($template_data['hidden_copy_to'])) {

                return $this->email->bcc($template_data['hidden_copy_to']);
            }

            return $this->email->send();
        } else {

            return false;
        }
    }

    /**
     * Prepare configuration for sending mail
     * @return array
     */
    protected function get_config()
    {
        $this->CI->load->library('ciext/configurator');
        $conf = new configurator('emailmng');
        $data = $conf->get_config();

        if (!isset($data['protocol'])) {
            
            return $this->default_config;
        }

        if ($data['protocol'] == self::SMTP_PROTOCOL) {
            $config['protocol'] = 'smtp';
            $config['smtp_host'] = $data['smtp_host'];
            $config['smtp_user'] = $data['smtp_user'];
            $config['smtp_pass'] = $data['smtp_pass'];
            $config['smtp_port'] = !empty($data['smtp_port']) ? $data['smtp_port'] : self::SMTP_PORT;
        } else {
            $config['protocol'] = $data['protocol'];
        }
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = ($data['wordwrap']) ? true : false;
        $config['validate'] = ($data['validate']) ? true : false;
        $config['mailtype'] = ($data['mailtype'] == self::DEFAULT_MAIL_TYPE) ? 'text' : 'html';
        $config['priority'] = (!empty($data['priority'])) ? $data['priority'] : self::DEFAULT_PRIORITY;
        $config['wrapchars'] = !empty($data['wrapchars']) ? $data['wrapchars'] : self::DEFAULT_WRAPCHARS;
        if (!empty($data['sender_email'])) {
            $config['sender_email'] = $data['sender_email'];
            $config['sender_name'] = $data['sender_name'];
        } else {
            $sys_conf = new configurator('ciext');
            if (!empty($sys_conf->item('email_from'))) {
                $config['sender_email'] = $sys_conf->item('email_from');
            }
        }

        return $config;
    }

}
