<?php
namespace app\models;

use app\app;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

class emails
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS emails (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER REFERENCES users(id),
            from_email TEXT NOT NULL,
            from_name TEXT NOT NULL,
            to_email TEXT NOT NULL,
            subject TEXT NOT NULL,
            message TEXT NOT NULL,
            html_message TEXT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        );");
    }

    public static function getRecentByUserId($user_id, $n)
    {
        $query = "SELECT * FROM emails WHERE user_id = :user_id ORDER BY created_at DESC LIMIT :n";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
        $stmt->bindParam(':n', $n, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public static function getRecent($n)
    {
        $query = "SELECT * FROM emails ORDER BY created_at DESC LIMIT :n";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':n', $n, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public static function updateUserIdByEmail($email, $user_id)
    {
        $query = "UPDATE emails SET user_id = :user_id WHERE to_email = :email AND user_id IS NULL";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
        $stmt->bindParam(':email', $email);
        $stmt->execute();
    }

    public static function send($subject, $from_email, $from_name, $to_email, $message, $template, $template_vars)
    {
        $user    = users::getByEmail($to_email);
        $user_id = $user ? $user['id'] : null;

        $HTML_message = $GLOBALS['twig']->render("lib/emails/$template", $template_vars);
        $query        = "INSERT INTO emails (user_id, from_email, from_name, to_email, subject, message, html_message)
                  VALUES (:user_id, :from_email, :from_name, :to_email, :subject, :message, :html_message)";
        $stmt = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':from_email', $from_email);
        $stmt->bindParam(':from_name', $from_name);
        $stmt->bindParam(':to_email', $to_email);
        $stmt->bindParam(':subject', $subject);
        $stmt->bindParam(':message', $message);
        $stmt->bindParam(':html_message', $HTML_message);
        $stmt->execute();
        $mail = new PHPMailer(exceptions: true);
        // Mail Server settings
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host       = $_ENV['SMTP_HOST'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $_ENV['SMTP_USER'];
        $mail->Password   = $_ENV['SMTP_PASS'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        $mail->isHTML(true);
        $mail->setFrom($from_email, $from_name);
        $mail->addAddress($to_email);
        $mail->Subject = $subject;
        $mail->Body    = $HTML_message;
        $mail->AltBody = $message;
        // Buffer the output
        ob_start();
        $mail->send();
        ob_end_clean();
    }
}
