<?php
/**
 * @package    Proxim
 * @author     Davison Pro <davisonpro.coder@gmail.com | https://davisonpro.dev>
 * @copyright  2019 Proxim
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

namespace Proxim;

use Db;
use Proxim\Database\DbQuery;
use Proxim\Cache\Cache;
use Proxim\ObjectModel;
use Proxim\Application;
use Proxim\Configuration;
use Proxim\Tools;
use Proxim\Validate;

/**
 * Class Mail
 */
class Mail extends ObjectModel
{
    public $id;

    /** @var int site_id */
    public $site_id = PROX_SITE_ID;

    /** @var string Recipient */
    public $recipient;

    /** @var string Template */
    public $template;

    /** @var string Subject */
    public $subject;

    /** @var int Timestamp */
    public $date_add;

    /**
     * @see ObjectModel::$definition
     */
    public static $definition = [
        'table' => 'mail',
        'primary' => 'mail_id',
        'fields' => [
            'site_id' => array(
                'type' => self::TYPE_INT, 
                'validate' => 'isUnsignedInt'
            ),
            'recipient' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isEmail',
                'required' => true,
                'size' => 255,
            ],
            'template' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isTplName',
                'required' => true,
                'size' => 62,
            ],
            'subject' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isMailSubject',
                'required' => true,
                'size' => 255,
            ],
            'date_add' => [
                'type' => self::TYPE_DATE,
                'validate' => 'isDate',
                'copy_post' => false,
                'required' => true,
            ],
        ],
    ];

    /**
     * Mail content type.
     */
    const TYPE_HTML = 1;
    const TYPE_TEXT = 2;
    const TYPE_BOTH = 3;

    /**
     * Send mail under SMTP server.
     */
    const METHOD_SMTP = 2;

    /**
     * Disable mail, will return immediately after calling send method.
     */
    const METHOD_DISABLE = 3;

    /**
     * Send Email.
     *
     * @param string $template Template: the name of template not be a var but a string !
     * @param string $subject Subject of the email
     * @param string $templateVars Template variables for the email
     * @param string $to To email
     * @param string $toName To name
     * @param string $from From email
     * @param string $fromName To email
     * @param array $fileAttachment array with three parameters (content, mime and name).
     *                              You can use an array of array to attach multiple files
     * @param bool $mode_smtp SMTP mode (deprecated)
     * @param string $templatePath Template path
     * @param bool $die Die after error
     * @param string $bcc Bcc recipient address. You can use an array of array to send to multiple recipients
     * @param string $replyTo Reply-To recipient address
     * @param string $replyToName Reply-To recipient name
     *
     * @return bool|int Whether sending was successful. If not at all, false, otherwise amount of recipients succeeded.
     */
    public static function send(
        $template,
        $subject,
        $templateVars,
        $to,
        $toName = null,
        $from = null,
        $fromName = null,
        $fileAttachment = null,
        $mode_smtp = null,
        $templatePath = PROX_DIR_MAIL,
        $die = false,
        $bcc = null,
        $replyTo = null,
        $replyToName = null,
        $site_id = PROX_SITE_ID
    ) {
        $smarty = Application::getInstance()->container->smarty;

        $configuration = Configuration::getMultiple(
            [
                'SITE_EMAIL',
                'MAIL_METHOD',
                'MAIL_SERVER',
                'MAIL_USER',
                'MAIL_PASSWD',
                'SITE_NAME',
                'MAIL_SMTP_ENCRYPTION',
                'MAIL_SMTP_PORT',
            ],
            $site_id
        );

        // Returns immediately if emails are deactivated
        if ($configuration['MAIL_METHOD'] == self::METHOD_DISABLE) {
            return true;
        }

        if (!isset($configuration['MAIL_SMTP_ENCRYPTION']) ||
            Tools::strtolower($configuration['MAIL_SMTP_ENCRYPTION']) === 'off'
        ) {
            $configuration['MAIL_SMTP_ENCRYPTION'] = false;
        }

        if (!isset($configuration['MAIL_SMTP_PORT'])) {
            $configuration['MAIL_SMTP_PORT'] = 'default';
        }

        /*
         * Sending an e-mail can be of vital importance for the merchant, when his password
         * is lost for example, so we must not die but do our best to send the e-mail.
         */
        if (!isset($from) || !Validate::isEmail($from)) {
            $from = $configuration['SITE_EMAIL'];
        }

        if (!Validate::isEmail($from)) {
            $from = null;
        }

        // $from_name is not that important, no need to die if it is not valid
        if (!isset($fromName) || !Validate::isMailName($fromName)) {
            $fromName = $configuration['SITE_NAME'];
        }

        if (!Validate::isMailName($fromName)) {
            $fromName = null;
        }

        /*
         * It would be difficult to send an e-mail if the e-mail is not valid,
         * so this time we can die if there is a problem.
         */
        if (!is_array($to) && !Validate::isEmail($to)) {
            throw new \Exception('Error: parameter "to" is corrupted');
            return false;
        }

        // if bcc is not null, make sure it's a vaild e-mail
        if (!is_null($bcc) && !is_array($bcc) && !Validate::isEmail($bcc)) {
            throw new \Exception('Error: parameter "bcc" is corrupted');
            $bcc = null;
        }

        if (!is_array($templateVars)) {
            $templateVars = [];
        }

        // Do not crash for this error, that may be a complicated customer name
        if (is_string($toName) && !empty($toName) && !Validate::isMailName($toName)) {
            $toName = null;
        }

        if (!Validate::isTplName($template)) {
            throw new \Exception('Error: invalid e-mail template');

            return false;
        }

        if (!Validate::isMailSubject($subject)) {
            throw new \Exception('Error: invalid e-mail subject');

            return false;
        }

        /* Construct multiple recipients list if needed */
        $message = \Swift_Message::newInstance();
        if (is_array($to) && isset($to)) {
            foreach ($to as $key => $addr) {
                $addr = trim($addr);
                if (!Validate::isEmail($addr)) {
                    throw new \Exception('Error: invalid e-mail address');
                    return false;
                }

                if (is_array($toName) && isset($toName[$key])) {
                    $addrName = $toName[$key];
                } else {
                    $addrName = $toName;
                }

                $addrName = ($addrName == null || $addrName == $addr || !Validate::isGenericName($addrName)) ?
                          '' :
                          self::mimeEncode($addrName);
                $message->addTo($addr, $addrName);
            }
            $toPlugin = $to[0];
        } else {
            /* Simple recipient, one address */
            $toPlugin = $to;
            $toName = (($toName == null || $toName == $to) ? '' : self::mimeEncode($toName));
            $message->addTo($to, $toName);
        }

        if (isset($bcc) && is_array($bcc)) {
            foreach ($bcc as $addr) {
                $addr = trim($addr);
                if (!Validate::isEmail($addr)) {
                    throw new \Exception('Error: invalid e-mail address');

                    return false;
                }

                $message->addBcc($addr);
            }
        } elseif (isset($bcc)) {
            $message->addBcc($bcc);
        }

        try {
            /* Connect with the appropriate configuration */
            if ($configuration['MAIL_METHOD'] == self::METHOD_SMTP) {
                if (empty($configuration['MAIL_SERVER']) || empty($configuration['MAIL_SMTP_PORT'])) {
                    throw new \Exception('Error: invalid SMTP server or SMTP port');

                    return false;
                }

                $connection = \Swift_SmtpTransport::newInstance(
                    $configuration['MAIL_SERVER'],
                    $configuration['MAIL_SMTP_PORT'],
                    $configuration['MAIL_SMTP_ENCRYPTION']
                )
                    ->setUsername($configuration['MAIL_USER'])
                    ->setPassword($configuration['MAIL_PASSWD']);
                    
            } else {
                $connection = \Swift_MailTransport::newInstance();
            }

            if (!$connection) {
                return false;
            }

            $swift = \Swift_Mailer::newInstance($connection);
            $templatePath = PROX_DIR_MAIL;

            if (!file_exists($templatePath . $template . '.tpl')
            ) {
                throw new \Exception(sprintf('Error - The following e-mail template is missing: %s', $templatePath . $template . '.tpl'));
            } else {
                $templatePathExists = true;
            }

            if (empty($templatePathExists)) {
                throw new \Exception(sprintf('Error - The following e-mail template is missing: %s', [$template]));
                return false;
            }

            /* Create mail and attach differents parts */
            $message->setSubject($subject);

            $message->setCharset('utf-8');

            /* Set Message-ID - getmypid() is blocked on some hosting */
            $message->setId(Mail::generateId());

            if (!($replyTo && Validate::isEmail($replyTo))) {
                $replyTo = $from;
            }

            if (isset($replyTo) && $replyTo) {
                $message->setReplyTo($replyTo, ($replyToName !== '' ? $replyToName : null));
            }

            $site_logo = Configuration::get('SITE_EMAIL_LOGO', $site_id);
            if ( file_exists( PROX_DIR_UPLOADS . $site_logo ) ) {
                $logo = PROX_DIR_UPLOADS . $site_logo;
                $templateVars['site_logo'] = $message->embed(\Swift_Image::fromPath($logo));
            } else {
                $templateVars['site_logo'] = '';
            }
            
            $templateVars['current_year'] = date('Y');
            $templateVars['subject'] = $subject;
            $templateVars['site_name'] = Tools::safeOutput(Configuration::get('SITE_NAME', $site_id));
            $templateVars['site_email'] = Tools::safeOutput(Configuration::get('SITE_EMAIL', $site_id));
            $templateVars['site_url'] = Tools::safeOutput(Configuration::get('SITE_DOMAIN', $site_id));
            $templateVars['color'] = Tools::safeOutput(Configuration::get('MAIL_COLOR', $site_id, '#3c90df'));
            // Get extra template_vars
            $extraTemplateVars = [];
           
            $templateVars = array_merge($templateVars, $extraTemplateVars);
            
            $smarty->assign([
                'templateVars' => $templateVars
            ]);

            $templateHtml = $smarty->fetch($templatePath . $template . '.tpl');

            $message->addPart($templateHtml, 'text/html', 'utf-8');

            if ($fileAttachment && !empty($fileAttachment)) {
                // Multiple attachments?
                if (!is_array(current($fileAttachment))) {
                    $fileAttachment = array($fileAttachment);
                }

                foreach ($fileAttachment as $attachment) {
                    if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) {
                        $message->attach(
                            \Swift_Attachment::newInstance()->setFilename(
                                $attachment['name']
                            )->setContentType($attachment['mime'])
                            ->setBody($attachment['content'])
                        );
                    }
                }
            }

            /* Send mail */
            $message->setFrom(array($from => $fromName));

            $send = $swift->send($message);

            if ($send && Configuration::get('LOG_EMAILS')) {
                $mail = new Mail();
                $mail->template = Tools::substr($template, 0, 62);
                $mail->subject = Tools::substr($subject, 0, 255);
                $recipientsTo = $message->getTo();
                $recipientsCc = $message->getCc();
                $recipientsBcc = $message->getBcc();
                if (!is_array($recipientsTo)) {
                    $recipientsTo = [];
                }
                if (!is_array($recipientsCc)) {
                    $recipientsCc = [];
                }
                if (!is_array($recipientsBcc)) {
                    $recipientsBcc = [];
                }
                foreach (array_merge($recipientsTo, $recipientsCc, $recipientsBcc) as $email => $recipient_name) {
                    /* @var Swift_Address $recipient */
                    $mail->id = null;
                    $mail->recipient = Tools::substr($email, 0, 255);
                    $mail->add();
                }
            }

            return $send;
        } catch (\Swift_SwiftException $e) {
            throw new \Exception('Swift Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * @param $idMail Mail ID
     *
     * @return bool Whether removal succeeded
     */
    public static function eraseLog($idMail)
    {
        return Db::getInstance()->delete('mail', 'mail_id = ' . (int) $idMail);
    }

    /**
     * @return bool
     */
    public static function eraseAllLogs()
    {
        return Db::getInstance()->execute('TRUNCATE TABLE ' . PROX_DB_PREFIX . 'mail');
    }

    /**
     * Send a test email.
     *
     * @param bool $smtpChecked Is SMTP checked?
     * @param string $smtp_server SMTP Server hostname
     * @param string $content Content of the email
     * @param string $subject Subject of the email
     * @param bool $type Deprecated
     * @param string $to To email address
     * @param string $from From email address
     * @param string $smtpLogin SMTP login name
     * @param string $smtpPassword SMTP password
     * @param int $smtpPort SMTP Port
     * @param bool|string $smtpEncryption Encryption type. "off" or false disable encryption.
     *
     * @return bool|string True if succeeded, otherwise the error message
     */
    public static function sendMailTest(
        $smtpChecked,
        $smtp_server,
        $content,
        $subject,
        $type,
        $to,
        $from,
        $smtpLogin,
        $smtpPassword,
        $smtpPort,
        $smtpEncryption
    ) {
        $result = false;
        try {
            if ($smtpChecked) {
                if (Tools::strtolower($smtpEncryption) === 'off') {
                    $smtpEncryption = false;
                }
                $smtp = \Swift_SmtpTransport::newInstance($smtp_server, $smtpPort, $smtpEncryption)
                    ->setUsername($smtpLogin)
                    ->setPassword($smtpPassword);
                $swift = \Swift_Mailer::newInstance($smtp);
            } else {
                $swift = \Swift_Mailer::newInstance(\Swift_MailTransport::newInstance());
            }

            $message = \Swift_Message::newInstance();

            $message
                ->setFrom($from)
                ->setTo($to)
                ->setSubject($subject)
                ->setBody($content);

            if ($swift->send($message)) {
                $result = true;
            }
        } catch (\Swift_SwiftException $e) {
            $result = $e->getMessage();
        }

        return $result;
    }

    /* Rewrite of Swift_Message::generateId() without getmypid() */
    protected static function generateId($idstring = null)
    {
        $midparams = [
            'utctime' => gmstrftime('%Y%m%d%H%M%S'),
            'randint' => mt_rand(),
            'customstr' => (preg_match('/^(?<!\\.)[a-z0-9\\.]+(?!\\.)$/iD', $idstring) ? $idstring : 'swift'),
            'hostname' => !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : php_uname('n'),
        ];

        return vsprintf('%s.%d.%s@%s', $midparams);
    }

    /**
     * Check if a multibyte character set is used for the data.
     *
     * @param string $data Data
     *
     * @return bool Whether the string uses a multibyte character set
     */
    public static function isMultibyte($data)
    {
        $length = Tools::strlen($data);
        for ($i = 0; $i < $length; ++$i) {
            if (ord(($data[$i])) > 128) {
                return true;
            }
        }

        return false;
    }

    /**
     * MIME encode the string.
     *
     * @param string $string The string to encode
     * @param string $charset The character set to use
     * @param string $newline The newline character(s)
     *
     * @return mixed|string MIME encoded string
     */
    public static function mimeEncode($string, $charset = 'UTF-8', $newline = "\r\n")
    {
        if (!self::isMultibyte($string) && Tools::strlen($string) < 75) {
            return $string;
        }

        $charset = Tools::strtoupper($charset);
        $start = '=?' . $charset . '?B?';
        $end = '?=';
        $sep = $end . $newline . ' ' . $start;
        $length = 75 - Tools::strlen($start) - Tools::strlen($end);
        $length = $length - ($length % 4);

        if ($charset === 'UTF-8') {
            $parts = [];
            $maxchars = floor(($length * 3) / 4);
            $stringLength = Tools::strlen($string);

            while ($stringLength > $maxchars) {
                $i = (int) $maxchars;
                $result = ord($string[$i]);

                while ($result >= 128 && $result <= 191) {
                    $result = ord($string[--$i]);
                }

                $parts[] = base64_encode(Tools::substr($string, 0, $i));
                $string = Tools::substr($string, $i);
                $stringLength = Tools::strlen($string);
            }

            $parts[] = base64_encode($string);
            $string = implode($sep, $parts);
        } else {
            $string = chunk_split(base64_encode($string), $length, $sep);
            $string = preg_replace('/' . preg_quote($sep) . '$/', '', $string);
        }

        return $start . $string . $end;
    }
}