<?php

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

class Email_sender
{

    public $ci;
    public $data;
    private $config;

    public function __construct()
    {
        $this->ci = &get_instance();
    }

    public function custom_email($user_data, $email_data, $template, $attach = FALSE)
    {

        /*
         * De acuerdo al protocolo de la librería email de CI
          - mail
          - sendmail
          - smtp
         */
        $this->config_smtp();

        $this->ci->email->initialize($this->config);
        $this->ci->email->set_newline("\r\n");
        $this->ci->email->from($user_data['sender_email'], $user_data['sender_name']);
        $this->ci->email->to($user_data['dest_email']);
        $this->ci->email->subject($user_data['subject']);
        $this->ci->email->reply_to($user_data['reply_to']);
        if ($attach) {
            $this->ci->email->attach($user_data['attach']);
        }
        $this->data = $email_data;
        $c['content'] = $this->ci->load->view("emails/{$template}", $this->data, true);
        $msg = $this->ci->load->view('emails/Layout', $c, true);
        $this->ci->email->message($msg);
        if ($this->ci->email->send()) {
            return true;
        } else {
            throw new Exception($this->ci->email->print_debugger());
        }
    }

    private function config_smtp()
    {
        $this->config = array(
            'protocol' => $this->ci->config->item('protocol'),
            'mailtype' => $this->ci->config->item('mailtype'),
            'charset' => $this->ci->config->item('charset'),
            'smtp_host' => $this->ci->config->item('smtp_host'),
            'smtp_port' => $this->ci->config->item('smtp_port'),
            'smtp_user' => $this->ci->config->item('smtp_user'),
            'smtp_pass' => $this->ci->config->item('smtp_pass'),
            'wordwrap' => $this->ci->config->item('wordwrap'),
            'newline' => $this->ci->config->item('newline')
        );
    }

    private function config_sendmail()
    {
        $this->config = array(
            'protocol' => $this->ci->config->item('protocol'),
            'mailtype' => $this->ci->config->item('mailtype'),
            'charset' => $this->ci->config->item('charset'),
            'mailpath' => $this->ci->config->item('mailpath'),
            'wordwrap' => $this->ci->config->item('wordwrap'),
            'newline' => $this->ci->config->item('newline')
        );
    }

    private function config_mail()
    {
        $this->config = array(
            'protocol' => $this->ci->config->item('protocol'),
            'mailtype' => $this->ci->config->item('mailtype'),
            'charset' => $this->ci->config->item('charset'),
            //'wordwrap'=> $this->ci->config->item('wordwrap'),
            //'newline'=> $this->ci->config->item('newline')
        );
    }
}
