<?php
require 'config/db.php';

// Iniciamos sesión antes que nada para el balance del header
if (session_status() === PHP_SESSION_NONE) { session_start(); }

$product_id = $_GET['id'] ?? 0;
$my_id = $_SESSION['user_id'] ?? 0;

// 1. Obtener datos del producto, vendedor y juego
$stmt = $pdo->prepare("
    SELECT p.*, u.id as seller_id, u.username, u.last_seen, u.created_at as user_date, g.name as game_name,
    (SELECT AVG(rating) FROM reviews WHERE seller_id = u.id) as avg_rating,
    (SELECT COUNT(*) FROM reviews WHERE seller_id = u.id) as total_reviews
    FROM products p
    JOIN users u ON p.seller_id = u.id
    JOIN games g ON p.game_id = g.id
    WHERE p.id = ?
");
$stmt->execute([$product_id]);
$product = $stmt->fetch();

if (!$product) { header("Location: index.php"); exit; }

// CARGAMOS EL HEADER AQUÍ para tener acceso a $user_balance en el HTML de abajo
include 'includes/header.php';

// 2. Cargar mensajes previos (Solo si el usuario está logueado)
$chat_history = [];
if ($my_id > 0) {
    $stmt_msg = $pdo->prepare("
        SELECT m.*, u.username as sender_name 
        FROM messages m 
        JOIN users u ON m.sender_id = u.id 
        WHERE m.product_id = ? 
        AND ((m.sender_id = ? AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = ?)) 
        ORDER BY m.created_at ASC
    ");
    $stmt_msg->execute([$product_id, $my_id, $product['seller_id'], $product['seller_id'], $my_id]);
    $chat_history = $stmt_msg->fetchAll();
}
?>

<style>
    .p-container { max-width: 1300px; margin: 30px auto; display: grid; grid-template-columns: 1fr 400px; gap: 30px; padding: 0 20px; }
    .p-main-card { background: var(--nav-bg); border: 1px solid var(--border); border-radius: 12px; padding: 30px; }
    .purchase-box { background: rgba(255,255,255,0.03); border-radius: 10px; padding: 20px; margin-top: 25px; border: 1px solid var(--border); }
    .v-input { width: 100%; background: #000; border: 1px solid var(--border); padding: 12px; color: white; border-radius: 6px; box-sizing: border-box; outline: none; }
    .v-input:focus { border-color: var(--primary); }
    
    /* Chat Style */
    .chat-card { background: var(--nav-bg); border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; height: 600px; position: sticky; top: 100px; }
    .chat-header { padding: 15px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
    .chat-body { flex: 1; padding: 15px; overflow-y: auto; background: rgba(0,0,0,0.2); display: flex; flex-direction: column; }
    .msg-bubble { margin-bottom: 10px; padding: 10px; border-radius: 8px; font-size: 13px; max-width: 85%; }
    .msg-me { background: var(--primary); color: black; align-self: flex-end; }
    .msg-them { background: #30363d; color: white; align-self: flex-start; }
    .chat-footer { padding: 15px; border-top: 1px solid var(--border); }
    .chat-input-area textarea { width: 100%; background: transparent; border: none; color: white; resize: none; outline: none; font-family: inherit; }

    .total-amount { font-size: 28px; font-weight: 900; color: var(--primary); }
    .btn-buy { background: var(--primary); color: black; width: 100%; padding: 18px; border: none; border-radius: 8px; font-weight: 900; font-size: 16px; cursor: pointer; text-transform: uppercase; transition: 0.3s; margin-top: 15px; }
    .btn-buy:hover { opacity: 0.8; transform: translateY(-2px); }
</style>

<div class="p-container">
    <div>
        <div class="p-main-card">
            <span style="color: var(--primary); font-size: 12px; font-weight: 800;"><?php echo strtoupper($product['game_name']); ?></span>
            <h1 style="color: white; font-size: 26px; margin: 10px 0;"><?php echo htmlspecialchars($product['title']); ?></h1>
            <p style="color: var(--text-gray); line-height: 1.6;"><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>

            <form action="process_purchase.php" method="POST" class="purchase-box">
                <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 15px;">
                    <div>
                        <label style="font-size: 11px; color: var(--text-gray);">PAYMENT METHOD</label>
                        <select class="v-input" name="payment_method">
                            <option value="balance">Vault Balance ($<?php echo number_format($user_balance, 2); ?>)</option>
                        </select>
                    </div>
                    <div>
                        <label style="font-size: 11px; color: var(--text-gray);">UNIT PRICE</label>
                        <div style="padding: 12px; font-weight: 800; color: white;">$<?php echo number_format($product['price'], 2); ?></div>
                    </div>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div>
                        <label style="font-size: 11px; color: var(--text-gray);">QUANTITY</label>
                        <input type="number" name="qty" id="qty" value="1" min="1" max="<?php echo $product['stock']; ?>" class="v-input" oninput="calcTotal()">
                    </div>
                    <div>
                        <label style="font-size: 11px; color: var(--text-gray);">CHARACTER NAME</label>
                        <input type="text" name="character_name" placeholder="In-game character name..." class="v-input" required>
                    </div>
                </div>

                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 25px; border-top: 1px solid #30363d; padding-top: 20px;">
                    <span style="color: var(--text-gray); font-weight: bold;">TOTAL TO PAY:</span>
                    <div class="total-amount">$<span id="total-val"><?php echo number_format($product['price'], 2); ?></span></div>
                </div>

                <button type="submit" class="btn-buy">Buy Now</button>
            </form>
        </div>
    </div>

    <div>
        <div class="chat-card">
            <div class="chat-header">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <div style="width: 10px; height: 10px; border-radius: 50%; background: var(--primary);"></div>
                    <span style="color: white; font-weight: bold; font-size: 14px;"><?php echo htmlspecialchars($product['username']); ?></span>
                </div>
            </div>

            <div class="chat-body" id="chat-window">
                <?php if(!$my_id): ?>
                    <div style="margin-top: 50%; text-align: center; color: var(--text-gray);">
                        Please <a href="login.php" style="color: var(--primary);">Login</a> to chat
                    </div>
                <?php elseif(empty($chat_history)): ?>
                    <div style="margin-top: 50%; text-align: center; color: var(--text-gray);">
                        <i class="fa-regular fa-comments" style="font-size: 40px; opacity: 0.2; display: block; margin-bottom: 10px;"></i>
                        Send a message to the seller
                    </div>
                <?php else: ?>
                    <?php foreach($chat_history as $msg): ?>
                        <div class="msg-bubble <?php echo ($msg['sender_id'] == $my_id) ? 'msg-me' : 'msg-them'; ?>">
                            <?php echo htmlspecialchars($msg['message']); ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <?php if($my_id): ?>
            <form id="chat-form" class="chat-footer">
                <input type="hidden" name="receiver_id" value="<?php echo $product['seller_id']; ?>">
                <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                <div class="chat-input-area">
                    <textarea name="message" id="chat-msg" placeholder="Write a message..." required></textarea>
                    <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
                        <button type="submit" style="background: var(--primary); border: none; width: 35px; height: 35px; border-radius: 50%; cursor: pointer;">
                            <i class="fa-solid fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    function calcTotal() {
        const price = <?php echo (float)$product['price']; ?>;
        const qty = document.getElementById('qty').value;
        document.getElementById('total-val').innerText = (price * qty).toFixed(2);
    }

    const chatWin = document.getElementById('chat-window');
    if(chatWin) chatWin.scrollTop = chatWin.scrollHeight;
</script>

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