<?php
/**
 * Email sending utility with SMTP fallback to mail()
 */

require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/Language.php';

// Включване на PHPMailer класовете, ако не са вече заредени
if (!class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
    require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
    require_once __DIR__ . '/PHPMailer/src/SMTP.php';
    require_once __DIR__ . '/PHPMailer/src/Exception.php';
}

if (!function_exists('getSetting')) {
    function getSetting($pdo, $name, $default = '') {
        $stmt = $pdo->prepare("SELECT value FROM settings WHERE name = ?");
        $stmt->execute([$name]);
        return $stmt->fetchColumn() ?: $default;
    }
}

function sendVerificationEmail($to, $username, $token, $site_url, $lang_code = 'en') {
    $pdo = Database::getInstance();
    $lang = new Language($lang_code);

    $subject = $lang->get('email_verification');
    $verify_link = rtrim($site_url, '/') . '/verify-email.php?token=' . urlencode($token) . '&lang=' . urlencode($lang_code);
    
    $message_text = $lang->get('hello') . " {$username}!\n\n";
    $message_text .= $lang->get('please_verify_email') . "\n";
    $message_text .= $verify_link . "\n\n";
    $message_text .= $lang->get('thank_you');

    $message_html = "<p>{$lang->get('hello')} {$username}!</p>";
    $message_html .= "<p>{$lang->get('please_verify_email')}</p>";
    $message_html .= "<p><a href=\"{$verify_link}\">{$lang->get('click_here_to_verify')}</a></p>";
    $message_html .= "<p>{$lang->get('thank_you')}</p>";

    // 🔹 ПОПРАВКА: Използваме site_email като основен from адрес
    $from_email = getSetting($pdo, 'site_email', 'noreply@example.com'); // избягваме @localhost
    $from_name = getSetting($pdo, 'smtp_from_name', 'TorrentBG');

    // Опит за SMTP, ако е включен
    if (getSetting($pdo, 'smtp_enabled', '0') === '1') {
        if (class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
            try {
                $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                $mail->isSMTP();
                $mail->Host = getSetting($pdo, 'smtp_host');
                $mail->Port = (int)getSetting($pdo, 'smtp_port', 465);
                $mail->SMTPAuth = true;
                $mail->Username = getSetting($pdo, 'smtp_username');
                $mail->Password = getSetting($pdo, 'smtp_password');
                $encryption = getSetting($pdo, 'smtp_encryption', 'ssl');
                if ($encryption === 'tls') {
                    $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                } else {
                    $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
                }

                $mail->setFrom($from_email, $from_name);
                $mail->addAddress($to, $username);
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message_html;
                $mail->AltBody = $message_text;

                $mail->send();
                return true;
            } catch (Exception $e) {
                error_log("SMTP send failed: " . $e->getMessage());
                // Продължаваме с mail() като резервен вариант
            }
        }
    }

    // Резервен вариант: mail() — но с валиден from адрес
    $headers = [];
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-type: text/html; charset=UTF-8';
    $headers[] = "From: {$from_name} <{$from_email}>";

    return mail($to, $subject, $message_html, implode("\r\n", $headers));
}

// ТЕСТ: премахни това след като потвърдиш, че работи
if (isset($_GET['test_phpmailer'])) {
    if (class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
        echo "✅ PHPMailer е зареден.";
    } else {
        echo "❌ PHPMailer НЕ е зареден!";
    }
    exit;
}