<?php
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;

    class Email {
        public function __construct(Database $db, Utils $utils){
            $this->db = $db;
            $this->utils = $utils;
            $this->mail = new PHPMailer(true);
            $this->setCredentials();
        }

        function setCredentials(){
            $query = $this->db->query("SELECT username, name, host, port, password FROM {$this->db->prefix}email_settings LIMIT 1");
        
            if($query->num_rows > 0){
                $this->mail->CharSet   = 'utf-8';
                $this->mail->Host      = $query->row['host'];
                $this->mail->Username  = $query->row['username'];
                $this->mail->Password  = $query->row['password'];
                $this->mail->Port      = $query->row['port'];
                $this->mail->setFrom($query->row['username'], $query->row['name']);
                $this->mail->SMTPDebug = 0;
                $this->mail->isSMTP();
                $this->mail->SMTPAuth = true;
                $this->mail->SMTPSecure = '';

                $this->mail->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );
            }
        }

        public function send($params = array()){
            if(isset($params['to'])){
                foreach ($params['to'] as $key => $row) {
                    $this->mail->addAddress($row['email'], $row['name']);
                }
            }
            if(isset($params['cc'])){
                foreach ($params['cc'] as $key => $row) {
                    $this->mail->addCC($row['email'], $row['name']);
                }
            }
            if(isset($params['bcc'])){
                foreach ($params['bcc'] as $key => $row) {
                    $this->mail->addBCC($row['email'], $row['name']);
                }
            }
            if(isset($params['reply_to'])){
                $this->mail->addReplyTo($params['reply_to']);
            }
            if(isset($params['attachment'])){
                foreach ($params['attachment'] as $key => $row) {
                    $this->mail->addAttachment($row['file'], $row['name']);
                }
            }
            if($params['is_html']){
                $this->mail->isHTML(true);
            }else{
                $this->mail->isHTML(false);
            }

            $this->mail->Subject = $params['subject'];
            $this->mail->Body    = $params['body'];

            if($this->mail->send()){
                return true;
            }

            return false;
        }
    }