<?php

class email
{
    private static $smtpServer = EMAIL_SMTP_HOST;
    private static $smtpPort = EMAIL_SMTP_PORT;
    private static $smtpSecure = EMAIL_SMTP_SECURE;
    private static $username = EMAIL_SMTP_USER;
    private static $password = EMAIL_SMTP_PASSWORD;
    private static $fromEmail = EMAIL_FROM_EMAIL;
    private static $fromName = EMAIL_FROM_NAME;

    public static function send($_to, $_name, $_subject, $_message)
    {
        $template = file_get_contents(DIR_TEMPLATE_EMAILS.'cms.alerte.html');

        if ($template === false) {
            echo "Impossible de lire le template d'email.";
            return;
        }

        // Remplacer les variables dans le template
        $template = str_replace('{{name}}', $_name, $template);
        $template = str_replace('{{message}}', $_message, $template);
        $template = str_replace('{{subject}}', $_subject, $template);

         // Créer une instance de PHPMailer
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);

        try {
            // Paramètres du serveur
            $mail->isSMTP();
            $mail->Host = self::$smtpServer; 
            $mail->SMTPAuth = true;
            $mail->Username = self::$username; 
            $mail->Password = self::$password; 
            $mail->SMTPSecure = self::$smtpSecure; 
            $mail->Port = self::$smtpPort;

            // Destinataires
            $mail->setFrom(self::$fromEmail, self::$fromName);
            $mail->addAddress($_to, $_name);

            // Contenu de l'email
            $mail->isHTML(true);
            $mail->Subject = $_subject;
            $mail->Body    = $template;

            try {
                $mail->send();
                return TRUE;
            } catch (Exception $e) {
                alert::recError("ERREUR TECHNIQUE : Send Email " . $mail->ErrorInfo);
                return FALSE;
            }
        } catch (Exception $e) {
            alert::recError("ERREUR TECHNIQUE : Config Email " . $mail->ErrorInfo);
            return FALSE;
        }
    }

    private static function sendCommand($smtp, $command)
    {
        fputs($smtp, $command . "\r\n");
        return self::serverResponse($smtp);
    }

    private static function serverResponse($smtp)
    {
        $response = '';
        while ($str = fgets($smtp, 512)) {
            $response .= $str;
            if (substr($str, 3, 1) == ' ') {
                break;
            }
        }
        return $response;
    }

}