<?php

/*
 * Copyright (c) 2018 Earworks.
 * Codeigniter Project Template Modification
 * Please contact our email for more information :
 * contact@earworks.co.id
 */

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

if (!function_exists('send_mail')) {

    /**
     * required parameter on input array :
     * to, subject, message.
     * optional : cc, bcc
     * @param array $input
     * @param array $config
     * @return bool
     */
    function send_mail($input = array(), $config = array()) {
        // call ancillary object
        $CI = ancillary_object();

        // load required config
        $CI->load->config('mail');
        $mail = Ci::library('email');

        $mail->initialize([
            'protocol' => (isset($input['protocol'])) ? $input['protocol'] : config_item('protocol'),
            'smtp_host' => (isset($input['smtp_host'])) ? $input['smtp_host'] : config_item('host'),
            'smtp_user' => (isset($input['smtp_user'])) ? $input['smtp_user'] : config_item('username'),
            'smtp_pass' => (isset($input['smtp_pass'])) ? $input['smtp_pass'] : config_item('password'),
            'smtp_port' => (isset($input['smtp_port'])) ? $input['smtp_port'] : config_item('port'),
            'smtp_crypto' => (isset($input['crypto'])) ? $input['crypto'] : config_item('crypto'),
            'mailtype' => (isset($input['mailtype'])) ? $input['mailtype'] : 'html',
        ]);
        $mail->set_newline("\r\n");
        $mail->from(config_item('sender_email'), config_item('sender_name'));
        $mail->to($input['to']);
        if (isset($input['cc'])) {
            foreach (explode($input['cc']) as $cc) {
                $mail->cc($cc);
            }
        }
        if (isset($input['bcc'])) {
            foreach (explode($input['bcc']) as $bcc) {
                $mail->bcc($bcc);
            }
        }
        $mail->subject($input['subject']);
        $mail->message(Ci::partials(config_item('mail_template'), [
                    'content' => $input['message'],
                    'title' => $input['subject']
        ]));
//        echo $CI->load->view('email/layouts/main', array(
//            'content' => $input['message'],
//            'title' => $input['subject']
//                ), true);
//        exit;
        
//         $mail->send();
//         echo "<pre>";
//         print_r($mail->print_debugger());
//         echo "</pre>";
//         exit;
        
        return $mail->send();
    }

}
