<?php
require_once __DIR__ . '/email_config.php';

// Try to load PHPMailer (Composer). If you don't use Composer, drop PHPMailer src files and require them.
if (MAIL_USE_SMTP) {
    // Composer autoload if present
    $vendor = __DIR__ . '/vendor/autoload.php';
    if (is_file($vendor)) {
        require_once $vendor;
    } else {
        // Manual includes fallback (if you copied PHPMailer src/ into lib/phpmailer)
        $alt1 = __DIR__ . '/lib/phpmailer/src/PHPMailer.php';
        $alt2 = __DIR__ . '/lib/phpmailer/src/SMTP.php';
        $alt3 = __DIR__ . '/lib/phpmailer/src/Exception.php';
        if (is_file($alt1) && is_file($alt2) && is_file($alt3)) {
            require_once $alt1; require_once $alt2; require_once $alt3;
        }
    }
}

/**
 * Send an email (UTF-8, HTML). SMTP via PHPMailer if available; else fallback to mail().
 * @param string $to
 * @param string $subject
 * @param string $html
 * @param string $text    (optional plain text)
 * @param array  $attachments each: ['path'=> '/full/path', 'name'=>'file.ext']
 * @return array ['ok'=>bool, 'error'?=>string]
 */
function send_email(string $to, string $subject, string $html, string $text = '', array $attachments = []): array {
    $subjectEnc = '=?UTF-8?B?' . base64_encode($subject) . '?=';

    if (MAIL_USE_SMTP && class_exists('\\PHPMailer\\PHPMailer\\PHPMailer')) {
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        try {
            $mail->CharSet = 'UTF-8';
            $mail->isSMTP();
            $mail->Host       = SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = SMTP_USER;
            $mail->Password   = SMTP_PASS;
            $mail->SMTPSecure = SMTP_SECURE;
            $mail->Port       = SMTP_PORT;

            $mail->setFrom(MAIL_FROM, MAIL_FROM_NAME);
            $mail->addAddress($to);
            if (!empty(MAIL_BCC_ADMIN)) $mail->addBCC(MAIL_BCC_ADMIN);
            $mail->addReplyTo(MAIL_REPLY_TO);

            foreach ($attachments as $a) {
                if (!empty($a['path']) && is_file($a['path'])) {
                    $mail->addAttachment($a['path'], $a['name'] ?? basename($a['path']));
                }
            }

            $mail->isHTML(true);
            $mail->Subject = $subject;                       // PHPMailer handles UTF-8
            $mail->Body    = $html;
            $mail->AltBody = $text !== '' ? $text : trim(strip_tags($html));

            // Optional SMTP debug to a log file:
            /*
            $mail->SMTPDebug  = 2;
            $mail->Debugoutput = function($str, $level) {
                error_log("[SMTP $level] $str");
            };
            */

            $mail->send();
            return ['ok'=>true];
        } catch (\Throwable $e) {
            error_log('[MAIL][SMTP] ' . $e->getMessage());
            return ['ok'=>false, 'error'=>$e->getMessage()];
        }
    }

    // Fallback: native mail() (less reliable, but works on many shared hosts)
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "From: ".MAIL_FROM_NAME." <".MAIL_FROM.">\r\n";
    $headers .= "Reply-To: ".MAIL_REPLY_TO."\r\n";
    if (!empty(MAIL_BCC_ADMIN)) $headers .= "Bcc: ".MAIL_BCC_ADMIN."\r\n";

    $ok = @mail($to, $subjectEnc, $html, $headers);
    if (!$ok) {
        error_log('[MAIL][PHP] mail() returned false for '.$to);
        return ['ok'=>false, 'error'=>'mail() failed'];
    }
    return ['ok'=>true];
}
