<?php

namespace {
    use HwapX\Core\Library\DB\SQL\Mapper;
    use HwapX\Core\Library\Template;
    use HwapX\Core\Library\SMTP;

    function SMTPConnection($account_id = null) {
        $f3 = \F3::instance();

        if($account_id) {
            $db     = $f3->get('db');
            $mapper = new Mapper($db, 'hwapx_email_account');
            $mapper->load(array('id = ?', $row->account_id));

            $smtp = new SMTP(
                $mapper->host,
                $mapper->port,
                $mapper->scheme,
                $mapper->email,
                $mapper->password
            );

            $from_email = $mapper->email;
            $from_name  = $f3->get('settings.site_name');
            $smtp->set('From', "\"$from_name\" <$from_email>");
        } else {
            $smtp = new SMTP(
                $f3->get('settings.email.host'),
                $f3->get('settings.email.port'),
                $f3->get('settings.email.scheme'),
                $f3->get('settings.email.user'),
                $f3->get('settings.email.password')
            );

            $from_email = $f3->get('settings.email.user');
            $from_name  = $f3->get('settings.site_name');
            $smtp->set('From', "\"$from_name\" <$from_email>");
        }

        return $smtp;
    }

    function SMTPMessage($template_id, $data = array(), $to = null, $attachments = array()) {
        $f3       = \F3::instance();
        $db       = $f3->get('db');
        $template = Template::instance();
        $mapper   = new Mapper($db, 'hwapx_email_template');

        $mapper->load(array('id = ? OR slug = ?', $template_id, $template_id));

        if($mapper->dry())
            user_error("Template $template_id not found.",E_USER_ERROR);

        $smtp = SMTPConnection($mapper->account_id);

        $smtp->set('Content-Type', 'text/html; charset=utf-8;');

        if($mapper->from) 
            $smtp->set('From', $mapper->from);

        if($to)
            $smtp->set('To', $template->resolve($to, $data));
        else if($mapper->to)
            $smtp->set('To', $template->resolve($mapper->to, $data));

        if($mapper->subject)
            $smtp->set('Subject', $template->resolve($mapper->subject, $data));

        if($mapper->reply_to)
            $smtp->set('Reply-To', $template->resolve($mapper->reply_to, $data));

        if($mapper->cc)
            $smtp->set('CC', $mapper->cc);

        if($mapper->bcc)
            $smtp->set('BCC', $mapper->bcc);

        if($attachments)
            foreach($attachments as $name => $attach) {
                $args = is_array($attach) ? $attach : array($attach, $name);

                call_user_func_array(array($smtp, 'attach'), $args);
            }

        $message = $template->resolve($mapper->body, $data);

        return $smtp->send($message);
    }

    function SMTPEnqueue($arg, $data = array(), $to = null, $attachments = array()) {
        $f3       = \F3::instance();
        $db       = $f3->get('db');
        $template = Template::instance();
        $queue    = new Mapper($db, 'hwapx_email_queue');
        $queue->reset();

        if(!is_array($arg)) {
            $template_id = $arg;
            $mapper   = new Mapper($db, 'hwapx_email_template');

            $mapper->load(array('id = ? OR slug = ?', $template_id, $template_id));

            if($mapper->dry())
                user_error("Template $template_id not found.",E_USER_ERROR);

            $queue->from        = $mapper->from;
            $queue->template_id = $mapper->id;
            $queue->account_id  = $mapper->account_id;

            if($to)
                $queue->to = $mapper->parse ? $to : $template->resolve($to, $data);
            else if($mapper->to)
                $queue->to = $mapper->parse ? $mapper->to : $template->resolve($mapper->to, $data);

            $queue->subject  = $mapper->parse ? $mapper->subject : $template->resolve($mapper->subject, $data);
            $queue->reply_to = $mapper->parse ? $mapper->reply_to : $template->resolve($mapper->reply_to, $data);
            $queue->cc       = $mapper->cc;
            $queue->bcc      = $mapper->bcc;
            $queue->body     = $mapper->parse ? $mapper->body : $template->resolve($mapper->body, $data);
            $queue->track    = $mapper->track;
            $queue->attachments = $attachments ? json_encode($attachments) : null;
            return $queue->save();
        }

        foreach (array('subject', 'from', 'to', 'body') as $key) {
            if(empty($arg[$key]))
                user_error("Field $key is not set.",E_USER_ERROR);
        }

        $queue->from = $arg['from'];

        if(!empty($arg['template_id']))
            $queue->template_id = $arg['template_id'];
        if(!empty($arg['account_id']))
            $queue->account_id  = $arg['account_id'];

        if($to)
            $queue->to = empty($arg['parse']) ? $to : $template->resolve($to, $data);
        else if($arg['to'])
            $queue->to = empty($arg['parse']) ? $arg['to'] : $template->resolve($arg['to'], $data);

        $queue->subject  = empty($arg['parse']) ? $arg['subject'] : $template->resolve($arg['subject'], $data);
        if(!empty($arg['reply_to']))
            $queue->reply_to = empty($arg['parse']) ? $arg['reply_to'] : $template->resolve($arg['reply_to'], $data);
        if(!empty($arg['cc']))
            $queue->cc       = $arg['cc'];
        if(!empty($arg['bcc']))
            $queue->bcc      = $arg['bcc'];
        if(isset($arg['track']))
            $queue->track    = $arg['track'];

        $queue->attachments = $attachments ? json_encode($attachments) : null;
        $queue->data        = json_encode($data);
        $queue->body        = empty($arg['parse']) ? $arg['body'] : $template->resolve($arg['body'], $data);

        return $queue->save();
    }
}