<?php
// ==========================================================
// ARQUIVO: admin/gacha_config.php
// Versão: 2.2 - Correção Completa de Compatibilidade PHP (Todas as expressões 'match' substituídas por 'switch')
// ==========================================================

ini_set('display_errors', 1);
error_reporting(E_ALL);

// 1. BLINDAGEM DE SESSÃO
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 2. BLINDAGEM DE INCLUDE E CONEXÃO
if (file_exists('../includes/conexao.php')) {
    require_once '../includes/conexao.php';
} else {
    die("Erro Crítico: Arquivo de conexão não encontrado. Verifique o caminho: ../includes/conexao.php");
}

// ===============================================
// FUNÇÃO showMsg() - CORRIGIDO COM SWITCH
// ===============================================
function showMsg($type, $txt) {
    // Definindo cores de fundo (bgColor)
    switch ($type) {
        case 'success':
            $bgColor = 'rgba(16, 185, 129, 0.2)';
            break;
        case 'danger':
            $bgColor = 'rgba(239, 68, 68, 0.2)';
            break;
        case 'warning':
            $bgColor = 'rgba(245, 158, 11, 0.2)';
            break;
        case 'info':
            $bgColor = 'rgba(59, 130, 246, 0.2)';
            break;
        default:
            $bgColor = 'rgba(255, 255, 255, 0.1)';
    }

    // Definindo cores do texto (textColor)
    switch ($type) {
        case 'warning':
            $textColor = '#fbbf24';
            break;
        case 'danger':
            $textColor = '#ef4444';
            break;
        case 'success':
            $textColor = '#10b981';
            break;
        case 'info':
            $textColor = '#3b82f6';
            break;
        default:
            $textColor = '#ffffff';
    }
    
    return "<div class='alert border-0 alert-dismissible fade show shadow-lg fw-bold' 
                style='background-color: {$bgColor}; color: {$textColor}; border-left: 5px solid {$textColor};' role='alert'>
                <i class='fas fa-info-circle me-2'></i> {$txt}
                <button type='button' class='btn-close btn-close-white' data-bs-dismiss='alert' style='filter: invert(1);'></button>
            </div>";
}
// ------------------------------------------------------------------

// SEGURANÇA (ADMIN)
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }

$stmt = $pdo->prepare("SELECT page_access FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$accData = $stmt->fetch();
if (!$accData || $accData['page_access'] < 3) die("Acesso Negado. Nível de acesso insuficiente.");

$page_title = "Configuração do Gacha";

if(file_exists('../includes/admin_header.php')) include_once '../includes/admin_header.php';


$msg = '';

// --- FUNÇÕES AUXILIARES ---

/**
 * Mapeamento de Raridade para Classe CSS (Dark Theme) - CORRIGIDO COM SWITCH
 * @param string $rarity Nome da raridade.
 * @return string Classe CSS do badge.
 */
function getRarityBadgeClass($rarity) {
    switch ($rarity) {
        case 'Comum':
            return 'bg-secondary';
        case 'Incomum':
            return 'bg-success';
        case 'Rara':
            return 'bg-primary';
        case 'Epica':
            return 'bg-purple';
        case 'Lendaria':
            return 'bg-warning text-dark';
        case 'Mitica':
            return 'bg-danger';
        default:
            return 'bg-info';
    }
}

/**
 * Função de Upload de Imagem Corrigida e Robusta
 * @param array $file Array $_FILES['image_file'].
 * @param string|null $currentImage Caminho da imagem atual no BD (ex: 'images/gacha/nome.png').
 * @return string Caminho da nova imagem para o BD ou mensagem de erro.
 */
function uploadGachaImage($file, $currentImage = null) {
    $target_dir = "../images/gacha/"; // Caminho corrigido relativo ao admin/
    if (!is_dir($target_dir)) {
        if (!mkdir($target_dir, 0777, true)) {
             return "Erro: Falha ao criar o diretório de upload.";
        }
    }

    if ($file['error'] === UPLOAD_ERR_NO_FILE || $file['size'] === 0) {
        return $currentImage; // Retorna o nome da imagem atual
    }
    
    // Validação de erro de upload PHP (limite de tamanho, etc.)
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return "Erro: Falha no upload do arquivo (código: " . $file['error'] . ").";
    }
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if(!in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp'])) { // Adicionado 'webp'
        return "Erro: Formato de imagem inválido. Use PNG, JPG, JPEG, GIF ou WEBP.";
    }
    
    $name = 'gacha_' . uniqid() . '.' . $ext;
    $target_file = $target_dir . $name;
    
    if(move_uploaded_file($file['tmp_name'], $target_file)) {
        // Se um novo arquivo foi enviado e havia um antigo, exclui o antigo (se for um arquivo gacha_ criado)
        if ($currentImage && strpos($currentImage, 'gacha_') !== false) {
             @unlink('../' . $currentImage); // @ para suprimir erro se arquivo não existir
        }
        return 'images/gacha/' . $name; // Caminho a ser salvo no BD
    } else {
        return "Erro: Falha ao mover o arquivo para o destino.";
    }
}


// --- PROCESSAMENTO PRINCIPAL ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // 1. CONFIGURAR PACOTES
    if (isset($_POST['update_options'])) {
        // Sanitização e validação simples dos inputs
        $opt1_qtd = max(1, (int)($_POST['opt1_qtd'] ?? 1));
        $opt1_val = max(1, (int)($_POST['opt1_val'] ?? 100));
        $opt2_qtd = max(1, (int)($_POST['opt2_qtd'] ?? 5));
        $opt2_val = max(1, (int)($_POST['opt2_val'] ?? 450));
        $opt3_qtd = max(1, (int)($_POST['opt3_qtd'] ?? 10));
        $opt3_val = max(1, (int)($_POST['opt3_val'] ?? 800));

        $sql = "UPDATE gacha_config SET opt1_amount=?, opt1_cost=?, opt2_amount=?, opt2_cost=?, opt3_amount=?, opt3_cost=? WHERE id=1";
        try {
            $pdo->prepare($sql)->execute([
                $opt1_qtd, $opt1_val,
                $opt2_qtd, $opt2_val,
                $opt3_qtd, $opt3_val
            ]);
            $msg = showMsg('success', 'Pacotes atualizados!');
        } catch (Exception $e) {
            $msg = showMsg('danger', 'Erro ao atualizar pacotes: ' . $e->getMessage());
        }
    }

    // 2. NOVA TEMPORADA
    if (isset($_POST['new_season'])) {
        $seasonName = trim($_POST['season_name'] ?? '');
        if (!empty($seasonName)) {
            try {
                $pdo->beginTransaction();
                $pdo->query("UPDATE gacha_seasons SET active = 0");
                $pdo->prepare("INSERT INTO gacha_seasons (name, active) VALUES (?, 1)")->execute([$seasonName]);
                $newId = $pdo->lastInsertId();
                $pdo->prepare("UPDATE gacha_config SET current_season_id = ? WHERE id = 1")->execute([$newId]);
                $pdo->commit();
                $msg = showMsg('success', 'Nova temporada **' . htmlspecialchars($seasonName) . '** iniciada!');

            } catch (Exception $e) {
                $pdo->rollBack();
                $msg = showMsg('danger', 'Erro ao iniciar nova temporada: ' . $e->getMessage());
            }
        } else {
             $msg = showMsg('warning', 'O nome da temporada não pode estar vazio.');
        }
    }

    // 3. ADICIONAR ITEM (C/ campo 'description' opcional)
    if (isset($_POST['add_item'])) {
        $currentImage = null; 
        $imgResult = uploadGachaImage($_FILES['image_file'], $currentImage);
        
        if (!$imgResult || strpos($imgResult, 'Erro:') === 0) {
            $msg = showMsg('danger', strpos($imgResult, 'Erro:') === 0 ? $imgResult : 'Erro: Imagem obrigatória não foi enviada ou falhou no upload.');
        } else {
            try {
                // Sanitização e formatação dos dados
                $item_name = trim($_POST['item_name'] ?? '');
                $item_id = (int)($_POST['item_id'] ?? 0);
                $item_count = max(1, (int)($_POST['item_count'] ?? 1));
                $probability = max(0.0001, (float)($_POST['probability'] ?? 0));
                $rarity = $_POST['rarity'] ?? 'Comum';
                $description = trim($_POST['description'] ?? ''); // Opcional, pode ser vazio

                if(empty($item_name) || $item_id <= 0 || $probability <= 0) {
                    $msg = showMsg('warning', 'Campos obrigatórios (Nome, ID e Chance) não preenchidos corretamente.');
                } else {
                    $pdo->prepare("INSERT INTO gacha_items (item_name, item_id, count, image_url, probability, rarity, description) VALUES (?, ?, ?, ?, ?, ?, ?)")
                        ->execute([
                            $item_name, $item_id, $item_count, 
                            $imgResult, $probability, $rarity, $description 
                        ]);
                    $msg = showMsg('success', 'Item **' . htmlspecialchars($item_name) . '** adicionado!');
                }
            } catch (Exception $e) {
                $msg = showMsg('danger', 'Erro ao inserir item. Detalhe: ' . $e->getMessage());
            }
        }
    }

    // 4. EDITAR ITEM (C/ campo 'description' opcional e upload corrigido)
    if (isset($_POST['edit_item'])) {
        $itemId = (int)($_POST['edit_id'] ?? 0);
        $currentImage = $_POST['current_image_url'] ?? null;
        $imgResult = uploadGachaImage($_FILES['image_file'], $currentImage);

        if (strpos($imgResult, 'Erro:') === 0) {
            $msg = showMsg('danger', $imgResult);
        } else {
            try {
                $edit_name = trim($_POST['edit_name'] ?? '');
                $edit_item_id = (int)($_POST['edit_item_id'] ?? 0);
                $edit_count = max(1, (int)($_POST['edit_count'] ?? 1));
                $edit_prob = max(0.0001, (float)($_POST['edit_prob'] ?? 0));
                $edit_rarity = $_POST['edit_rarity'] ?? 'Comum';
                $edit_description = trim($_POST['edit_description'] ?? ''); // Opcional

                if ($itemId <= 0 || empty($edit_name) || $edit_item_id <= 0 || $edit_prob <= 0) {
                     $msg = showMsg('warning', 'Campos obrigatórios (Nome, ID, Chance) não preenchidos ou ID inválido.');
                } else {
                    $sqlInfo = "UPDATE gacha_items SET item_name=?, item_id=?, count=?, probability=?, rarity=?, image_url=?, description=? WHERE id=?";
                    $params = [
                        $edit_name, $edit_item_id, $edit_count, 
                        $edit_prob, $edit_rarity, $imgResult, 
                        $edit_description, 
                        $itemId
                    ];
                    
                    $pdo->prepare($sqlInfo)->execute($params);
                    $msg = showMsg('info', 'Item **' . htmlspecialchars($edit_name) . '** editado com sucesso.');
                }
            } catch (Exception $e) {
                $msg = showMsg('danger', 'Erro ao editar item. Detalhe: ' . $e->getMessage());
            }
        }
    }

    // 5. EXCLUIR ITEM
    if (isset($_POST['delete_item'])) {
        $idToDelete = (int)($_POST['delete_id'] ?? 0);
        if ($idToDelete > 0) {
            try {
                $stmt = $pdo->prepare("SELECT item_name, image_url FROM gacha_items WHERE id = ?");
                $stmt->execute([$idToDelete]);
                $itemData = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($itemData) {
                    $pdo->prepare("DELETE FROM gacha_items WHERE id = ?")->execute([$idToDelete]);
                    $msg = showMsg('danger', 'Item **' . htmlspecialchars($itemData['item_name']) . '** removido.');
                    
                    if ($itemData['image_url'] && strpos($itemData['image_url'], 'gacha_') !== false) {
                         @unlink('../' . $itemData['image_url']);
                    }
                } else {
                    $msg = showMsg('warning', 'Item não encontrado para exclusão.');
                }
            } catch (Exception $e) {
                $msg = showMsg('danger', 'Erro ao deletar item. Detalhe: ' . $e->getMessage());
            }
        }
    }

    // 6. EDIÇÃO EM MASSA
    if (isset($_POST['mass_edit'])) {
        $targetRarity = $_POST['mass_rarity'] ?? 'all'; 
        $action = $_POST['mass_action'] ?? 'set'; 
        $value = (float)($_POST['mass_value'] ?? 0);

        if ($action == 'set' && $value < 0) $value = 0;
        
        $sql = "UPDATE gacha_items SET probability = ";
        if ($action == 'set') $sql .= "?";
        if ($action == 'add') $sql .= "probability + ?";
        if ($action == 'sub') $sql .= "probability - ?";
        
        $sql .= " WHERE 1=1";
        $params = [$value];

        if ($targetRarity != 'all') {
            $sql .= " AND rarity = ?";
            $params[] = $targetRarity;
        }

        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            // Aplica o "chão" de 0.0001 para garantir que a probabilidade não seja zero/negativa
            if ($action != 'set') {
                $sql_check = "UPDATE gacha_items SET probability = GREATEST(0.0001, probability) WHERE 1=1";
                 if ($targetRarity != 'all') $sql_check .= " AND rarity = '$targetRarity'";
                 $pdo->query($sql_check);
            }
           
            $msg = showMsg('info', 'Probabilidades para ' . ($targetRarity == 'all' ? 'TODOS os itens' : 'a raridade **' . htmlspecialchars($targetRarity) . '**') . ' foram ajustadas.');
        } catch (Exception $e) {
            $msg = showMsg('danger', 'Erro ao realizar ajuste em massa: ' . $e->getMessage());
        }
    }
}

// --- DADOS PARA VIEW ---
$config = $pdo->query("SELECT * FROM gacha_config WHERE id = 1")->fetch(PDO::FETCH_ASSOC) ?: [
    'current_season_id' => 1,
    'opt1_amount' => 1, 'opt1_cost' => 100, 
    'opt2_amount' => 5, 'opt2_cost' => 450, 
    'opt3_amount' => 10, 'opt3_cost' => 800
];
$currentSeasonId = $config['current_season_id'] ?? 1;

$stmtSeason = $pdo->prepare("SELECT * FROM gacha_seasons WHERE id = ?");
$stmtSeason->execute([$currentSeasonId]);
$currentSeason = $stmtSeason->fetch(PDO::FETCH_ASSOC) ?: ['name' => 'Padrão'];

// Filtros e Busca
$filterRarity = $_GET['rarity'] ?? 'all';
$search = trim($_GET['q'] ?? '');

$sqlItems = "SELECT * FROM gacha_items WHERE 1=1";
$paramsItems = [];

if ($filterRarity != 'all') {
    $sqlItems .= " AND rarity = ?";
    $paramsItems[] = $filterRarity;
}
if (!empty($search)) {
    $sqlItems .= " AND (item_name LIKE ? OR description LIKE ?)"; 
    $paramsItems[] = "%$search%";
    $paramsItems[] = "%$search%";
}
$sqlItems .= " ORDER BY probability DESC"; 

$stmtItems = $pdo->prepare($sqlItems);
$stmtItems->execute($paramsItems);
$items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);

$totalProbability = array_sum(array_column($items, 'probability'));
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
    /* --- CONFIGURAÇÃO GLOBAL DARK INSANO --- */
    :root {
        --bg-deep: #0f172a;
        --card-bg: #1e293b;
        --border-color: rgba(255,255,255,0.1);
        --text-main: #ffffff;
        --accent: #3b82f6;
        --warning-accent: #f59e0b;
    }
    
    body { 
        background-color: var(--bg-deep) !important; 
        color: var(--text-main) !important; 
        font-family: 'Segoe UI', sans-serif; 
    }
    
    .text-muted, .text-white-50 { 
        color: rgba(255, 255, 255, 0.7) !important; 
    }
    .bg-purple { background-color: #a855f7 !important; color: #fff !important; }

    /* --- CARDS & HEADER --- */
    .admin-card {
        background-color: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.5);
        margin-bottom: 20px;
    }
    
    .card-header-dark {
        background-color: #000000;
        border-bottom: 2px solid var(--accent);
        padding: 15px 20px;
        font-weight: 700;
        text-transform: uppercase;
        font-size: 0.9rem;
        color: var(--text-main);
        display: flex; justify-content: space-between; align-items: center;
    }

    /* --- INPUTS --- */
    .form-control, .form-select, .input-group-text {
        background-color: #020617 !important;
        border: 1px solid #475569 !important;
        color: var(--text-main) !important;
    }
    .form-control:focus, .form-select:focus {
        border-color: var(--accent) !important;
        box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25) !important;
    }
    
    .btn-primary { background-color: var(--accent); border-color: var(--accent); }
    .btn-primary:hover { background-color: #2563eb; border-color: #2563eb; }

    /* --- TABELA (Estilo Insano) --- */
    .table-responsive {
        border-radius: 0 0 12px 12px;
        overflow-x: auto;
    }
    
    .table-dark-custom {
        background-color: var(--card-bg) !important;
    }
    
    .table-dark-custom thead th {
        background-color: #000000 !important;
        border-bottom: 2px solid var(--warning-accent) !important;
        color: #ffffff !important;
        font-weight: 800;
        letter-spacing: 1px;
    }
    
    .table-dark-custom td {
        background-color: var(--card-bg) !important;
        color: var(--text-main) !important;
        border-bottom: 1px solid var(--border-color);
        padding: 12px 15px;
        font-size: 0.85rem;
    }
    
    .item-thumb {
        width: 40px; height: 40px;
        background: #000;
        border: 1px solid #475569;
        border-radius: 6px;
        object-fit: contain;
        padding: 2px;
    }
    .badge-rarity { font-size: 0.7rem; text-transform: uppercase; font-weight: 800; }

    /* Destaque para Probabilidade Total */
    .prob-display {
        padding: 8px 15px;
        border-radius: 8px;
        font-size: 1.1rem;
    }
    .prob-success { background-color: #1e293b; color: #10b981; border: 1px solid #10b981; }
    .prob-danger { background-color: #1e293b; color: #ef4444; border: 1px solid #ef4444; }

    /* Modal */
    .modal-content { background-color: var(--card-bg); color: #fff; border: 1px solid var(--accent); }
    .modal-header { background: #000; border-bottom: 1px solid var(--accent); }
    .btn-close-white { filter: invert(1) grayscale(100%) brightness(200%); }
</style>

<div class="container-fluid py-4" style="max-width: 1400px;">

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <div>
            <h2 class="fw-bold m-0 text-white"><i class="fas fa-magic text-warning me-2"></i> Administração Gacha</h2>
            <p class="text-muted m-0 small">Gerencie itens, probabilidades e configurações de temporada.</p>
        </div>
        <div class="d-flex gap-2 align-items-center">
            <div class="bg-dark px-3 py-2 rounded border border-secondary text-white small">
                Temporada Atual: <strong class="text-warning"><?php echo htmlspecialchars($currentSeason['name']); ?></strong>
            </div>
            </div>
    </div>

    <?php echo $msg; ?>

    <div class="row g-4">
        
        <div class="col-xl-3 col-lg-4">
            
            <div class="admin-card">
                <div class="card-header-dark"><i class="fas fa-coins text-warning me-2"></i> Preços dos Giros (Pacotes)</div>
                <div class="p-3">
                    <form method="POST">
                        <div class="mb-3">
                            <label class="small text-muted mb-1">Opção 1 (Básico)</label>
                            <div class="input-group input-group-sm">
                                <span class="input-group-text">Qtd Giros</span>
                                <input type="number" name="opt1_qtd" class="form-control" value="<?php echo $config['opt1_amount']; ?>" min="1" required>
                                <span class="input-group-text">Custo Pts</span>
                                <input type="number" name="opt1_val" class="form-control" value="<?php echo $config['opt1_cost']; ?>" min="1" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted mb-1">Opção 2 (Intermediário)</label>
                            <div class="input-group input-group-sm">
                                <span class="input-group-text">Qtd Giros</span>
                                <input type="number" name="opt2_qtd" class="form-control" value="<?php echo $config['opt2_amount']; ?>" min="1" required>
                                <span class="input-group-text">Custo Pts</span>
                                <input type="number" name="opt2_val" class="form-control" value="<?php echo $config['opt2_cost']; ?>" min="1" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted mb-1">Opção 3 (Avançado)</label>
                            <div class="input-group input-group-sm">
                                <span class="input-group-text">Qtd Giros</span>
                                <input type="number" name="opt3_qtd" class="form-control" value="<?php echo $config['opt3_amount']; ?>" min="1" required>
                                <span class="input-group-text">Custo Pts</span>
                                <input type="number" name="opt3_val" class="form-control" value="<?php echo $config['opt3_cost']; ?>" min="1" required>
                            </div>
                        </div>
                        <button type="submit" name="update_options" class="btn btn-primary btn-sm w-100 fw-bold">Salvar Preços</button>
                    </form>
                </div>
            </div>

            <div class="admin-card">
                <div class="card-header-dark"><i class="fas fa-calendar-alt text-info me-2"></i> Iniciar Nova Temporada</div>
                <div class="p-3">
                    <form method="POST" onsubmit="return confirm('ATENÇÃO! Iniciar uma nova temporada irá DESATIVAR a atual. Isso é recomendado apenas quando os itens da nova temporada estiverem prontos. Continuar?');">
                        <label for="season_name" class="small text-muted mb-1">Nome da Nova Temporada</label>
                        <div class="input-group">
                            <input type="text" id="season_name" name="season_name" class="form-control form-control-sm" placeholder="Ex: Season Fire" required>
                            <button name="new_season" class="btn btn-info btn-sm fw-bold text-white">Iniciar</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="admin-card" style="border-color: #ef4444;">
                <div class="card-header-dark" style="color: #ef4444;"><i class="fas fa-sliders-h me-2"></i> Ajuste de Chance em Massa (%)</div>
                <div class="p-3">
                    <form method="POST" onsubmit="return confirm('Isso afetará VÁRIOS itens. Confirme se os valores estão corretos!');">
                        <div class="mb-2">
                            <label for="mass_rarity" class="small text-muted mb-1">Alvo da Raridade</label>
                            <select id="mass_rarity" name="mass_rarity" class="form-select form-select-sm">
                                <option value="all">Todas as Raridades</option>
                                <option value="Comum">Apenas Comum</option>
                                <option value="Incomum">Apenas Incomum</option>
                                <option value="Rara">Apenas Rara</option>
                                <option value="Epica">Apenas Épica</option>
                                <option value="Lendaria">Apenas Lendária</option>
                                <option value="Mitica">Apenas Mítica</option>
                            </select>
                        </div>
                        <div class="mb-2">
                            <label for="mass_action" class="small text-muted mb-1">Ação</label>
                            <select id="mass_action" name="mass_action" class="form-select form-select-sm">
                                <option value="set">Definir Valor Fixo (=)</option>
                                <option value="add">Adicionar (+)</option>
                                <option value="sub">Subtrair (-)</option>
                            </select>
                        </div>
                        <div class="input-group input-group-sm mb-2">
                            <input type="number" step="0.0001" name="mass_value" class="form-control" placeholder="Valor % (Ex: 0.5)" required>
                            <button type="submit" name="mass_edit" class="btn btn-danger fw-bold">Aplicar Ajuste</button>
                        </div>
                        <small class="text-white-50">Use casas decimais para alta precisão (ex: 0.0001)</small>
                    </form>
                </div>
            </div>

        </div>

        <div class="col-xl-9 col-lg-8">
            
            <div class="admin-card">
                <div class="card-header-dark" style="color: #10b981;"><i class="fas fa-plus-circle me-2"></i> Novo Item Gacha</div>
                <div class="p-3">
                    <form method="POST" enctype="multipart/form-data" class="row g-3 align-items-end">
                        <div class="col-md-3 col-sm-6">
                            <label class="small text-muted">Nome</label>
                            <input type="text" name="item_name" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <label class="small text-muted">ID (Game)</label>
                            <input type="number" name="item_id" class="form-control form-control-sm" min="1" required>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <label class="small text-muted">Raridade</label>
                            <select name="rarity" class="form-select form-select-sm">
                                <option value="Comum">Comum</option>
                                <option value="Incomum">Incomum</option>
                                <option value="Rara">Rara</option>
                                <option value="Epica">Épica</option>
                                <option value="Lendaria">Lendária</option>
                                <option value="Mitica">Mítica</option>
                            </select>
                        </div>
                        <div class="col-md-3 col-sm-6">
                            <label class="small text-muted">Chance (%)</label>
                            <input type="number" step="0.0001" name="probability" class="form-control form-control-sm" placeholder="Ex: 0.5000" min="0.0001" required>
                        </div>
                        
                        <div class="col-md-6 col-lg-5">
                            <label class="small text-muted">Descrição (Opcional - Tooltip no Guia)</label>
                            <input type="text" name="description" class="form-control form-control-sm" placeholder="Descreva o efeito do item (máx 255 caracteres)" maxlength="255">
                        </div>
                        <div class="col-md-2 col-sm-6">
                            <label class="small text-muted">Qtd. (x)</label>
                            <input type="number" name="item_count" class="form-control form-control-sm" value="1" min="1" required>
                        </div>
                        <div class="col-md-4 col-sm-6">
                            <label class="small text-muted">Imagem (Upload) **Obrigatório**</label>
                            <input type="file" name="image_file" class="form-control form-control-sm" accept="image/png, image/jpeg, image/gif, image/webp" required>
                        </div>
                        
                        <div class="col-12 mt-3">
                            <button type="submit" name="add_item" class="btn btn-success btn-sm w-100 fw-bold"><i class="fas fa-plus-square me-1"></i> ADICIONAR NOVO ITEM À LOTERIA</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="admin-card">
                <div class="card-header-dark">
                    <span><i class="fas fa-list me-2"></i> Itens Atuais</span>
                    <span class="prob-display <?php echo (round($totalProbability, 4) == 100) ? 'prob-success' : 'prob-danger'; ?>">
                        SOMA DE PROBABILIDADE: <strong class="text-white"><?php echo number_format($totalProbability, 4); ?>%</strong>
                    </span>
                </div>

                <?php if (round($totalProbability, 4) != 100): ?>
                    <div class="alert alert-danger fw-bold shadow-sm rounded-0 border-0 m-0">
                        <i class="fas fa-exclamation-triangle me-2"></i> **ATENÇÃO!** A soma total das probabilidades não está exatamente em 100%. Isso pode causar drops inesperados.
                    </div>
                <?php endif; ?>

                <div class="p-3">
                    <form class="d-flex gap-2 mb-3" method="GET">
                        <select name="rarity" class="form-select form-select-sm w-auto">
                            <option value="all">Todas as Raridades</option>
                            <option value="Comum" <?php if($filterRarity=='Comum') echo 'selected'; ?>>Comum</option>
                            <option value="Incomum" <?php if($filterRarity=='Incomum') echo 'selected'; ?>>Incomum</option>
                            <option value="Rara" <?php if($filterRarity=='Rara') echo 'selected'; ?>>Rara</option>
                            <option value="Epica" <?php if($filterRarity=='Epica') echo 'selected'; ?>>Épica</option>
                            <option value="Lendaria" <?php if($filterRarity=='Lendaria') echo 'selected'; ?>>Lendária</option>
                            <option value="Mitica" <?php if($filterRarity=='Mitica') echo 'selected'; ?>>Mítica</option>
                        </select>
                        <input type="text" name="q" class="form-control form-control-sm" placeholder="Buscar por Nome ou Descrição..." value="<?php echo htmlspecialchars($search); ?>">
                        <button class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
                        <?php if($search || $filterRarity!='all'): ?>
                            <a href="gacha_config.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-times"></i> Limpar</a>
                        <?php endif; ?>
                    </form>
                </div>

                <div class="table-responsive">
                    <table class="table table-dark-custom mb-0">
                        <thead>
                            <tr>
                                <th class="ps-3">Item / Descrição</th>
                                <th>ID</th>
                                <th>Qtd</th>
                                <th>Raridade</th>
                                <th>Chance</th>
                                <th class="text-end pe-3">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($items)): ?>
                                <tr><td colspan="6" class="text-center py-5 text-muted">Nenhum item encontrado.</td></tr>
                            <?php else: ?>
                                <?php foreach($items as $item):  ?>
                                <tr>
                                    <td class="ps-3">
                                        <div class="d-flex align-items-center">
                                            <img src="../<?php echo htmlspecialchars($item['image_url']); ?>" class="item-thumb me-3" onerror="this.src='../images/default.png'" alt="<?php echo htmlspecialchars($item['item_name']); ?>">
                                            <div>
                                                <span class="fw-bold text-white d-block"><?php echo htmlspecialchars($item['item_name']); ?></span>
                                                <small class="text-muted d-block text-truncate" style="max-width: 250px;" title="<?php echo htmlspecialchars($item['description'] ?? 'Sem descrição.'); ?>"><?php echo htmlspecialchars($item['description'] ?? 'Sem descrição.'); ?></small>
                                            </div>
                                        </div>
                                    </td>
                                    <td><code class="text-info"><?php echo $item['item_id']; ?></code></td>
                                    <td><?php echo $item['count']; ?>x</td>
                                    <td><span class="badge <?php echo getRarityBadgeClass($item['rarity']); ?> badge-rarity"><?php echo $item['rarity']; ?></span></td>
                                    <td class="text-warning fw-bold"><?php echo number_format($item['probability'], 4); ?>%</td>
                                    <td class="text-end pe-3">
                                        <button class="btn btn-sm btn-primary me-1" onclick='openEdit(<?php echo json_encode($item); ?>)'><i class="fas fa-edit"></i></button>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('ATENÇÃO: Deletar o item: <?php echo addslashes($item['item_name']); ?>?');">
                                            <input type="hidden" name="delete_id" value="<?php echo $item['id']; ?>">
                                            <button name="delete_item" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-white"><i class="fas fa-pen-to-square me-2"></i> Editar Item: <span id="modal_edit_name_title" class="text-warning"></span></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <input type="hidden" name="current_image_url" id="current_image_url">
                    <div class="mb-3">
                        <label class="small text-muted">Nome</label>
                        <input type="text" name="edit_name" id="edit_name" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="small text-muted">Descrição (Opcional - Máx 255)</label>
                        <input type="text" name="edit_description" id="edit_description" class="form-control" maxlength="255">
                    </div>

                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="small text-muted">ID (Game)</label>
                            <input type="number" name="edit_item_id" id="edit_item_id" class="form-control" min="1" required>
                        </div>
                        <div class="col-6">
                            <label class="small text-muted">Quantidade</label>
                            <input type="number" name="edit_count" id="edit_count" class="form-control" min="1" required>
                        </div>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="small text-muted">Probabilidade (%)</label>
                            <input type="number" step="0.0001" name="edit_prob" id="edit_prob" class="form-control" min="0.0001" required>
                        </div>
                        <div class="col-6">
                            <label class="small text-muted">Raridade</label>
                            <select name="edit_rarity" id="edit_rarity" class="form-select">
                                <option value="Comum">Comum</option>
                                <option value="Incomum">Incomum</option>
                                <option value="Rara">Rara</option>
                                <option value="Epica">Épica</option>
                                <option value="Lendaria">Lendária</option>
                                <option value="Mitica">Mítica</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small text-muted d-block">Nova Imagem (Opcional - Manterá a atual se vazio)</label>
                        <input type="file" name="image_file" class="form-control mb-2" accept="image/png, image/jpeg, image/gif, image/webp">
                        <small class="text-muted d-block">Imagem Atual: <img src="" id="current_image_preview" style="width:30px; height:30px; object-fit:contain; border: 1px solid #334155; padding: 2px;" onerror="this.src='../images/default.png'" alt="Preview"></small>
                    </div>
                    <button type="submit" name="edit_item" class="btn btn-warning w-100 fw-bold"><i class="fas fa-save me-1"></i> SALVAR ALTERAÇÕES</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function openEdit(item) {
        document.getElementById('edit_id').value = item.id;
        document.getElementById('edit_name').value = item.item_name;
        document.getElementById('edit_description').value = item.description || ''; 
        document.getElementById('edit_item_id').value = item.item_id;
        document.getElementById('edit_count').value = item.count;
        document.getElementById('edit_prob').value = item.probability;
        document.getElementById('edit_rarity').value = item.rarity;
        
        document.getElementById('current_image_url').value = item.image_url; 
        
        document.getElementById('current_image_preview').src = '../' + item.image_url;
        document.getElementById('modal_edit_name_title').textContent = item.item_name;


        new bootstrap.Modal(document.getElementById('editModal')).show();
    }
</script>

<?php 
if(file_exists('../includes/admin_footer.php')) {
    include_once '../includes/admin_footer.php'; 
} else if(file_exists('../includes/footer.php')) {
    include_once '../includes/footer.php';
}
?>