<?php
use Slim\Views\Twig;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class Mailer
{
  public static function sendMail($request, $body, $response)
  {
    $config = new Settings();
    $settings = $config->getSettings();
    $mailConfig = $settings["email"];

    if ($body["mail_task"] == "TESTING") {
      $html =
        "<h1>Hi! It's Fipamo!</h1><br>" .
        "<strong>It's just a test</strong><br>" .
        $body["content"];
    } else {
      $html =
        "<h1>Hi! It's Fipamo!</h1><br>" .
        "<strong>Really cool content and stuff</strong><br>" .
        $body["content"];
    }

    $mail = new PHPMailer();

    //set values based on current active protocol
    switch ($mailConfig["active"]) {
      case "option-smtp":
        $mail->setFrom($mailConfig["smtp"]["email"], "System Email");
        $mail->Host = "playvicio.us";
        $mail->Username = $mailConfig["smtp"]["email"];
        $mail->Password = $mailConfig["smtp"]["password"];

        break;
      case "option-mg":
        $mail->setFrom($mailConfig["mailgun"]["domain"], "No Reply");
        $mail->Host = "smtp.mailgun.org";
        $mail->Username = $mailConfig["mailgun"]["domain"];
        $mail->Password = $mailConfig["mailgun"]["key"];
        break;
      default:
        //no mail service
        return $result = [
          "type" => "noMailService",
          "message" => "Mail is not configured. Handle that.",
        ];
        break;
    }

    $mail->Body = $html;
    $mail->IsHTML(true);
    $mail->isSMTP();
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "ssl";
    $mail->addAddress("services@playvicio.us", ""); //pull email address from current user
    $mail->Subject = "A test email";
    $mail->Port = 465;

    // Uncomment for debug info
    //$mail->SMTPDebug = 4;

    /* Finally send the mail. */
    try {
      $mail->send();
      $result = ["type" => "mailSent", "message" => "Message Away!"];
    } catch (Exception $e) {
      echo $e->errorMessage();
      $result = ["type" => "mailNotSent", "message" => "Message Not Away!"];
    }

    return $result;
  }
}