<?php
// publish.php
require 'config/db.php';
require __DIR__ . '/addons/game_system/functions.php'; 

if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$my_id = $_SESSION['user_id'];

try {
    $stmt_role = $pdo->prepare("SELECT username, role, is_verified FROM users WHERE id = ? LIMIT 1");
    $stmt_role->execute([$my_id]);
    $user_data = $stmt_role->fetch();
    
    if (!$user_data) { session_destroy(); header("Location: login.php"); exit; }
    $username = $user_data['username'];

    $stmt_avg = $pdo->prepare("SELECT AVG(rating) as average, COUNT(*) as total FROM reviews WHERE seller_id = ?");
    $stmt_avg->execute([$my_id]);
    $rating_stats = $stmt_avg->fetch();
    $average = round($rating_stats['average'] ?? 0, 1);

    $stmt_unread = $pdo->prepare("SELECT COUNT(*) FROM messages WHERE receiver_id = ? AND is_read = 0");
    $stmt_unread->execute([$my_id]);
    $unread_count = $stmt_unread->fetchColumn();

} catch (PDOException $e) { die("Vault Connection Error."); }

$games_list = g_get_active_games($pdo); 
$types = $pdo->query("SELECT * FROM categories WHERE parent_id = 0 AND is_hidden = 0 ORDER BY priority DESC")->fetchAll();

$message = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $price = $_POST['price'];
    $stock = (int)$_POST['stock'];
    $category_id = $_POST['category_id'] ?? null; 
    $game_id = $_POST['game_id'] ?? null;
    $server_name = trim($_POST['server_name'] ?? 'Global'); // Recibe el valor del SELECT
    $auto_content = trim($_POST['auto_delivery_content'] ?? null);

    if ($category_id && $game_id && !empty($title)) {
        $image_name = "default_item.png";
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $new_name = "item_" . time() . "_" . bin2hex(random_bytes(4)) . "." . $file_ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $new_name)) {
                $image_name = $new_name;
            }
        }

        try {
            $sql = "INSERT INTO products (title, description, price, stock, image, category_id, game_id, seller_id, server_name, auto_delivery_content, status) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'available')";
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute([$title, $description, $price, $stock, $image_name, $category_id, $game_id, $my_id, $server_name, $auto_content])) {
                $message = "Success! Your item is now live in the Vault.";
            }
        } catch (PDOException $e) { $message = "Error: " . $e->getMessage(); }
    }
}

include 'includes/header.php'; 
?>

<style>
    :root {
        --bg-dark: #0a0c0f;
        --card-bg: #111418;
        --primary: #00ff88;
        --text-gray: #888;
        --border: #222;
    }

    body { background: var(--bg-dark); color: white; font-family: 'Inter', sans-serif; }

    .v-container {
        display: grid;
        grid-template-columns: 280px 1fr;
        gap: 30px;
        max-width: 1400px;
        margin: 40px auto;
        padding: 0 20px;
    }

    .v-sidebar { display: flex; flex-direction: column; gap: 20px; }
    
    .profile-sidebar, .v-menu-card {
        background: var(--card-bg);
        border: 1px solid var(--border);
        border-radius: 18px;
        padding: 30px;
        text-align: center;
    }

    .avatar {
        width: 80px; height: 80px; background: var(--primary);
        border-radius: 50%; color: #000; font-size: 32px; font-weight: 800;
        display: flex; align-items: center; justify-content: center; margin: 0 auto 15px;
    }

    .v-nav-group { display: flex; flex-direction: column; gap: 10px; margin-top: 20px; }
    
    .nav-item {
        display: flex; align-items: center; gap: 12px; padding: 12px 20px;
        color: var(--text-gray); text-decoration: none; border-radius: 12px;
        font-weight: 600; transition: 0.3s;
    }

    .nav-item:hover { background: rgba(255,255,255,0.03); color: white; }
    .nav-item.active { background: var(--primary); color: #000; }

    .v-card {
        background: var(--card-bg);
        border: 1px solid var(--border);
        border-radius: 20px;
        padding: 40px;
    }

    .step-header {
        font-size: 11px; font-weight: 800; color: var(--primary);
        text-transform: uppercase; margin: 25px 0 15px; display: flex; gap: 10px;
    }

    .step-header span { background: var(--primary); color: #000; padding: 2px 6px; border-radius: 4px; }

    .v-input {
        width: 100%; background: #1a1e23; border: 1px solid var(--border);
        border-radius: 10px; padding: 15px; color: white; margin-bottom: 15px;
    }

    .v-input-special { border: 1px dashed var(--primary); background: rgba(0,255,136,0.02); }

    .type-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; }
    
    .type-card { cursor: pointer; }
    .type-card input { display: none; }
    .type-box {
        padding: 15px; background: #1a1e23; border: 1px solid var(--border);
        border-radius: 10px; text-align: center; font-weight: 700; color: #555;
    }
    .type-card input:checked + .type-box { border-color: var(--primary); color: var(--primary); background: rgba(0,255,136,0.05); }

    .v-btn-publish {
        width: 100%; background: var(--primary); color: #000; border: none;
        padding: 18px; border-radius: 12px; font-weight: 800; cursor: pointer; margin-top: 20px;
    }

    .v-btn-publish:disabled { background: #222; color: #444; cursor: not-allowed; }
</style>

<div class="v-container">
    <aside class="v-sidebar">
        <div class="profile-sidebar">
            <div class="avatar"><?php echo strtoupper(substr($username, 0, 1)); ?></div>
            <h2 style="font-size: 18px; margin: 0;"><?php echo htmlspecialchars($username); ?></h2>
            <div style="font-size: 11px; color: var(--text-gray); margin-top: 5px;">Seller Level 1</div>
        </div>
        
        <div class="v-menu-card" style="padding: 15px;">
            <div class="v-nav-group">
                <a href="dashboard.php" class="nav-item"><i class="fa-solid fa-gauge"></i> Overview</a>
                <a href="messages.php" class="nav-item"><i class="fa-solid fa-envelope"></i> Inbox (<?php echo $unread_count; ?>)</a>
                <a href="my_orders.php" class="nav-item"><i class="fa-solid fa-cart-shopping"></i> My Purchases</a>
                <a href="my_sales.php" class="nav-item"><i class="fa-solid fa-tag"></i> My Sales</a>
                <a href="publish.php" class="nav-item active"><i class="fa-solid fa-plus-circle"></i> Post Item</a>
                <a href="logout.php" class="nav-item" style="color: #ff4d4d;"><i class="fa-solid fa-right-from-bracket"></i> Logout</a>
            </div>
        </div>
    </aside>

    <main>
        <div class="v-card">
            <h3 style="margin: 0; font-size: 22px;"><i class="fa-solid fa-cloud-arrow-up" style="color: var(--primary);"></i> List New Item</h3>

            <form method="POST" enctype="multipart/form-data">
                <div class="step-header"><span>01</span> Targeting Game</div>
                <select name="game_id" id="game_selector" class="v-input" required onchange="updateServers()">
                    <option value="" disabled selected>Which game is this for?</option>
                    <?php foreach($games_list as $g): ?>
                        <option value="<?php echo $g['id']; ?>"><?php echo htmlspecialchars($g['name']); ?></option>
                    <?php endforeach; ?>
                </select>

                <div class="step-header"><span>02</span> Listing Type</div>
                <div class="type-grid">
                    <?php foreach($types as $t): ?>
                        <label class="type-card">
                            <input type="radio" name="category_id" value="<?php echo $t['id']; ?>" required onchange="checkFormValidity()">
                            <div class="type-box"><?php echo htmlspecialchars($t['name']); ?></div>
                        </label>
                    <?php endforeach; ?>
                </div>

                <div class="step-header"><span>03</span> Item Specifications</div>
                
                <label style="font-size: 11px; color: var(--text-gray); font-weight: 700;">SERVER NAME</label>
                <select name="server_name" id="server_selector" class="v-input v-input-special" required>
                    <option value="" disabled selected>Select a game first...</option>
                </select>

                <label style="font-size: 11px; color: var(--text-gray); font-weight: 700;">PRODUCT TITLE</label>
                <input type="text" name="title" class="v-input" placeholder="e.g. 500M Gold - Instant Delivery" required>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div>
                        <label style="font-size: 11px; color: var(--text-gray); font-weight: 700;">PRICE ($)</label>
                        <input type="number" name="price" step="0.01" class="v-input" placeholder="0.00" required>
                    </div>
                    <div>
                        <label style="font-size: 11px; color: var(--text-gray); font-weight: 700;">STOCK / QUANTITY</label>
                        <input type="number" name="stock" value="1" min="1" class="v-input" required>
                    </div>
                </div>

                <label style="font-size: 11px; color: var(--text-gray); font-weight: 700;">DESCRIPTION</label>
                <textarea name="description" rows="4" class="v-input" placeholder="Describe features, delivery time, etc..." style="resize: none;"></textarea>

                <div style="background: rgba(0, 255, 136, 0.05); border: 1px dashed var(--primary); padding: 20px; border-radius: 12px; margin-bottom: 20px;">
                    <label style="font-size: 11px; color: var(--primary); font-weight: 800;"><i class="fa-solid fa-bolt"></i> INSTANT DELIVERY CONTENT (OPTIONAL)</label>
                    <p style="font-size: 10px; color: #666; margin-bottom: 10px;">The buyer will see this information immediately after the payment is confirmed.</p>
                    <textarea name="auto_delivery_content" rows="3" class="v-input" placeholder="Enter keys, links, or account credentials here..." style="background: #000; margin-bottom: 0;"></textarea>
                </div>

                <label style="font-size: 11px; color: var(--text-gray); font-weight: 700;">COVER IMAGE</label>
                <input type="file" name="image" accept="image/*" class="v-input">

                <button type="submit" id="submit-btn" class="v-btn-publish" disabled>CONFIRM & LIST ITEM</button>
            </form>
        </div>
    </main>
</div>

<script>
// Función para cargar servidores según el juego seleccionado
function updateServers() {
    const gameId = document.getElementById('game_selector').value;
    const serverSelect = document.getElementById('server_selector');
    
    serverSelect.innerHTML = '<option value="">Loading servers...</option>';
    
    // Llamada AJAX a un archivo que debes crear (get_servers.php)
    fetch('get_servers.php?game_id=' + gameId)
        .then(response => response.json())
        .then(data => {
            serverSelect.innerHTML = '<option value="" disabled selected>Choose a server...</option>';
            if(data.length > 0) {
                data.forEach(server => {
                    serverSelect.innerHTML += `<option value="${server.server_name}">${server.server_name}</option>`;
                });
            } else {
                serverSelect.innerHTML = '<option value="Global">Global / No servers found</option>';
            }
            checkFormValidity();
        })
        .catch(error => {
            console.error('Error fetching servers:', error);
            serverSelect.innerHTML = '<option value="Global">Global</option>';
            checkFormValidity();
        });
}

function checkFormValidity() {
    const gameId = document.getElementById('game_selector').value;
    const categoryId = document.querySelector('input[name="category_id"]:checked');
    const serverId = document.getElementById('server_selector').value;
    
    document.getElementById('submit-btn').disabled = !(gameId && categoryId && serverId);
}
</script>

<?php include 'includes/footer.php'; ?>