<?php
// File: email_helper.php (Debug + Logging Enabled)
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require __DIR__ . '/PHPMailer/Exception.php';
require __DIR__ . '/PHPMailer/PHPMailer.php';
require __DIR__ . '/PHPMailer/SMTP.php';

function sendEmail($to, $subject, $message) {
    $mail = new PHPMailer(true);
    $logFile = __DIR__ . '/email_error_log.txt'; // Local log file in same folder

    try {
        // --- SMTP SETTINGS ---
        $mail->isSMTP();
        $mail->Host       = 'smtp.hostinger.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'contact@unitedculturalforum.com';
        $mail->Password   = 'Pardhu@2012'; // Replace later with env variable
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;

        // --- Debugging (writes to log file, not browser) ---
        $mail->SMTPDebug = 2;
        $mail->Debugoutput = function($str, $level) use ($logFile) {
            file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] SMTP[$level]: $str\n", FILE_APPEND);
        };

        // --- Email Content ---
        $mail->setFrom('contact@unitedculturalforum.com', 'United Cultural Forum');
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;

        $mail->send();
        file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] SUCCESS: Email sent to $to\n", FILE_APPEND);
        return true;
    } catch (Exception $e) {
        // Log PHPMailer error details
        file_put_contents(
            $logFile,
            "[" . date('Y-m-d H:i:s') . "] ERROR sending to $to: " . $mail->ErrorInfo . " | Exception: " . $e->getMessage() . "\n",
            FILE_APPEND
        );
        return false;
    }
}
?>
