<?php
// includes/email_functions.php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once __DIR__ . '/PHPMailer/Exception.php';
require_once __DIR__ . '/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/SMTP.php';

function getEmailTemplate($title, $content) {
    return "
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body { font-family: sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
            .container { max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
            .header { background-color: #1e3c72; color: #ffffff; padding: 20px; text-align: center; }
            .content { padding: 30px; color: #333333; line-height: 1.6; }
            .footer { background-color: #eeeeee; padding: 15px; text-align: center; font-size: 12px; color: #666666; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>{$title}</h2>
            </div>
            <div class='content'>
                {$content}
            </div>
            <div class='footer'>
                &copy; " . date('Y') . " WCS Admin System
            </div>
        </div>
    </body>
    </html>";
}

function send_mail($to, $subject, $message, $isHtml = true, $attachments = []) {
    global $pdo; // Ensure global pdo is available
    $mail = new PHPMailer(true);

    try {
        // Fetch Settings from DB
        $settings = [];
        $keys = ['smtp_host', 'smtp_user', 'smtp_pass', 'smtp_port', 'smtp_from_email', 'smtp_from_name'];
        foreach ($keys as $k) {
            $val = $pdo->query("SELECT value FROM settings_options WHERE category='$k'")->fetchColumn();
            $settings[$k] = $val;
        }

        // Fallback to Constants if DB is empty
        $host = !empty($settings['smtp_host']) ? $settings['smtp_host'] : (defined('SMTP_HOST') ? SMTP_HOST : '');
        $user = !empty($settings['smtp_user']) ? $settings['smtp_user'] : (defined('SMTP_USER') ? SMTP_USER : '');
        $pass = !empty($settings['smtp_pass']) ? $settings['smtp_pass'] : (defined('SMTP_PASS') ? SMTP_PASS : '');
        $port = !empty($settings['smtp_port']) ? $settings['smtp_port'] : (defined('SMTP_PORT') ? SMTP_PORT : 587);
        $fromEmail = !empty($settings['smtp_from_email']) ? $settings['smtp_from_email'] : (defined('SMTP_FROM_EMAIL') ? SMTP_FROM_EMAIL : '');
        $fromName = !empty($settings['smtp_from_name']) ? $settings['smtp_from_name'] : (defined('SMTP_FROM_NAME') ? SMTP_FROM_NAME : 'WCS Admin');

        // Server settings
        $mail->isSMTP();
        $mail->Host       = $host;
        $mail->SMTPAuth   = true;
        $mail->Username   = $user;
        $mail->Password   = $pass;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = $port;

        // Recipients
        $mail->setFrom($fromEmail, $fromName);
        
        // Handle multiple recipients (array or comma-separated string)
        if (is_array($to)) {
            foreach ($to as $email) {
                if(filter_var(trim($email), FILTER_VALIDATE_EMAIL)) $mail->addAddress(trim($email));
            }
        } else {
            // Split by comma if string
            $emails = explode(',', $to);
            foreach ($emails as $email) {
                if(filter_var(trim($email), FILTER_VALIDATE_EMAIL)) $mail->addAddress(trim($email));
            }
        }

        // Attachments
        foreach ($attachments as $path) {
            if (file_exists($path)) {
                $mail->addAttachment($path);
            }
        }

        // Content
        $mail->isHTML($isHtml);
        $mail->Subject = $subject;
        
        if ($isHtml) {
            $mail->Body = getEmailTemplate($subject, $message);
            $mail->AltBody = strip_tags(str_replace(['<br>', '</p>'], ["\n", "\n\n"], $message));
        } else {
            $mail->Body = $message;
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
