<?php
// shop.php
session_start();
$page_title = "Shop & Serviços";
// Assume-se que 'includes/conexao.php' e 'includes/header.php' existem e funcionam
require 'includes/conexao.php';
include 'includes/header.php';

// --- FUNÇÃO DE MENSAGEM ---
function showMsg($type, $text) {
    $icon = '';
    switch ($type) {
        case 'success': $icon = 'check-circle'; break;
        case 'warning': $icon = 'exclamation-triangle'; break;
        case 'danger': $icon = 'exclamation-circle'; break;
        default: $icon = 'info-circle';
    }
    return "<div class='alert alert-{$type} shadow-sm border-0 d-flex align-items-center mb-4'><i class='fas fa-{$icon} fa-2x me-3'></i><div>{$text}</div></div>";
}

// --- SEGURANÇA: Redireciona se não estiver logado ---
if (!isset($_SESSION['account_id'])) {
    header("Location: login.php");
    exit;
}

$account_id = $_SESSION['account_id'];
$msg = '';

// --- 1. BUSCAR PERSONAGENS DA CONTA ---
try {
    $stmtChars = $pdo->prepare("SELECT id, name, level, vocation FROM players WHERE account_id = ? AND deleted = 0 ORDER BY level DESC");
    $stmtChars->execute([$account_id]);
    $characters = $stmtChars->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Erro ao carregar personagens: " . $e->getMessage());
}


$char_warning = '';
if (empty($characters)) {
    // A validação de personagem para ITENS será feita no POST.
    $char_warning = showMsg('warning', 'Você não tem nenhum personagem criado. Você só poderá comprar serviços de conta (como VIP) até criar um.');
}

// --- SALDO INICIAL ---
try {
    $stmtUser = $pdo->prepare("SELECT post_points FROM accounts WHERE id = ?");
    $stmtUser->execute([$account_id]);
    $userPoints = $stmtUser->fetchColumn();
} catch (PDOException $e) {
    die("Erro ao carregar saldo: " . $e->getMessage());
}


// --- PROCESSAR COMPRA ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['buy_offer'])) {
    
    $offer_id = (int)$_POST['offer_id'];
    $qtd_buy = (int)$_POST['qtd_buy'];
    // target_player_id é 0 (VIP/Serviço de Conta) ou o ID do char (Item/Serviço de Char)
    $target_player_id = isset($_POST['target_player_id']) ? (int)$_POST['target_player_id'] : 0; 

    if($qtd_buy < 1) $qtd_buy = 1;

    try {
        $pdo->beginTransaction();

        // 1. Dados da Oferta com LOCK (para evitar que a oferta mude de preço durante a transação)
        $stmt = $pdo->prepare("SELECT * FROM shop_offers WHERE id = ? FOR UPDATE");
        $stmt->execute([$offer_id]);
        $offer = $stmt->fetch(PDO::FETCH_ASSOC);

        // 2. Rebusca dados da conta com LOCK (para garantir saldo atualizado e prevenir gasto duplo)
        $stmtUserCheck = $pdo->prepare("SELECT post_points FROM accounts WHERE id = ? FOR UPDATE");
        $stmtUserCheck->execute([$account_id]);
        $currentPoints = $stmtUserCheck->fetchColumn();

        $totalCost = 0;
        $validTarget = false;
        $target_player_name = '';
        $isAccountService = false;
        
        // --- Validações ---
        if (!$offer) {
            $msg = showMsg('danger', 'Oferta inválida!');
        } else {
            $totalCost = $offer['points'] * $qtd_buy;
            $isAccountService = ($offer['offer_type'] == 'vip');

            // Validação do saldo
            if ($currentPoints < $totalCost) {
                $msg = showMsg('danger', 'Saldo insuficiente. Você precisa de <strong>'.number_format($totalCost, 0, ',', '.').'</strong> pontos.');
            
            // Validação do personagem para itens/serviços de personagem
            } elseif (!$isAccountService) {
                
                // Verifica se o ID do personagem pertence à conta
                foreach($characters as $char) {
                    if ($char['id'] == $target_player_id) {
                        $validTarget = true;
                        $target_player_name = $char['name'];
                        break;
                    }
                }
                
                if (!$validTarget) {
                    $msg = showMsg('danger', 'Personagem de destino inválido ou não selecionado. Recarregue a página e tente novamente.');
                }
            }
        }
        
        // --- Processamento da Transação ---
        if (empty($msg)) {
            
            // 1. Debitar Pontos
            $pdo->prepare("UPDATE accounts SET post_points = post_points - ? WHERE id = ?")->execute([$totalCost, $account_id]);

            // 2. Entregar e Logar
            $status_log = 'pending';
            $finalCount = $offer['count'] * $qtd_buy;
            
            // A. ENTREGA VIP (IMEDIATA)
            if ($isAccountService) {
                $days = $finalCount;
                $pdo->prepare("UPDATE accounts SET premdays = premdays + ? WHERE id = ?")->execute([$days, $account_id]);
                $status_log = 'delivered'; // Marca como entregue pois não precisa do servidor do jogo
                $msg = showMsg('success', "Sucesso! Adicionado <strong>{$days} dias VIP</strong> na conta.");
                $target_player_id = 0; // O alvo é a conta
            
            // B. ENTREGA DE ITEM/SERVIÇO (PENDENTE PARA O LUA)
            } else {
                // target_player_name já está definido pela validação
                $msg = showMsg('success', "Compra realizada! <strong>{$finalCount}x {$offer['offer_name']}</strong> será entregue para <strong>{$target_player_name}</strong> assim que o personagem logar. Status: PENDENTE");
            }

            // 3. Log da Transação na shop_history
            $log = $pdo->prepare("INSERT INTO shop_history (account_id, player_id, offer_name, itemid, count, points_cost, date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $log->execute([
                $account_id,
                $target_player_id,  // O ID do personagem (GUID) ou 0 se for serviço de conta.
                $offer['offer_name'],
                $offer['itemid'],   
                $finalCount,        
                $totalCost,         
                time(),             
                $status_log
            ]);

            $pdo->commit();
            
            // Atualiza saldo visual para o usuário
            $userPoints = $currentPoints - $totalCost;
        } else {
            // Se houve erro de validação (ex: saldo insuficiente), apenas faz o rollback
             if($pdo->inTransaction()) $pdo->rollBack();
        }

    } catch (Exception $e) {
        if($pdo->inTransaction()) $pdo->rollBack();
        // Em um ambiente de produção, logar $e->getMessage() mas não mostrar ao usuário final
        $msg = showMsg('danger', 'Erro inesperado ao processar a compra. Contate a administração.');
    }
} 

// --- 2. BUSCAR CATEGORIAS E OFERTAS (APÓS A COMPRA, PARA ATUALIZAR A LISTA) ---
try {
    $categories = $pdo->query("SELECT * FROM shop_categories ORDER BY priority ASC")->fetchAll(PDO::FETCH_ASSOC);
    $offers = $pdo->query("SELECT * FROM shop_offers ORDER BY category_id ASC, id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Erro ao carregar dados do Shop: " . $e->getMessage());
}
?>

<style>
    /* Estilos Visuais para o Shop */
    .shop-header {
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        padding: 40px 0 80px 0;
        margin-top: -20px;
        position: relative;
        overflow: hidden;
    }
    .shop-nav {
        margin-top: -40px;
        background: rgba(30, 41, 59, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 12px;
        padding: 10px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        border: 1px solid rgba(255,255,255,0.1);
    }
    .nav-pills .nav-link {
        color: #94a3b8;
        font-weight: 600;
        border-radius: 8px;
        padding: 10px 20px;
        transition: all 0.3s;
    }
    .nav-pills .nav-link.active {
        background-color: #3b82f6;
        color: #fff;
        box-shadow: 0 4px 10px rgba(59, 130, 246, 0.4);
    }
    
    .product-card {
        background: #1e293b;
        border: 1px solid rgba(255,255,255,0.05);
        border-radius: 16px;
        overflow: hidden;
        transition: transform 0.3s, box-shadow 0.3s;
        height: 100%;
        display: flex;
        flex-direction: column;
    }
    .product-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 15px 30px rgba(0,0,0,0.3);
        border-color: #3b82f6;
    }
    .product-img-box {
        height: 160px;
        background: radial-gradient(circle, rgba(255,255,255,0.05) 0%, rgba(30,41,59,0) 70%);
        display: flex; align-items: center; justify-content: center;
        padding: 20px;
        position: relative;
    }
    .product-img-box img {
        max-height: 100px; max-width: 100px;
        filter: drop-shadow(0 5px 10px rgba(0,0,0,0.5));
        transition: transform 0.3s;
    }
    .product-card:hover .product-img-box img { transform: scale(1.1); }
    
    .badge-discount {
        position: absolute; top: 15px; right: 15px;
        background: #ef4444; color: white;
        font-weight: 800; padding: 5px 10px; border-radius: 6px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.2);
    }
    
    .btn-buy {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        border: none; color: white; font-weight: 700;
        width: 100%; padding: 12px; border-radius: 10px;
        transition: all 0.2s;
    }
    .btn-buy:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(37,99,235,0.4); }
    .btn-buy:disabled { background: #334155; color: #64748b; cursor: not-allowed; }
    
    .qty-input {
        background: #0f172a; border: 1px solid rgba(255,255,255,0.1);
        color: white; text-align: center; font-weight: bold;
        width: 60px; border-radius: 8px;
    }
    .char-select {
        background: #0f172a; border: 1px solid rgba(255,255,255,0.1);
        color: white; border-radius: 8px; padding: 8px; width: 100%;
        margin-bottom: 10px;
    }
</style>

<div class="shop-header">
    <div class="container d-flex flex-wrap justify-content-between align-items-center">
        <div>
            <h1 class="display-5 fw-bold text-white mb-0" style="font-family: 'Rajdhani', sans-serif;">SHOP ONLINE</h1>
            <p class="text-white-50 mt-1">Itens entregues automaticamente no jogo.</p>
        </div>
        <div class="bg-dark bg-opacity-50 p-3 rounded-pill border border-secondary d-flex align-items-center">
            <span class="text-white-50 me-3">SEU SALDO:</span>
            <span class="text-warning fw-bold fs-3 me-3"><i class="fas fa-coins me-1"></i> <?php echo number_format($userPoints, 0, ',', '.'); ?></span>
            <a href="donate.php" class="btn btn-success rounded-pill fw-bold px-4 shadow-sm"><i class="fas fa-plus-circle"></i> Adicionar</a>
        </div>
    </div>
</div>

<div class="container pb-5">
    
    <div class="shop-nav mb-5">
        <ul class="nav nav-pills justify-content-center" id="pills-tab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="pills-all-tab" data-bs-toggle="pill" data-bs-target="#pills-all" type="button"><i class="fas fa-th-large me-2"></i> Todos</button>
            </li>
            <?php foreach($categories as $cat): ?>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="pills-cat<?php echo $cat['id']; ?>-tab" data-bs-toggle="pill" data-bs-target="#pills-cat<?php echo $cat['id']; ?>" type="button"><i class="fas <?php echo htmlspecialchars($cat['icon']); ?> me-2"></i> <?php echo htmlspecialchars($cat['name']); ?></button>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <?php 
    echo $msg; 
    if (!empty($char_warning)) echo $char_warning;
    ?>

    <div class="tab-content" id="pills-tabContent">
        
        <div class="tab-pane fade show active" id="pills-all">
            <div class="row g-4">
                <?php foreach($offers as $item): renderProductCard($item, $userPoints, $characters); endforeach; ?>
            </div>
        </div>

        <?php foreach($categories as $cat): ?>
        <div class="tab-pane fade" id="pills-cat<?php echo $cat['id']; ?>">
            <div class="row g-4">
                <?php 
                $hasItem = false;
                foreach($offers as $item): 
                    if($item['category_id'] == $cat['id']):
                        renderProductCard($item, $userPoints, $characters); 
                        $hasItem = true;
                    endif;
                endforeach; 
                if(!$hasItem): echo '<div class="text-center text-white-50 py-5"><h4>Nenhum item nesta categoria.</h4></div>'; endif;
                ?>
            </div>
        </div>
        <?php endforeach; ?>

    </div>
</div>

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

// FUNÇÃO PARA RENDERIZAR O CARD DO PRODUTO
function renderProductCard($item, $userPoints, $characters) {
    
    $isAccountService = ($item['offer_type'] == 'vip');
    $canBuy = ($userPoints >= $item['points']);
    $needsChar = (!$isAccountService && empty($characters));

    // Imagem
    $imgSrc = htmlspecialchars($item['image']);
    if(empty($imgSrc) || $imgSrc == 'default_item.png') $imgSrc = 'images/no_item.png';

    $hasDiscount = ($item['points_old'] > $item['points']);
    $discount = $hasDiscount ? round((($item['points_old'] - $item['points']) / $item['points_old']) * 100) : 0;
    ?>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="product-card">
            <?php if($hasDiscount): ?><span class="badge-discount">-<?php echo $discount; ?>%</span><?php endif; ?>
            
            <div class="product-img-box">
                <img src="<?php echo $imgSrc; ?>" alt="<?php echo htmlspecialchars($item['offer_name']); ?>" onerror="this.src='images/no_item.png'">
            </div>
            
            <div class="p-4 d-flex flex-column flex-grow-1">
                <h5 class="fw-bold text-white mb-2 text-center text-truncate" title="<?php echo htmlspecialchars($item['offer_name']); ?>">
                    <?php echo htmlspecialchars($item['offer_name']); ?>
                </h5>
                <p class="text-white-50 small text-center mb-3 flex-grow-1" style="min-height: 40px; line-height: 1.4;">
                    <?php echo nl2br(htmlspecialchars($item['offer_desc'])); ?>
                </p>
                
                <div class="border-top border-secondary pt-3 mt-auto">
                    <div class="d-flex justify-content-center align-items-end mb-3">
                        <?php if($hasDiscount): ?>
                            <small class="text-decoration-line-through text-muted me-2 mb-1"><?php echo $item['points_old']; ?></small>
                        <?php endif; ?>
                        <span class="text-info fw-bold fs-3"><?php echo number_format($item['points'], 0, ',', '.'); ?></span>
                        <small class="text-info ms-1 mb-1">pts</small>
                    </div>

                    <form method="POST" class="d-flex flex-column gap-2" onsubmit="return confirm('Confirmar compra de ' + this.qtd_buy.value + 'x <?php echo str_replace("'", "\'", $item['offer_name']); ?>?');">
                        <input type="hidden" name="offer_id" value="<?php echo $item['id']; ?>">
                        
                        <?php if (!$isAccountService): // Se for item, precisa escolher o char ?>
                            <select name="target_player_id" class="char-select" required <?php echo $needsChar ? 'disabled' : ''; ?>>
                                <option value="" disabled selected>-- Enviar para --</option>
                                <?php foreach($characters as $char): ?>
                                    <option value="<?php echo $char['id']; ?>">
                                        <?php echo htmlspecialchars($char['name']); ?> (Lvl <?php echo $char['level']; ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        <?php else: // VIP/Serviços de Conta ?>
                            <input type="hidden" name="target_player_id" value="0">
                        <?php endif; ?>

                        <div class="d-flex gap-2">
                            <input type="number" name="qtd_buy" class="form-control qty-input" value="1" min="1" max="100">
                            <button type="submit" name="buy_offer" class="btn-buy" <?php echo ($canBuy && !$needsChar) ? '' : 'disabled'; ?>>
                                <?php if($canBuy): ?>
                                    <i class="fas fa-shopping-cart me-1"></i> COMPRAR
                                <?php else: ?>
                                    <i class="fas fa-lock me-1"></i> SALDO INSUFICIENTE
                                <?php endif; ?>
                            </button>
                        </div>
                        <?php if ($needsChar): ?>
                            <small class="text-danger mt-1 text-center">Crie um personagem para comprar este item.</small>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php
}
?>