<?php
session_start();
require '../auth/config.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header("Location: ../auth/");
    exit();
}

$user_id = $_SESSION['user_id'];
function get_user_full_info($conn, $user_id) {
    $stmt = $conn->prepare("SELECT 
        username, 
        level, 
        points, 
        email, 
        register_time, 
        organization, 
        development_field, 
        skill_tags 
        FROM users 
        WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        return $row;
    }
    return [
        'username' => '未授权人员',
        'level' => 1,
        'points' => 0,
        'email' => 'NULL',
        'register_time' => 'NULL',
        'organization' => 'NULL',
        'development_field' => 'NULL',
        'skill_tags' => 'NULL'
    ];
}

$user_info = get_user_full_info($conn, $user_id);
$username = $user_info['username'];
$level = $user_info['level'];
$points = $user_info['points'];
$email = $user_info['email'];
$register_time = $user_info['register_time'];
$organization = $user_info['organization'];
$development_field = $user_info['development_field'];
$skill_tags = explode(',', $user_info['skill_tags']);

$levelDescriptions = [1 => '云境初探者', 2 => '云境行者', 3 => '云智大师', 4 => '云核守护者'];
$userLevelDescription = $levelDescriptions[$level] ?? '未知等级';

function get_user_players($conn, $user_id) {
    $sql = "SELECT name, uuid, daemonId FROM instances WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        // 输出错误信息，帮助调试
        die("查询准备失败: " . $conn->error);
    }
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $userPlayers = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $userPlayers;
}

$user_players = get_user_players($conn, $user_id);
$max_players = 5;
$can_create_player = count($user_players) < $max_players;

// 管理功能 - 获取所有用户
function get_all_users($conn) {
    $stmt = $conn->prepare("SELECT id, username, level, points, email, register_time FROM users");
    $stmt->execute();
    $result = $stmt->get_result();
    $users = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $users;
}

// 管理功能 - 获取所有实例
function get_all_players($conn) {
    $stmt = $conn->prepare("SELECT i.id, i.name, i.uuid, i.daemonId, i.created_at, u.username as owner 
                            FROM instances i 
                            JOIN users u ON i.user_id = u.id");
    $stmt->execute();
    $result = $stmt->get_result();
    $instances = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    return $instances;
}

// 只有管理员用户才能获取管理数据
if ($level == 4) {
    $all_users = get_all_users($conn);
    $all_players = get_all_players($conn);
}
$token = bin2hex(random_bytes(32));
$_SESSION['player_token'] = $token;
$levelDescriptions = [1 => '云境初探者', 2 => '云境行者', 3 => '云智大师', 4 => '云核管理员'];
$conn->close();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>楼兰蜜语新疆核桃 - 优质坚果产品</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#800080', // 主色调：紫色
                        secondary: '#C00000', // 辅助色：红色
                        neutral: '#f8f9fa', // 中性色：浅灰
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        serif: ['SimSun', 'serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .browser-frame {
                border: 1px solid #ced4da;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .product-card {
                transition: all 0.3s ease;
            }
            .product-card:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 20px rgba(0,0,0,0.1);
            }
            /* 模态框样式 */
            .modal {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                z-index: 50;
                align-items: center;
                justify-content: center;
            }
            .modal-content {
                background-color: white;
                border-radius: 8px;
                padding: 24px;
                width: 90%;
                max-width: 400px;
                animation: fadeIn 0.3s ease;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(-20px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .price-input {
                border: 1px solid #ced4da;
                padding: 8px 12px;
                border-radius: 4px;
                width: 100%;
                font-size: 16px;
                margin-bottom: 16px;
            }
            .price-input:focus {
                outline: none;
                border-color: #800080;
                box-shadow: 0 0 0 2px rgba(128, 0, 128, 0.2);
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-serif min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-3">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-leaf text-primary text-xl"></i>
                    <h1 class="text-xl font-bold text-gray-800">圆周云境</h1>
                </div>
                <nav class="hidden md:flex space-x-6">
                    <a href="./logout.php" class="text-gray-700 hover:text-primary transition-colors duration-200">登出</a>
                    <p class="text-gray-700 transition-colors duration-200"><?php echo $userLevelDescription;?></p>
                </nav>
                <div class="md:hidden">
                    <button class="text-gray-700 focus:outline-none">
                        <i class="fa fa-bars text-xl"></i>
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <div class="browser-frame mb-8 p-2 bg-white">
            <div class="flex items-center">
                <i class="fa fa-globe text-gray-500 mr-2"></i>
                <input type="text" id="address-bar" value="https://www.loulanmiyu.com/product/核桃" 
                       class="w-full bg-gray-100 border-none rounded px-3 py-1 text-sm focus:outline-none" readonly>
                <button class="ml-2 px-3 py-1 bg-primary text-white rounded text-sm hover:bg-primary/90 transition-colors duration-200">
                    <i class="fa fa-search"></i>
                </button>
            </div>
        </div>

        <!-- 产品展示区 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <!-- 产品图片 -->
            <div class="product-card bg-white rounded-lg overflow-hidden shadow-md">
                <div class="relative">
                    <img src="index3.jpg" alt="楼兰蜜语新疆野生无漂白薄皮核桃" 
                         class="w-full h-auto object-cover">
                    <div class="absolute top-3 left-3 bg-secondary text-white text-sm px-3 py-1 rounded-full">
                        畅销产品
                    </div>
                </div>
                <div class="p-4">
                    <div class="flex items-center text-yellow-400 mb-2">
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <i class="fa fa-star"></i>
                        <span class="text-gray-600 text-sm ml-2">(5/5)</span>
                    </div>
                    <p class="text-gray-700 text-sm">已售 11,451 件</p>
                </div>
            </div>

            <!-- 产品信息 -->
            <div class="bg-white p-6 rounded-lg shadow-md">
                <h2 class="text-2xl font-bold text-gray-800 mb-3">楼兰蜜语新疆野生 无漂白薄皮核桃</h2>
                <div class="mb-4">
                    <?php if($level ==  4){
                    echo '<span id="product-price" class="text-secondary text-2xl font-bold cursor-pointer hover:underline">￥1</span>';
                    }else{
                    echo '<span class="text-secondary text-2xl font-bold cursor-pointer hover:underline">￥1</span>';
                    }?>
                    <span class="text-gray-400 line-through text-sm ml-2">¥79.9</span>
                    <span class="bg-primary/10 text-primary text-xs px-2 py-1 rounded ml-2">限时优惠</span>
                </div>
                <div class="mb-6">
                    <p class="text-gray-600 mb-3">精选新疆野生核桃，自然晾晒，无漂白，皮薄易剥，果仁饱满，营养丰富。</p>
                    <ul class="text-gray-600 space-y-1">
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <span>产地直采，新鲜直达</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <span>无添加、无漂白、无防腐剂</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <span>富含蛋白质、维生素E和不饱和脂肪酸</span>
                        </li>
                    </ul>
                </div>
                
                <!-- 购买选项 -->
                <div class="mb-6">
                    <div class="flex items-center mb-4">
                        <label class="text-gray-700 mr-4">规格：</label>
                        <div class="flex space-x-2">
                            <button class="px-4 py-2 border border-gray-300 rounded-md hover:border-primary transition-colors duration-200">250g</button>
                            <button class="px-4 py-2 border border-primary bg-primary/5 text-primary rounded-md">500g</button>
                            <button class="px-4 py-2 border border-gray-300 rounded-md hover:border-primary transition-colors duration-200">1000g</button>
                        </div>
                    </div>
                    
                    <div class="flex items-center mb-6">
                        <label class="text-gray-700 mr-4">数量：</label>
                        <div class="flex border rounded-md">
                            <button class="px-3 py-2 border-r border-gray-300 hover:bg-gray-100 transition-colors duration-200">
                                <i class="fa fa-minus"></i>
                            </button>
                            <input type="number" value="1" min="1" class="w-16 text-center border-none focus:outline-none">
                            <button class="px-3 py-2 border-l border-gray-300 hover:bg-gray-100 transition-colors duration-200">
                                <i class="fa fa-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 购买按钮 -->
                <div class="flex space-x-4">
                    <button class="flex-1 py-3 bg-secondary text-white rounded-md hover:bg-secondary/90 transition-colors duration-200 flex items-center justify-center">
                        <i class="fa fa-shopping-cart mr-2"></i> 加入购物车
                    </button>
                    <button class="flex-1 py-3 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200 flex items-center justify-center">
                        <i class="fa fa-bolt mr-2"></i> 立即购买
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 产品详情 -->
        <div class="mt-12 bg-white p-6 rounded-lg shadow-md">
            <h3 class="text-xl font-bold text-gray-800 mb-4">产品详情</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="text-center p-4 border border-gray-100 rounded-lg">
                    <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-3">
                        <i class="fa fa-map-marker text-primary text-2xl"></i>
                    </div>
                    <h4 class="font-bold text-gray-800 mb-1">产地优势</h4>
                    <p class="text-gray-600 text-sm">新疆阿克苏，昼夜温差大，日照充足，产出的核桃品质上乘。</p>
                </div>
                <div class="text-center p-4 border border-gray-100 rounded-lg">
                    <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-3">
                        <i class="fa fa-leaf text-primary text-2xl"></i>
                    </div>
                    <h4 class="font-bold text-gray-800 mb-1">品质保证</h4>
                    <p class="text-gray-600 text-sm">精选优质核桃，人工筛选，确保每一颗都饱满完整。</p>
                </div>
                <div class="text-center p-4 border border-gray-100 rounded-lg">
                    <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-3">
                        <i class="fa fa-truck text-primary text-2xl"></i>
                    </div>
                    <h4 class="font-bold text-gray-800 mb-1">新鲜直达</h4>
                    <p class="text-gray-600 text-sm">当天采摘，当天加工，冷链运输，保证新鲜度。</p>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-8">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <h3 class="text-lg font-bold mb-4">圆周云境</h3>
                    <p>© 2025 圆周云境 All Rights Reserved. <a href="https://beta.none.pw/" class="text-gray-400 hover:text-white transition-colors duration-200	text-sm"><br>Powered By CCSNetwork</a></p>
                </div>
                <div>
            </div>
        </div>
    </footer>

    <!-- 价格修改模态框 -->
    <div id="price-modal" class="modal">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-bold text-gray-800">修改价格</h3>
                <button id="close-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <p class="text-gray-600 mb-4">请输入新的产品价格：</p>
            <div class="mb-4">
                <div class="flex items-center">
                    <span class="text-gray-700 mr-2">￥</span>
                    <input type="number" id="new-price" class="price-input" value="1" min="0" step="0.01">
                </div>
            </div>
            <div class="flex space-x-3">
                <button id="cancel-price" class="flex-1 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors duration-200">
                    取消
                </button>
                <button id="save-price" class="flex-1 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200">
                    保存
                </button>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // 地址栏交互
        document.getElementById('address-bar').addEventListener('click', function() {
            this.classList.add('border-primary');
            setTimeout(() => {
                this.classList.remove('border-primary');
            }, 1000);
        });
        
        // 数量选择器
        const minusBtn = document.querySelector('.fa-minus').parentElement;
        const plusBtn = document.querySelector('.fa-plus').parentElement;
        const quantityInput = document.querySelector('input[type="number"]');
        
        minusBtn.addEventListener('click', function() {
            const currentValue = parseInt(quantityInput.value);
            if (currentValue > 1) {
                quantityInput.value = currentValue - 1;
            }
        });
        
        plusBtn.addEventListener('click', function() {
            const currentValue = parseInt(quantityInput.value);
            quantityInput.value = currentValue + 1;
        });
        
        // 模拟添加购物车动画
        const addToCartBtn = document.querySelector('.fa-shopping-cart').parentElement;
        addToCartBtn.addEventListener('click', function() {
            this.innerHTML = '<i class="fa fa-check mr-2"></i> 已加入购物车';
            setTimeout(() => {
                this.innerHTML = '<i class="fa fa-shopping-cart mr-2"></i> 加入购物车';
            }, 2000);
        });
        
        // 价格修改模态框相关代码
        const priceElement = document.getElementById('product-price');
        const modal = document.getElementById('price-modal');
        const closeModalBtn = document.getElementById('close-modal');
        const cancelBtn = document.getElementById('cancel-price');
        const saveBtn = document.getElementById('save-price');
        const newPriceInput = document.getElementById('new-price');
        
        // 打开模态框
        priceElement.addEventListener('click', function() {
            // 获取当前价格（去除货币符号）
            const currentPrice = parseFloat(priceElement.textContent.replace('￥', ''));
            newPriceInput.value = currentPrice;
            modal.style.display = 'flex';
            // 阻止页面滚动
            document.body.style.overflow = 'hidden';
        });
        
        // 关闭模态框的函数
        function closeModal() {
            modal.style.display = 'none';
            // 恢复页面滚动
            document.body.style.overflow = 'auto';
        }
        
        // 点击关闭按钮或取消按钮
        closeModalBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        
        // 点击模态框外部关闭
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModal();
            }
        });
        
        // 按ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.style.display === 'flex') {
                closeModal();
            }
        });
        
        // 保存新价格
        saveBtn.addEventListener('click', function() {
            const newPrice = parseFloat(newPriceInput.value);
            if (!isNaN(newPrice) && newPrice >= 0) {
                // 更新显示的价格
                priceElement.textContent = `￥${newPrice.toFixed(2)}`;
                closeModal();
                
                // 显示保存成功的提示
                const notification = document.createElement('div');
                notification.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-lg z-50';
                notification.textContent = '价格已更新！';
                document.body.appendChild(notification);
                
                // 3秒后自动消失
                setTimeout(() => {
                    notification.style.opacity = '0';
                    notification.style.transition = 'opacity 0.5s';
                    setTimeout(() => {
                        document.body.removeChild(notification);
                    }, 500);
                }, 3000);
            } else {
                // 显示错误提示
                newPriceInput.classList.add('border-red-500');
                setTimeout(() => {
                    newPriceInput.classList.remove('border-red-500');
                }, 2000);
            }
        });
    </script>
</body>
</html>