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

//Load Composer's autoloader
require 'vendor/autoload.php';

class Mailer {

    private $mail;

    public function __construct() {
        //Load Composer's autoloader
        require 'vendor/autoload.php';

        //Create an instance; passing `true` enables exceptions
        $this->mail = new PHPMailer(true);

        //Server settings
        //$this->mail->SMTPDebug = SMTP::DEBUG_OFF;                      //Enable verbose debug output
        $this->mail->SMTPDebug = SMTP::DEBUG_LOWLEVEL;                      //Enable verbose debug output
        $this->mail->isSMTP();                                            //Send using SMTP
        $this->mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
        $this->mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $this->mail->Username   = 'participa@auna.org.mx';                     //SMTP username
        $this->mail->Password   = 'pxniuzmmsekngzya';                               //SMTP password
        //$this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //ORIGINAL ANOTHER ACCOUNTS
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;            //GMAIL
        //$this->mail->Port       = 465;   
        $this->mail->Port       = 587;   //GMAIL
        
        $this->mail->From       = 'participa@auna.org.mx';                         //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
        $this->mail->FromName   = 'Participa Auna';

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

    public function sendEmail($to, $subject, $body, $altBody, $attachments = []) {
        try {
            //Recipients
            
            $this->mail->addAddress($to);

            //Content
            $this->mail->isHTML(true);                                  //Set email format to HTML
            $this->mail->Subject = $subject;
            $this->mail->Body    = $body;
            $this->mail->AltBody = $altBody;

            //Attachments
            if (!empty($attachments)) {
                foreach ($attachments as $attachment) {
                    $this->mail->addAttachment($attachment);
                }
            }
            $this->mail->CharSet = 'UTF-8';

            $this->mail->send();
            
            return true;
        } catch (Exception $e) {
            echo $e->getMessage();
            return false;
        }
    }
}