<?php

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

require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

date_default_timezone_set('Asia/Tehran');

ini_set("log_errors", 1);
ini_set("error_log", "./z_php_error.log");

set_exception_handler(function ($e) {
    error_log(
        date('Y-m-d H:i:s') . ' | ' . ($_SERVER['REQUEST_URI'] ?? '-') . ' | ' . $e->getMessage() . PHP_EOL,
        3,
        "./z_sql_error.log"
    );
});

header("Content-Type: application/json");

// configs
require('../../majoris_config.php');
foreach (glob("../v3/class/*.php") as $filename) {
    include $filename;
}
db::init();

// validation
if (!isset($_POST['app_id'], $_POST['to'], $_POST['code'])) {
    http_response_code(400);
    echo "[app_id] or [code] or [to] parameters missing";
    exit;
}

$app_id = $_POST['app_id'];
$to     = $_POST['to'];
$code   = $_POST['code'];

$email_server_config = db::fetch(
    "SELECT * FROM `serverconfig` WHERE `app_id` = ? AND `type` = ?",
    [$app_id, "email_server_config"]
);

if (!$email_server_config) {
    http_response_code(400);
    echo "app_id is not correct";
    exit;
}

$config = json_decode($email_server_config['data'], true);

if (empty(trim($config['email_host'] ?? ''))) {
    http_response_code(400);
    echo "email host address is empty";
    exit;
}

// message
$messageraw = $config['email_from_message'] ?? '';
$message = str_replace('[code]', $code, $messageraw);

// ---------------- SMTP ----------------

$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->isHTML(true);

if ($config['email_use_smtp'] == "1") {

    $mail->isSMTP();
    $mail->Host = trim($config['email_host']);
    $mail->SMTPAuth = true;

    // IMPORTANT: must be FULL email address on Exim
    $mail->Username = trim($config['email_username']);
    $mail->Password = (string)$config['email_password'];

    $mail->Port = (int)$config['email_server_port'];

    // normalize encryption
    $secure = strtolower(trim($config['email_secure_type'] ?? ''));

    if ($mail->Port === 587) {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->SMTPAutoTLS = true;
    } elseif ($mail->Port === 465) {
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    } else {
        $mail->SMTPSecure = false;
    }

    if (($config['email_less_secure'] ?? "0") == "1") {
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            ]
        ];
    }

    if (($config['email_debug_mode'] ?? "0") == "1") {
        $mail->SMTPDebug = 2;
    }

} else {
    $mail->SMTPAuth = false;
}

// headers
$mail->setFrom(
    trim($config['email_from_address']),
    trim($config['email_from_name'])
);

$mail->addAddress($to);
$mail->Subject = $config['email_from_subject'] ?? '';
$mail->Body    = $message;
$mail->AltBody = strip_tags($message);

// send
try {

    $mail->send();
    http_response_code(200);
    echo "ok";
    exit;

} catch (Exception $e) {

    http_response_code(500);
    echo "Mailer Error: " . $mail->ErrorInfo;
    exit;
}