<?php
// File: /admin/email_helper.php
// Use absolute-ish paths so require works when called from admin folder
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/../PHPMailer/Exception.php';
require_once __DIR__ . '/../PHPMailer/PHPMailer.php';
require_once __DIR__ . '/../PHPMailer/SMTP.php';

if (!function_exists('admin_send_email')) {
    /**
     * admin_send_email - newsletter-specific email sender
     * returns true on success, false on failure
     */
    function admin_send_email(string $to, string $subject, string $htmlBody, string $altBody = ''): bool {
        $logFile = __DIR__ . '/newsletter_log.txt';
        try {
            $mail = new PHPMailer(true);

            // SMTP settings (Hostinger example) - keep these secure in production
            $mail->isSMTP();
            $mail->Host       = 'smtp.hostinger.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'contact@unitedculturalforum.com';
            $mail->Password   = 'Pardhu@2012';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;

            $mail->setFrom('contact@unitedculturalforum.com', 'United Cultural Forum');
            $mail->addAddress($to);
            $mail->addReplyTo('contact@unitedculturalforum.com', 'United Cultural Forum');

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $htmlBody;
            $mail->AltBody = $altBody ?: strip_tags($htmlBody);

            // Optional helpful header
            $mail->addCustomHeader('List-Unsubscribe', '<mailto:contact@unitedculturalforum.com>, <https://unitedculturalforum.com/unsubscribe.php>');

            $mail->send();

            file_put_contents($logFile, "[".date('Y-m-d H:i:s')."] SUCCESS sent to $to\n", FILE_APPEND);
            return true;

        } catch (Exception $e) {
            // Log the PHPMailer error info and exception message
            $err = "[".date('Y-m-d H:i:s')."] ERROR sending to $to: " . ($mail->ErrorInfo ?? '') . " | Exception: " . $e->getMessage() . "\n";
            file_put_contents($logFile, $err, FILE_APPEND);
            error_log($err); // also write to PHP error log
            return false;
        }
    }
}
