<?php
require_once "config.php";

function sendEmail($to, $subject, $body, $isHtml = false) {
    if (!SMTP_ENABLED) {
        $headers = "From: " . SMTP_FROM_NAME . " <" . SMTP_FROM_EMAIL . ">\r\n";
        $headers .= "Reply-To: " . SMTP_REPLY_TO . "\r\n";
        $headers .= "Content-Type: " . ($isHtml ? "text/html" : "text/plain") . "; charset=UTF-8\r\n";
        return mail($to, $subject, $body, $headers);
    }
    
    $autoloadPath = __DIR__ . '/vendor/autoload.php';
    $phpmailerPath = __DIR__ . '/PHPMailer/src/Exception.php';
    
    if (file_exists($autoloadPath)) {
        require_once $autoloadPath;
    } elseif (file_exists($phpmailerPath)) {
        require_once __DIR__ . '/PHPMailer/src/Exception.php';
        require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
        require_once __DIR__ . '/PHPMailer/src/SMTP.php';
    } else {
        error_log("PHPMailer not found. Checked: " . $autoloadPath . " and " . $phpmailerPath);
        $headers = "From: " . SMTP_FROM_NAME . " <" . SMTP_FROM_EMAIL . ">\r\n";
        $headers .= "Reply-To: " . SMTP_REPLY_TO . "\r\n";
        $headers .= "Content-Type: " . ($isHtml ? "text/html" : "text/plain") . "; charset=UTF-8\r\n";
        return mail($to, $subject, $body, $headers);
    }
    
    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
    
    try {
        $mail->isSMTP();
        $mail->Host = SMTP_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = SMTP_USERNAME;
        $mail->Password = SMTP_PASSWORD;
        $mail->SMTPSecure = SMTP_SECURE;
        $mail->Port = SMTP_PORT;
        $mail->CharSet = 'UTF-8';
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = function($str, $level) {
            error_log("PHPMailer Debug: " . $str);
        };
        
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to);
        $mail->addReplyTo(SMTP_REPLY_TO, SMTP_FROM_NAME);
        
        $mail->isHTML($isHtml);
        $mail->Subject = $subject;
        $mail->Body = $body;
        
        if (!$isHtml) {
            $mail->AltBody = strip_tags($body);
        }
        
        $result = $mail->send();
        if (!$result) {
            error_log("PHPMailer send failed: " . $mail->ErrorInfo);
        }
        return $result;
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        error_log("PHPMailer Exception: " . $mail->ErrorInfo);
        return false;
    }
}
?>
