<?php
// PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Function to send custom email
function send_custom_email(string $to, string $subject, string $body, array $additional_headers = []): bool {
    $log_file = __DIR__ . '/../logs/mail_test_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    $log_message = "[{$timestamp}] Attempting to send email.\n";
    $log_message .= "To: {$to}\n";
    $log_message .= "Subject: {$subject}\n";
    // Log first 100 chars of body
    $log_message .= "Body (snippet): " . substr(strip_tags($body), 0, 100) . "...\n";
    $log_message .= "MAIL_PROVIDER: " . (defined('MAIL_PROVIDER') ? MAIL_PROVIDER : 'NOT DEFINED') . "\n";

    if (!defined('MAIL_PROVIDER')) {
        error_log('MAIL_PROVIDER is not defined. Cannot send email.');
        $log_message .= "Result: FAILED (MAIL_PROVIDER not defined)\n\n";
        file_put_contents($log_file, $log_message, FILE_APPEND);
        return false;
    }

    // Attempt to load PHPMailer classes if not already available (e.g. via autoloader)
    // This path points to the actual PHPMailer location
    $phpMailerPath = __DIR__ . '/lib/PHPMailer/';
    if (!class_exists(PHPMailer::class) && is_dir($phpMailerPath)) {
        if (file_exists($phpMailerPath . 'Exception.php')) require_once $phpMailerPath . 'Exception.php';
        if (file_exists($phpMailerPath . 'PHPMailer.php')) require_once $phpMailerPath . 'PHPMailer.php';
        if (file_exists($phpMailerPath . 'SMTP.php')) require_once $phpMailerPath . 'SMTP.php';
        $log_message .= "PHPMailer classes loaded from: {$phpMailerPath}\n";
    } else if (!class_exists(PHPMailer::class)) {
        $log_message .= "PHPMailer directory not found at: {$phpMailerPath}\n";
    }

    $from_email = (defined('SMTP_FROM_EMAIL') && !empty(SMTP_FROM_EMAIL)) ? SMTP_FROM_EMAIL : (defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'noreply@example.com');
    $from_name = (defined('SMTP_FROM_NAME') && !empty(SMTP_FROM_NAME)) ? SMTP_FROM_NAME : (defined('SITE_NAME') ? SITE_NAME : 'Your Application');
    $log_message .= "From: {$from_name} <{$from_email}>\n";

    if (MAIL_PROVIDER === 'smtp') {
        $log_message .= "SMTP Details: Host=" . (defined('SMTP_HOST') ? SMTP_HOST : 'N/A') . 
                        ", Port=" . (defined('SMTP_PORT') ? SMTP_PORT : 'N/A') .
                        ", Username=" . (defined('SMTP_USERNAME') ? SMTP_USERNAME : 'N/A') .
                        ", Encryption=" . (defined('SMTP_ENCRYPTION') ? SMTP_ENCRYPTION : 'N/A') . "\n";

        if (!class_exists(PHPMailer::class)) {
            error_log('SMTP provider selected, but PHPMailer class not found. Please ensure PHPMailer is installed correctly in includes/lib/PHPMailer/.');
            $log_message .= "Result: FAILED (PHPMailer class not found after attempting to load from {$phpMailerPath})\n";
            $log_message .= "Check that these files exist:\n";
            $log_message .= "- {$phpMailerPath}Exception.php\n";
            $log_message .= "- {$phpMailerPath}PHPMailer.php\n";
            $log_message .= "- {$phpMailerPath}SMTP.php\n\n";
            file_put_contents($log_file, $log_message, FILE_APPEND);
            return false;
        }

        $mail = new PHPMailer(true); // Passing `true` enables exceptions

        try {
            // Server settings
            $mail->isSMTP();
            
            // Enable debug mode if needed (uncomment for troubleshooting)
            // $mail->SMTPDebug = SMTP::DEBUG_SERVER;
            // $mail->Debugoutput = function($str, $level) use (&$log_message) {
            //     $log_message .= "SMTP Debug: " . trim($str) . "\n";
            // };
            if (!defined('SMTP_HOST') || empty(SMTP_HOST)) {
                error_log('SMTP_HOST is not defined or empty. Cannot send email via SMTP.');
                $log_message .= "Result: FAILED (SMTP_HOST not defined or empty)\n\n";
                file_put_contents($log_file, $log_message, FILE_APPEND);
                return false;
            }
            
            if (!defined('SMTP_PORT') || empty(SMTP_PORT) || !is_numeric(SMTP_PORT)) {
                error_log('SMTP_PORT is not defined, empty, or not numeric. Cannot send email via SMTP.');
                $log_message .= "Result: FAILED (SMTP_PORT invalid)\n\n";
                file_put_contents($log_file, $log_message, FILE_APPEND);
                return false;
            }
            $mail->Host       = SMTP_HOST;
            
            // Set authentication based on whether username/password are provided
            if (defined('SMTP_USERNAME') && !empty(SMTP_USERNAME) && defined('SMTP_PASSWORD') && !empty(SMTP_PASSWORD)) {
                $mail->SMTPAuth   = true;
                $mail->Username   = SMTP_USERNAME;
                $mail->Password   = SMTP_PASSWORD;
                $log_message .= "SMTP Auth: Enabled with username\n";
            } else {
                $mail->SMTPAuth   = false;
                $log_message .= "SMTP Auth: Disabled (no credentials provided)\n";
            }
            
            // Handle encryption settings
            $smtp_encryption = defined('SMTP_ENCRYPTION') ? strtolower(SMTP_ENCRYPTION) : 'tls';
            $log_message .= "SMTP Encryption setting: {$smtp_encryption}\n";
            
            if ($smtp_encryption === 'none') {
                $mail->SMTPSecure = false; 
                $mail->SMTPAutoTLS = false;
                $log_message .= "SMTP Encryption: Disabled\n";
            } elseif ($smtp_encryption === 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $log_message .= "SMTP Encryption: SSL/TLS (SMTPS)\n";
            } elseif ($smtp_encryption === 'tls') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $log_message .= "SMTP Encryption: STARTTLS\n";
            } else {
                // Default to TLS if unrecognized
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $log_message .= "SMTP Encryption: Default to STARTTLS\n";
            }

            $mail->Port       = defined('SMTP_PORT') ? (int)SMTP_PORT : 587;
            $mail->Timeout    = 30; // Set timeout to 30 seconds
            
            $log_message .= "Final SMTP settings - Host: {$mail->Host}, Port: {$mail->Port}, Auth: " . ($mail->SMTPAuth ? 'Yes' : 'No') . ", Encryption: " . ($mail->SMTPSecure ?: 'None') . "\n";

            // Recipients
            $mail->setFrom($from_email, $from_name);
            $mail->addAddress($to); 

            if (isset($additional_headers['Reply-To'])) $mail->addReplyTo($additional_headers['Reply-To']);
            if (isset($additional_headers['Cc'])) {
                if (is_array($additional_headers['Cc'])) { foreach ($additional_headers['Cc'] as $cc) $mail->addCC($cc); }
                else { $mail->addCC($additional_headers['Cc']); }
            }
            if (isset($additional_headers['Bcc'])) {
                if (is_array($additional_headers['Bcc'])) { foreach ($additional_headers['Bcc'] as $bcc) $mail->addBCC($bcc); }
                else { $mail->addBCC($additional_headers['Bcc']); }
            }

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->AltBody = strip_tags($body);

            $mail->send();
            $log_message .= "Result: SUCCESS (PHPMailer)\n\n";
            file_put_contents($log_file, $log_message, FILE_APPEND);
            return true;
        } catch (Exception $e) {
            error_log("Message could not be sent using PHPMailer. Mailer Error: {$mail->ErrorInfo}");
            $log_message .= "Result: FAILED (PHPMailer Error: {$mail->ErrorInfo})\n\n";
            file_put_contents($log_file, $log_message, FILE_APPEND);
            return false;
        }
    } elseif (MAIL_PROVIDER === 'php') {
        $headers_str = "From: \"{$from_name}\" <{$from_email}>\r\n";
        $default_reply_to = $additional_headers['Reply-To'] ?? $from_email;
        $headers_str .= "Reply-To: {$default_reply_to}\r\n";
        $headers_str .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers_str .= "X-Mailer: PHP/" . phpversion() . "\r\n";

        foreach($additional_headers as $key => $value) {
            if (strtolower($key) === 'reply-to' || strtolower($key) === 'content-type' || strtolower($key) === 'from') {
                continue;
            }
            $headers_str .= "{$key}: {$value}\r\n";
        }
        $headers_str = rtrim($headers_str, "\r\n");

        if (mail($to, $subject, $body, $headers_str)) {
            $log_message .= "Result: SUCCESS (PHP mail())\n\n";
            file_put_contents($log_file, $log_message, FILE_APPEND);
            return true;
        } else {
            error_log("PHP mail() failed to send email to {$to} with subject \"{$subject}\"");
            $log_message .= "Result: FAILED (PHP mail())\n\n";
            file_put_contents($log_file, $log_message, FILE_APPEND);
            return false;
        }
    } else {
        error_log("Invalid MAIL_PROVIDER specified: " . MAIL_PROVIDER . ". Must be 'smtp' or 'php'.");
        $log_message .= "Result: FAILED (Invalid MAIL_PROVIDER)\n\n";
        file_put_contents($log_file, $log_message, FILE_APPEND);
        return false;
    }
}

function send_system_email($to, $subject, $message_content) {
    // Append a standard footer or header if desired
    $full_message = $message_content;
    $full_message .= "<p><small>This is an automated message from " . SITE_NAME . ". Please do not reply directly to this email.</small></p>";
    // $timestamp = getCurrentDateTime(); // This line was present but $timestamp was not used.

    // Prepare additional headers if needed, though send_custom_email has defaults
    $additional_headers = [];
    // Example: if you had a specific system reply-to different from default
    // if (defined('SYSTEM_REPLY_TO_EMAIL')) {
    //    $additional_headers['Reply-To'] = SYSTEM_REPLY_TO_EMAIL;
    // }

    // Call the unified send_custom_email function
    // It will internally check MAIL_PROVIDER and handle SMTP or PHP mail accordingly.
    return send_custom_email($to, $subject, $full_message, $additional_headers);
}

?>
