<?php
// 开启 Session
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once 'config.php';

// ================= 1. 登录检测 =================
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    die('<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>请先登录</title><style>body{background:#f4f6f9;font-family:sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;}.box{background:#fff;padding:40px;border-radius:10px;text-align:center;box-shadow:0 4px 15px rgba(0,0,0,0.1);}h3{color:#333;margin-bottom:15px;}p{color:#666;margin-bottom:25px;}a{padding:10px 30px;background:#007bff;color:white;text-decoration:none;border-radius:20px;}</style></head><body><div class="box"><h3>⚠️ 请先登录</h3><p>您需要登录后才能投稿软件</p><a href="user/index.php">立即登录</a></div></body></html>');
}

$user_id = $_SESSION['user_id'];

// ================= 1.5. 获取自动审核开关状态 =================
$auto_approve_enabled = false;
$res_setting = mysqli_query($conn, "SELECT setting_value FROM system_settings WHERE setting_key='auto_approve'");
if ($res_setting && $row_setting = mysqli_fetch_assoc($res_setting)) {
    if ($row_setting['setting_value'] == 1) {
        $auto_approve_enabled = true;
    }
}

// ================= 2. 获取用户等级与价格限制 =================
$stmt_user = mysqli_prepare($conn, "SELECT level FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt_user, "i", $user_id);
mysqli_stmt_execute($stmt_user);
$res_user = mysqli_stmt_get_result($stmt_user);
$user_info = mysqli_fetch_assoc($res_user);
$user_level = intval($user_info['level'] ?? 0);

// 价格限制逻辑
$max_price_limit = floor($user_level / 10) + 1;
if ($max_price_limit < 1) $max_price_limit = 1;

// 获取分类
$categories = mysqli_query($conn, "SELECT * FROM categories ORDER BY sort_order, name");
$categories_array = [];
if ($categories && mysqli_num_rows($categories) > 0) {
    while ($cat = mysqli_fetch_assoc($categories)) {
        $categories_array[] = $cat;
    }
}

$msg = '';
$current_tab = isset($_GET['tab']) ? $_GET['tab'] : 'single';

// ================= 网盘识别核心函数 (修复蓝奏云) =================
function getDiskType($url) {
    $rules = [
        'baidu.com'        => '百度网盘',
        'quark.cn'         => '夸克网盘',
        'xunlei.com'       => '迅雷网盘',
        'lanzou'           => '蓝奏云',  // 修复：匹配所有蓝奏云变体
        'aliyundrive.com'  => '阿里云盘',
        'alipan.com'       => '阿里云盘', // 新增阿里云盘新域名
        'weiyun.com'       => '腾讯微云',
        'yun.10086.cn'     => '中国移动云盘',
        '123pan.com'       => '123云盘'
    ];
    foreach ($rules as $domain => $name) {
        if (strpos($url, $domain) !== false) {
            return $name;
        }
    }
    return false;
}

// ================= 3. 处理单个投稿 =================
if (isset($_POST['submit'])) {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $download_url = mysqli_real_escape_string($conn, $_POST['download_url']);
    $disk_code = mysqli_real_escape_string($conn, $_POST['disk_code'] ?? '');
    $coin_price = intval($_POST['coin_price'] ?? 0);
    $category = mysqli_real_escape_string($conn, $_POST['category']);

    // A. 校验价格权限
    if ($coin_price > 0 && $coin_price > $max_price_limit) {
        $msg = '<div class="alert error">❌ 价格设置错误：您的等级最高只能设置 ' . $max_price_limit . ' 个小马币。</div>';
    } 
    // B. 校验网盘链接
    else {
        $disk_type = getDiskType($download_url);
        if ($disk_type === false) {
            $msg = '<div class="alert error">❌ 链接格式错误：仅支持百度、夸克、迅雷、蓝奏、阿里、微云、移动、123云盘。</div>';
        } else {
            // C. 处理图片上传
            $upload_dir = "uploads/";
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            $pic_name = uniqid() . "_" . basename($_FILES['image']['name']);
            $dst = $upload_dir . $pic_name;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $dst)) {
                // D. 写入数据库
                $disk_type_sql = mysqli_real_escape_string($conn, $disk_type);
                $final_status = $auto_approve_enabled ? 1 : 0;
                $success_msg = $auto_approve_enabled ? '✅ 投稿成功！已自动审核通过。' : '✅ 投稿成功！请等待管理员审核。';

                $sql = "INSERT INTO apps(name, image, download_url, disk_type, disk_code, coin_price, category, status, user_id) 
                        VALUES('$name', '$dst', '$download_url', '$disk_type_sql', '$disk_code', '$coin_price', '$category', $final_status, '$user_id')";
                
                if (mysqli_query($conn, $sql)) {
                    $msg = '<div class="alert success">' . $success_msg . '</div>';
                } else {
                    $msg = '<div class="alert error">❌ 数据库错误：' . mysqli_error($conn) . '</div>';
                }
            } else {
                $msg = '<div class="alert error">❌ 图片上传失败，请检查目录权限。</div>';
            }
        }
    }
}

// ================= 4. 处理批量投稿 =================
if (isset($_POST['batch_submit'])) {
    $content = trim($_POST['batch_content']);
    $lines = explode("\n", $content);
    $names = [];
    $urls = [];
    
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) continue;
        if (filter_var($line, FILTER_VALIDATE_URL)) {
            $urls[] = $line;
        } else {
            $names[] = $line;
        }
    }
    
    $count = min(count($names), count($urls));
    $upload_dir = "uploads/";
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
    
    $success_count = 0;
    $error_msgs = [];
    
    $cats_post = isset($_POST['batch_cats']) ? $_POST['batch_cats'] : [];
    $prices_post = isset($_POST['batch_prices']) ? $_POST['batch_prices'] : [];
    $codes_post = isset($_POST['batch_codes']) ? $_POST['batch_codes'] : [];

    $final_status = $auto_approve_enabled ? 1 : 0;
    
    for ($i = 0; $i < $count; $i++) {
        $name_safe = mysqli_real_escape_string($conn, $names[$i]);
        $url_safe = mysqli_real_escape_string($conn, $urls[$i]);
        $cat_safe = isset($cats_post[$i]) ? mysqli_real_escape_string($conn, $cats_post[$i]) : '';
        
        $item_price = intval($prices_post[$i] ?? 0);
        $item_code = mysqli_real_escape_string($conn, $codes_post[$i] ?? '');
        
        // 1. 校验价格权限
        if ($item_price > 0 && $item_price > $max_price_limit) {
            $error_msgs[] = "第".($i+1)."项价格超限";
            continue;
        }

        // 2. 校验网盘类型
        $disk_type = getDiskType($url_safe);
        if ($disk_type === false) {
            $error_msgs[] = "第".($i+1)."项链接不支持";
            continue;
        }
        $disk_type_safe = mysqli_real_escape_string($conn, $disk_type);

        // 3. 上传图片
        $image_path_to_db = "";
        $file_key = 'batch_image_' . ($i + 1);
        
        if (isset($_FILES[$file_key]) && $_FILES[$file_key]['size'] > 0) {
            $pic_name = uniqid() . "_" . basename($_FILES[$file_key]['name']);
            $dst = $upload_dir . $pic_name;
            if (move_uploaded_file($_FILES[$file_key]['tmp_name'], $dst)) {
                $image_path_to_db = $dst;
            }
        }
        
        // 4. 数据库写入
        if(!empty($image_path_to_db) && !empty($cat_safe)) {
            $sql = "INSERT INTO apps(name, image, download_url, disk_type, disk_code, coin_price, category, status, user_id) 
                    VALUES('$name_safe', '$image_path_to_db', '$url_safe', '$disk_type_safe', '$item_code', '$item_price', '$cat_safe', $final_status, '$user_id')";
            if(mysqli_query($conn, $sql)) {
                $success_count++;
            }
        } else {
            $error_msgs[] = "第".($i+1)."项缺图或分类";
        }
    }
    
    if($success_count > 0) {
        $success_msg_batch = $auto_approve_enabled ? '✅ 批量投稿成功！共提交 ' . $success_count . ' 个应用，已自动审核通过。' : '✅ 批量投稿成功！共提交 ' . $success_count . ' 个应用，等待审核。';
        $msg = '<div class="alert success">' . $success_msg_batch . '</div>';
    }
    if(!empty($error_msgs)) {
        $msg .= '<div class="alert error">部分失败：' . implode(', ', $error_msgs) . '</div>';
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>软件投稿 - WC软件</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f0f2f5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; }
        .alert.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        
        .notice-box {
            background: #fff3cd; border: 1px solid #ffeeba; color: #856404;
            padding: 15px 20px; border-radius: 8px; margin-bottom: 20px;
            border-left: 5px solid #ffc107; font-size: 14px; line-height: 1.6;
        }
        .notice-box strong { display: block; margin-bottom: 5px; font-size: 15px; }

        .tabs { display: flex; gap: 10px; margin-bottom: 20px; }
        .tab-btn { padding: 10px 20px; background: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; color: #333; flex: 1; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .tab-btn.active { background: #007bff; color: white; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        
        .card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .card-title { font-size: 18px; font-weight: 600; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center; }
        .card-title span { font-size: 12px; color: #999; font-weight: normal; }
        
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; font-size: 14px; color: #666; margin-bottom: 8px; font-weight: 500; }
        
        input[type="text"], input[type="url"], input[type="number"], select, textarea { 
            width: 100%; height: 44px; border: 1px solid #e0e0e0; border-radius: 8px; 
            padding: 0 12px; font-size: 15px; background: #fafafa; transition: all 0.3s; 
        }
        textarea { height: 200px; padding: 12px; font-family: monospace; resize: vertical; }
        input:focus, textarea:focus, select:focus { border-color: #007bff; background: #fff; outline: none; box-shadow: 0 0 0 3px rgba(0,123,255,0.1); }
        
        .input-row { display: flex; gap: 10px; }
        .input-row .form-group { flex: 1; }

        .btn { padding: 10px 30px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; transition: opacity 0.3s; }
        .btn:hover { opacity: 0.9; }
        .btn-success { background: #28a745; }
        
        .single-upload-box {
            position: relative; width: 100%; height: 180px; border: 2px dashed #ddd;
            border-radius: 8px; background: #fafafa; cursor: pointer; overflow: hidden;
            display: flex; align-items: center; justify-content: center;
        }
        .single-upload-box input { position: absolute; width: 100%; height: 100%; opacity: 0; cursor: pointer; z-index: 2; }
        .single-upload-box img { max-width: 90%; max-height: 90%; object-fit: contain; z-index: 1; }
        .single-upload-box .text { color: #999; font-size: 14px; z-index: 1; pointer-events: none; text-align: center; }

        .item-row { 
            display: grid; grid-template-columns: 40px 1fr 120px 80px 100px 100px; 
            gap: 10px; align-items: center; margin-bottom: 10px; padding: 12px; 
            background: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef;
        }
        .item-row .num { width: 30px; height: 30px; background: #007bff; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px; }
        .item-row .info { font-size: 14px; color: #333; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .item-row input, .item-row select { height: 36px; font-size: 13px; padding: 0 8px; width: 100%; }

        .batch-upload-box {
            position: relative; width: 100%; height: 70px; background: #fff;
            border: 1px solid #e0e0e0; border-radius: 6px; display: flex;
            align-items: center; justify-content: center; overflow: hidden; cursor: pointer;
        }
        .batch-upload-box input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; z-index: 10; }
        .batch-upload-box .preview-content { position: relative; z-index: 1; pointer-events: none; text-align: center; color: #999; font-size: 12px; }
        .batch-upload-box .preview-content img { display: block; max-width: 50px; max-height: 50px; object-fit: contain; margin: 0 auto; }

        @media (max-width: 768px) {
            .item-row { grid-template-columns: 30px 1fr; gap: 8px; }
            .item-row .info { grid-column: 2; margin-bottom: 5px; }
            .item-row select, .item-row input, .item-row .batch-upload-box { grid-column: 2; width: 100%; }
            .input-row { flex-direction: column; gap: 0; }
        }
    </style>
</head>
<body>
<div class="container">
    <div style="text-align: center; margin-bottom: 20px;">
        <h1 style="color: #333; font-size: 24px;">WC软件 - 投稿中心</h1>
        <p style="color: #666; font-size: 14px; margin-top: 5px;">分享好软件，方便你我他</p>
    </div>
    
    <div class="notice-box">
        <strong>⚠️ 温馨提示：</strong>
        1. 禁止上传二维码、分享色情、暴力、恐怖、侵权盗版、政治敏感、违法违规等内容；<br>
        2. 链接仅用于合法合规用途，违反平台规则及法律法规将被封禁处理；<br>
        3. 仅支持：百度、夸克、迅雷、蓝奏、阿里、微云、移动、123云盘。
    </div>

    <?= $msg ?>

    <div class="tabs">
        <button class="tab-btn <?= $current_tab == 'single' ? 'active' : '' ?>" onclick="showTab('single')">单个投稿</button>
        <button class="tab-btn <?= $current_tab == 'batch' ? 'active' : '' ?>" onclick="showTab('batch')">批量投稿</button>
    </div>
    
    <div id="single" class="tab-content <?= $current_tab == 'single' ? 'active' : '' ?>">
        <div class="card">
            <div class="card-title">提交新软件</div>
            <form method="post" enctype="multipart/form-data">
                <div class="input-row">
                    <div class="form-group">
                        <label>软件名称 *</label>
                        <input type="text" name="name" required placeholder="例如：WC助手">
                    </div>
                    <div class="form-group">
                        <label>所属分类 *</label>
                        <select name="category" required>
                            <option value="">请选择分类</option>
                            <?php foreach($categories_array as $cat): ?>
                            <option value="<?= htmlspecialchars($cat['name']) ?>"><?= htmlspecialchars($cat['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label>软件图标 *</label>
                    <div class="single-upload-box">
                        <input type="file" name="image" accept="image/*" required onchange="previewSingle(this)">
                        <div class="text" id="singlePreview">点击上传图标</div>
                    </div>
                </div>

                <div class="form-group">
                    <label>下载链接 * (支持：百度、夸克、迅雷、蓝奏、阿里、微云、移动、123)</label>
                    <input type="url" name="download_url" required placeholder="请粘贴支持的网盘链接">
                </div>

                <div class="input-row">
                    <div class="form-group">
                        <label>提取码 (如无留空)</label>
                        <input type="text" name="disk_code" placeholder="如：abcd">
                    </div>
                    <div class="form-group">
                        <label>下载价格 (当前等级限额: <?= $max_price_limit ?>)</label>
                        <select name="coin_price">
                            <option value="0">免费下载</option>
                            <?php for($i=1; $i<=$max_price_limit; $i++): ?>
                            <option value="<?= $i ?>"><?= $i ?> 个小马币</option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>

                <button type="submit" name="submit" class="btn btn-success" style="width: 100%; margin-top: 10px;">提交投稿</button>
            </form>
        </div>
    </div>
    
    <div id="batch" class="tab-content <?= $current_tab == 'batch' ? 'active' : '' ?>">
        <div class="card">
            <div class="card-title">
                批量投稿软件
                <span>您的价格限额：<?= $max_price_limit ?> 币</span>
            </div>
            
            <div style="background: #e8f4fd; padding: 15px; border-radius: 8px; margin-bottom: 15px; line-height: 1.6; font-size: 13px; border-left: 4px solid #007bff;">
                <strong>📖 格式说明：</strong><br>
                一行软件名称，一行下载链接，交替排列。不支持链接会自动跳过。
            </div>
            
            <form method="post" enctype="multipart/form-data" id="batchForm">
                <div class="form-group">
                    <label>批量输入内容 *</label>
                    <textarea name="batch_content" id="batchContent" placeholder="软件名1\n链接1\n软件名2\n链接2..." required></textarea>
                    <button type="button" class="btn" style="margin-top:10px; padding:8px 15px; font-size:14px;" onclick="generateRows()">解析并生成上传列表</button>
                </div>
                
                <div id="itemRowsContainer" style="max-height: 600px; overflow-y: auto; margin-bottom: 15px;">
                    <div style="color: #999; text-align: center; padding: 40px 20px; background: #f9f9f9; border-radius: 8px; border: 1px dashed #ddd;">
                        请在上方输入内容后点击按钮生成列表
                    </div>
                </div>
                
                <button type="submit" name="batch_submit" class="btn btn-success" style="width: 100%;">开始批量投稿</button>
            </form>
        </div>
    </div>
</div>

<script>
    function showTab(tabId) {
        document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.getElementById(tabId).classList.add('active');
        event.target.classList.add('active');
        history.pushState(null, null, '?tab='+tabId);
    }
    
    function previewSingle(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                var previewDiv = document.getElementById('singlePreview');
                previewDiv.innerHTML = '<img src="' + e.target.result + '">';
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    function previewBatch(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                var contentDiv = input.parentElement.querySelector('.preview-content');
                contentDiv.innerHTML = '<img src="' + e.target.result + '">';
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    var maxPriceLimit = <?= $max_price_limit ?>;
    var catsJson = <?= json_encode(array_column($categories_array, 'name')) ?>;

    function generateRows() {
        var content = document.getElementById('batchContent').value;
        var lines = content.split('\n').filter(line => line.trim() !== '');
        var names = [];
        
        lines.forEach(line => {
            var trimmed = line.trim();
            if (trimmed && !trimmed.match(/^https?:\/\//)) {
                names.push(trimmed);
            }
        });
        
        var html = '';
        if(names.length > 0) {
            for (var i = 0; i < names.length; i++) {
                var catOptions = '<option value="">分类</option>';
                for(var j=0; j<catsJson.length; j++) {
                    catOptions += '<option value="'+catsJson[j]+'">'+catsJson[j]+'</option>';
                }
                
                var priceOptions = '<option value="0">免费</option>';
                for(var p=1; p<=maxPriceLimit; p++) {
                    priceOptions += '<option value="'+p+'">'+p+'币</option>';
                }
                
                var fileIndex = i + 1;
                
                html += `
                <div class="item-row">
                    <div class="num">${fileIndex}</div>
                    <div class="info">${escapeHtml(names[i])}</div>
                    <select name="batch_cats[${i}]" required>${catOptions}</select>
                    <input type="text" name="batch_codes[${i}]" placeholder="提取码">
                    <select name="batch_prices[${i}]">${priceOptions}</select>
                    
                    <div class="batch-upload-box">
                        <input type="file" name="batch_image_${fileIndex}" accept="image/*" required onchange="previewBatch(this)">
                        <div class="preview-content">点击上传</div>
                    </div>
                </div>
                `;
            }
        } else {
            html = '<div style="color: #999; text-align: center; padding: 20px;">未识别到软件名称，请检查格式</div>';
        }
        
        document.getElementById('itemRowsContainer').innerHTML = html;
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    }
</script>
</body>
</html>
