<?php
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

$host = $_POST['host'] ?? '';
$port = (int)($_POST['port']??0);
$user = $_POST['user'] ?? '';
$pass = $_POST['pass'] ?? '';
$secure = $_POST['secure'] ?? '';

$success = false;
$message = '';

if($host && $port && $user && $pass){
    $mail = new PHPMailer(true);
    try{
        $mail->isSMTP();
        $mail->Host = $host;
        $mail->SMTPAuth = true;
        $mail->Username = $user;
        $mail->Password = $pass;
        $mail->Port = $port;
        if($secure==='tls') $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        if($secure==='ssl') $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Timeout = 10;

        $mail->smtpConnect();
        $success = true;
        $message = 'Connection & AUTH success';
        $mail->smtpClose();
    }catch(Exception $e){
        $success = false;
        $message = $e->getMessage(); // tampilkan alasan gagal
    }
}else{
    $success = false;
    $message = 'Missing credentials';
}

echo json_encode(['success'=>$success, 'message'=>$message]);