<?php
require_once dirname(__DIR__, 2) . '/config.php';

$user_id = $_SESSION['user_id'];
$user = currentUser();

// 检查登录
if (!isLoggedIn()) {
    redirect('/modules/home/login.php');
    exit;
}

// 检查是否为代理商
if ($user['is_agent'] != 1) {
    redirect('?page=dashboard');
    exit;
}

$app_id = isset($_GET['app_id']) ? intval($_GET['app_id']) : 0;

// 调试：输出到文件
file_put_contents(__DIR__ . '/debug.log', date('Y-m-d H:i:s') . " - user_id: $user_id, app_id: $app_id, is_agent: {$user['is_agent']}\n", FILE_APPEND);

// 获取代理商的应用信息
$agent_app = $db->fetchOne("
    SELECT aa.*, a.name, a.description 
    FROM agent_apps aa
    JOIN apps a ON aa.app_id = a.id
    WHERE aa.agent_id = $user_id AND aa.app_id = $app_id AND aa.status = 1
");

if (!$agent_app) {
    redirect('?page=agent_apps');
    exit;
}

// 生成推广链接
$promo_link = SITE_URL . 'index.php?agent=' . $user_id . '&app=' . $app_id;
$promo_code = base64_encode($user_id . '|' . $app_id);
$promo_link_short = SITE_URL . '?code=' . $promo_code;

// 折扣信息
$discount_info = '';
if ($agent_app['discount_enabled']) {
    if ($agent_app['discount_type'] == 'percent') {
        $discount_info = '<span class="discount-badge">🔥 ' . $agent_app['discount_value'] . '% OFF</span>';
    } else {
        $discount_info = '<span class="discount-badge">🎁 减 ¥' . number_format($agent_app['discount_value'], 2) . '</span>';
    }
    if ($agent_app['stack_discount']) {
        $discount_info .= '<span class="stack-badge">🔄 可叠加会员折扣</span>';
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>推广链接 - 麟泓授权系统</title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="/assets/css/dark.css" id="dark-theme" disabled>
    <script src="/assets/js/main.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs2@0.0.2/qrcode.min.js"></script>
</head>
<body>
<div class="agent-sell-container" style="max-width: 800px; margin: 40px auto; padding: 20px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2>推广链接</h2>
        <a href="?page=agent_apps" class="btn btn-secondary">返回</a>
    </div>
    
    <div style="background: var(--bg-primary); border-radius: 16px; padding: 30px; border: 1px solid var(--border-color);">
        <h3><?php echo htmlspecialchars($agent_app['name']); ?></h3>
        <p><?php echo htmlspecialchars($agent_app['description'] ?: '暂无描述'); ?></p>
        <div style="display: flex; gap: 20px; margin: 20px 0; padding: 15px; background: var(--bg-secondary); border-radius: 12px; flex-wrap: wrap;">
            <span>💰 售价: ¥<?php echo number_format($agent_app['agent_price'], 2); ?></span>
            <?php echo $discount_info; ?>
            <span>🎁 您的佣金: <?php echo $agent_app['commission_rate']; ?>% (约 ¥<?php echo number_format($agent_app['agent_price'] * $agent_app['commission_rate'] / 100, 2); ?>)</span>
        </div>
        
        <div style="margin: 20px 0;">
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 500;">推广链接</label>
                <div style="display: flex; gap: 10px;">
                    <input type="text" id="promoLink" value="<?php echo htmlspecialchars($promo_link); ?>" readonly style="flex:1; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                    <button onclick="copyToClipboard('promoLink')" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">复制</button>
                </div>
            </div>
            <div>
                <label style="display: block; margin-bottom: 8px; font-weight: 500;">推广二维码</label>
                <div id="qrcode" style="padding: 20px; background: white; border-radius: 12px; display: inline-block;"></div>
            </div>
        </div>
        
        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <h4>推广技巧</h4>
            <ul style="margin-top: 10px; padding-left: 20px;">
                <li>将链接分享到您的网站、博客、社交媒体</li>
                <li>制作推广文章介绍产品优势</li>
                <li>引导客户通过您的链接购买，您将获得佣金</li>
            </ul>
        </div>
    </div>
</div>

<script>
function copyToClipboard(elementId) {
    const input = document.getElementById(elementId);
    input.select();
    document.execCommand('copy');
    if (window.showToast) {
        window.showToast('链接已复制', 'success');
    } else {
        alert('链接已复制');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const promoLink = document.getElementById('promoLink').value;
    if (typeof QRCode !== 'undefined') {
        new QRCode(document.getElementById('qrcode'), {
            text: promoLink,
            width: 150,
            height: 150,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    }
});
</script>
</body>
</html>