<?php
/**
 * 邮件发送辅助函数
 */

// 获取邮件配置（从主站配置读取）
function getMailConfig() {
    $smtp_host = getSiteConfig('smtp_host');
    if ($smtp_host) {
        return [
            'host' => $smtp_host,
            'port' => getSiteConfig('smtp_port') ?: 465,
            'user' => getSiteConfig('smtp_user') ?: '',
            'pass' => getSiteConfig('smtp_pass') ?: '',
            'from' => getSiteConfig('smtp_from') ?: '',
            'name' => getSiteConfig('smtp_name') ?: getSiteConfig('site_name') ?: '系统通知',
        ];
    }
    return null;
}

// 发送邮件
function sendMail($to, $subject, $content) {
    $config = getMailConfig();
    
    if (!$config || empty($config['user']) || empty($config['pass'])) {
        logMailError("邮件配置未设置");
        return false;
    }
    
    // 查找 autoload
    $autoloadPaths = [
        __DIR__ . '/../encrypt/vendor/autoload.php',
        __DIR__ . '/../vendor/autoload.php',
        __DIR__ . '/vendor/autoload.php',
    ];
    
    $loaded = false;
    foreach ($autoloadPaths as $path) {
        if (file_exists($path)) {
            require_once $path;
            $loaded = true;
            break;
        }
    }
    
    if (!$loaded) {
        logMailError("PHPMailer 未安装");
        return false;
    }
    
    $mail = new PHPMailer\PHPMailer\PHPMailer(true);
    
    try {
        $mail->isSMTP();
        $mail->Host = $config['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $config['user'];
        $mail->Password = $config['pass'];
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $config['port'];
        $mail->setFrom($config['from'] ?: $config['user'], $config['name']);
        $mail->addAddress($to);
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->isHTML(true);
        $mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
        $mail->Body = $content;
        $mail->AltBody = strip_tags($content);
        
        $mail->send();
        
        // 记录日志
        logMailSuccess($to, $subject);
        return true;
    } catch (Exception $e) {
        logMailError("发送失败: " . $mail->ErrorInfo, $to, $subject);
        return false;
    }
}

// 获取邮件模板并替换变量
function getEmailTemplate($type, $variables = []) {
    global $db;
    
    $template = $db->fetchOne("SELECT * FROM email_templates WHERE type = '$type'");
    if (!$template) {
        return null;
    }
    
    $site_name = getSiteConfig('site_name') ?: '授权系统';
    $variables['site_name'] = $site_name;
    
    $subject = $template['subject'];
    $content = $template['content'];
    
    foreach ($variables as $key => $value) {
        $subject = str_replace('{' . $key . '}', $value, $subject);
        $content = str_replace('{' . $key . '}', $value, $content);
    }
    
    return ['subject' => $subject, 'content' => $content];
}

// 发送验证码邮件
function sendVerifyCodeMail($email, $code, $type = 'register') {
    $siteName = getSiteConfig('site_name') ?: '麟泓授权系统';
    
    $typeNames = [
        'register' => '注册验证',
        'login' => '登录验证',
        'bind' => '绑定邮箱',
        'reset' => '重置密码'
    ];
    
    $typeName = $typeNames[$type] ?? '验证';
    
    $subject = "【{$siteName}】{$typeName}验证码";
    
    $content = '
    <!DOCTYPE html>
    <html>
    <head><meta charset="UTF-8"></head>
    <body style="font-family: Arial, sans-serif; padding: 20px;">
        <div style="max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;">
            <div style="background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;">
                <h2 style="color: white; margin: 0;">' . $typeName . '</h2>
            </div>
            <div style="padding: 30px;">
                <p style="font-size: 16px;">您好！</p>
                <p>您正在进行<span style="color: #667eea; font-weight: bold;">' . $typeName . '</span>操作，验证码如下：</p>
                <div style="text-align: center; margin: 30px 0;">
                    <span style="font-size: 32px; font-weight: bold; letter-spacing: 5px; background: #f3f4f6; padding: 12px 24px; border-radius: 12px;">' . $code . '</span>
                </div>
                <p style="color: #6b7280; font-size: 14px;">验证码有效期为 <strong>5分钟</strong>，请尽快完成验证。</p>
                <p style="color: #6b7280; font-size: 14px;">如果这不是您本人操作，请忽略此邮件。</p>
                <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;">
                <p style="color: #9ca3af; font-size: 12px;">此邮件由系统自动发送，请勿回复。</p>
            </div>
        </div>
    </body>
    </html>';
    
    return sendMail($email, $subject, $content);
}

// 发送充值成功通知（使用模板）
function sendRechargeNotification($user, $amount, $order_no, $payment_method = '在线支付') {
    $balance = $user['balance'];
    $template = getEmailTemplate('recharge', [
        'username' => $user['username'],
        'amount' => number_format($amount, 2),
        'order_no' => $order_no,
        'balance' => number_format($balance, 2),
        'payment_method' => $payment_method
    ]);
    
    if ($template) {
        return sendMail($user['email'], $template['subject'], $template['content']);
    }
    return false;
}

// 发送消费通知
function sendConsumeNotification($user, $item_name, $amount, $order_no) {
    $siteName = getSiteConfig('site_name') ?: '万能授权系统';
    $subject = "【{$siteName}】购买成功通知";
    
    $content = '
    <!DOCTYPE html>
    <html>
    <head><meta charset="UTF-8"></head>
    <body style="font-family: Arial, sans-serif; padding: 20px;">
        <div style="max-width: 500px; margin: 0 auto; background: #f9fafb; border-radius: 16px; overflow: hidden;">
            <div style="background: linear-gradient(135deg, #667eea, #764ba2); padding: 30px; text-align: center;">
                <h2 style="color: white; margin: 0;">🎉 购买成功</h2>
            </div>
            <div style="padding: 30px;">
                <p style="font-size: 16px;">尊敬的 ' . htmlspecialchars($user['username']) . '，您好！</p>
                <p>您已成功购买：</p>
                <div style="margin: 20px 0; padding: 15px; background: #f3f4f6; border-radius: 12px;">
                    <p>应用名称：<strong>' . htmlspecialchars($item_name) . '</strong></p>
                    <p>金额：¥' . number_format($amount, 2) . '</p>
                    <p>订单号：' . $order_no . '</p>
                </div>
                <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;">
                <p style="color: #9ca3af; font-size: 12px;">此邮件由系统自动发送，请勿回复。</p>
            </div>
        </div>
    </body>
    </html>';
    
    return sendMail($user['email'], $subject, $content);
}

// 发送登录提醒邮件（使用模板）
function sendLoginAlert($user, $ip, $city, $device, $login_time) {
    $template = getEmailTemplate('login_alert', [
        'username' => $user['username'],
        'login_time' => $login_time,
        'city' => $city,
        'device' => $device,
        'ip' => $ip
    ]);
    
    if ($template) {
        return sendMail($user['email'], $template['subject'], $template['content']);
    }
    return false;
}

// 发送卡密充值成功通知（使用模板）
function sendCardRechargeNotification($user, $amount, $card_code) {
    $balance = $user['balance'];
    $template = getEmailTemplate('card_recharge', [
        'username' => $user['username'],
        'amount' => number_format($amount, 2),
        'card_code' => $card_code,
        'balance' => number_format($balance, 2),
        'payment_method' => '卡密'
    ]);
    
    if ($template) {
        return sendMail($user['email'], $template['subject'], $template['content']);
    }
    return false;
}
// 发送快捷登录绑定通知
function sendOauthBindNotification($user, $oauth_type) {
    $template = getEmailTemplate('oauth_bind', [
        'username' => $user['username'],
        'oauth_type' => $oauth_type,
        'bind_time' => date('Y-m-d H:i:s')
    ]);
    
    if ($template) {
        return sendMail($user['email'], $template['subject'], $template['content']);
    }
    return false;
}

// 日志记录
function logMailSuccess($to, $subject) {
    global $db;
    if (isset($db)) {
        $to = $db->escape($to);
        $subject = $db->escape($subject);
        $db->query("INSERT INTO email_log (to_email, subject, status) VALUES ('$to', '$subject', 1)");
    }
}

function logMailError($error, $to = '', $subject = '') {
    global $db;
    if (isset($db)) {
        $to = $db->escape($to);
        $subject = $db->escape($subject);
        $error = $db->escape($error);
        $db->query("INSERT INTO email_log (to_email, subject, status, error_msg) VALUES ('$to', '$subject', 0, '$error')");
    }
    error_log("邮件发送失败: $error");
}