<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader or include the PHPMailer library
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // SMTP server configuration
    $smtpServer = "mail.ediblegardencreations.com.au";
    $port = 465;
    $username = "elizabeth@ediblegardencreations.com.au";
    $password = "Redapple99";

    // Retrieve form inputs
    $customSenderName = $_POST['custom_sender_name'] ?? 'No Name Provided';
    $customSenderEmail = $_POST['custom_sender_email'] ?? 'noemail@domain.com';
    $receiverEmail = $_POST['receiver_email'] ?? '';

    // Check if HTML file is uploaded
    $htmlFile = $_FILES['html_file'] ?? null;
    if ($htmlFile && $htmlFile['error'] === UPLOAD_ERR_OK) {
        $htmlContent = file_get_contents($htmlFile['tmp_name']);
    } else {
        echo "Error: Please upload a valid HTML file.";
        exit;
    }

    // Create the email
    $mail = new PHPMailer(true);

    try {
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host = $smtpServer;
        $mail->SMTPAuth = true;
        $mail->Username = $username;
        $mail->Password = $password;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $port;

        // Email headers and content
        $mail->setFrom($username, $customSenderName);
        $mail->addAddress($receiverEmail);
        $mail->addReplyTo($customSenderEmail);
        $mail->Subject = $_POST['email_subject'] ?? 'No Subject';
        $mail->isHTML(true);
        $mail->Body = $htmlContent;

        // Send the email
        $mail->send();
        echo "Email sent successfully!";
    } catch (Exception $e) {
        echo "Error: Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
} else {
    echo "Invalid request method. Please submit the form.";
}
