<?php
// File: send_email.php
// Handles sending email using PHPMailer with manual includes.

// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// --- Manually include the required files ---
// Make sure these files are in the SAME directory as send_email.php
require 'PHPMailer.php';
require 'SMTP.php';
require 'Exception.php';

// --- Email Configuration ---
// IMPORTANT: Use environment variables or a secure config file in production!
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587); // Port for TLS
define('SMTP_USERNAME', 'chanuxbro@gmail.com'); // <-- Replace with your FULL Gmail address
define('SMTP_PASSWORD', 'tdmb pydc ktps olze');     // <-- Replace with your generated 16-char App Password
define('SMTP_ENCRYPTION', PHPMailer::ENCRYPTION_STARTTLS); // Use TLS encryption
define('FROM_EMAIL', 'chanuxbro@gmail.com');    // <-- Replace with your Gmail address (often same as Username)
define('FROM_NAME', 'ensi.lk 🎓'); // Updated Sender Name
define('BCC_EMAIL', 'chanuxbro@gmail.com');


/**
 * Sends an email using Google SMTP via PHPMailer.
 *
 * @param string $toEmail The recipient's email address.
 * @param string $subject The email subject.
 * @param string $bodyHTML The HTML content of the email.
 * @param string $bodyText Optional plain text version of the email body.
 * @return bool True on success, false on failure.
 */
function sendIdeasEmail(string $toEmail, string $subject, string $bodyHTML, string $bodyText = ''): bool {
    $mail = new PHPMailer(true); // Enable exceptions

    try {
        // Server settings
        // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable for detailed error output if needed
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USERNAME;
        $mail->Password   = SMTP_PASSWORD; // Use App Password
        $mail->SMTPSecure = SMTP_ENCRYPTION;
        $mail->Port       = SMTP_PORT;
        $mail->CharSet    = 'UTF-8'; // Essential for Sinhala

        // Recipients
        $mail->setFrom(FROM_EMAIL, FROM_NAME); // Updated FROM_NAME
        $mail->addAddress($toEmail); // Add a recipient
        $mail->addBCC(BCC_EMAIL);    // Add the BCC address

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject; // Subject is passed as a parameter
        $mail->Body    = $bodyHTML; // HTML Body is passed as a parameter
        if (!empty($bodyText)) {
            $mail->AltBody = $bodyText; // Plain text version
        } else {
            // Auto-generate plain text from HTML, stripping tags
            $mail->AltBody = strip_tags(str_replace('<br>', "\n", $bodyHTML));
        }


        $mail->send();
        error_log("Email sent successfully to: " . $toEmail . " (BCC: " . BCC_EMAIL . ")");
        return true;
    } catch (Exception $e) {
        // Log the detailed error to PHP's error log
        error_log("Mailer Error [{$toEmail}]: {$mail->ErrorInfo}");
        return false;
    }
}

/**
 * Formats the raw Gemini ideas text into a clean HTML list.
 * Removes common markdown like **, *, leading numbers/bullets.
 *
 * @param string $ideasText Raw text from Gemini.
 * @return string HTML formatted list (<ul><li>...</li></ul>).
 */
function formatIdeasForEmail(string $ideasText): string {
    $lines = explode("\n", trim($ideasText));
    $html = '<ul style="list-style-type: disc; margin-left: 20px;">'; // Basic styling
    foreach ($lines as $line) {
        $trimmedLine = trim($line);
        // Remove potential leading numbers/bullets like "1.", "* ", "- "
        $cleanedLine = preg_replace('/^[\d\*\-\.]+\s*/', '', $trimmedLine);
        // Remove markdown bold/italics (**) and (*)
        $cleanedLine = str_replace(['**', '*'], '', $cleanedLine);
        if (!empty($cleanedLine)) {
            // Use htmlspecialchars to prevent XSS attacks from unexpected Gemini output
            $html .= '<li style="margin-bottom: 5px;">' . htmlspecialchars($cleanedLine) . '</li>';
        }
    }
    $html .= '</ul>';
    return $html;
}
?>
