<?php
// admin/config_seller.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// SEGURANÇA ADMIN
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }
$stmt = $pdo->prepare("SELECT group_id FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();
if (!$acc || $acc['group_id'] < 3) die("Acesso Negado."); // Mude para group_id se page_access não for o campo de grupo.

$page_title = "Configuração Venda Personagens";

if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

$msg = '';

// PROCESSAR CONFIGURAÇÃO
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_config'])) {
    $commission = (int)$_POST['admin_commission_percent'];
    $storage_key = (int)$_POST['char_item_storage_key'];
    $min_level = (int)$_POST['min_level_to_sell'];
    $min_price = (int)$_POST['min_price_pps'];

    if ($commission < 0 || $commission > 100) {
        $msg = '<div class="alert alert-danger shadow-sm border-0"><i class="fas fa-times-circle me-2"></i> Porcentagem de comissão deve ser entre 0 e 100.</div>';
    } else {
        try {
            $stmt = $pdo->prepare("
                UPDATE character_seller_config
                SET admin_commission_percent = ?, char_item_storage_key = ?, min_level_to_sell = ?, min_price_pps = ?
                WHERE id = 1
            ");
            $stmt->execute([$commission, $storage_key, $min_level, $min_price]);
            $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-check-circle me-2"></i> Configurações salvas com sucesso!</div>';
        } catch (Exception $e) {
            $msg = '<div class="alert alert-danger shadow-sm border-0">Erro SQL: ' . $e->getMessage() . '</div>';
        }
    }
}

// BUSCAR CONFIGURAÇÃO ATUAL
$config = $pdo->query("SELECT * FROM character_seller_config WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
if (!$config) {
    // Garante que a linha padrão exista se o select falhar (código de DDL acima resolve isso)
    $config = ['admin_commission_percent' => 10, 'char_item_storage_key' => 98765, 'min_level_to_sell' => 100, 'min_price_pps' => 50];
}
?>

<style>
    /* Admin Dark Theme */
    body { background-color: #0f172a; color: #f8fafc; font-family: 'Poppins', sans-serif; }
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 12px; }
    .table { color: #cbd5e1; }
    .table thead th { background-color: #0f172a; border-bottom: 2px solid #334155; color: #94a3b8; }
    .form-control { background-color: #0b1120; color: #f8fafc; border-color: #334155; }
</style>

<div class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-secondary pb-3">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-handshake text-info me-2"></i>Bazaar de Personagens: Configurações</h2>
            <p class="text-white-50 m-0">Defina a taxa de comissão e os requisitos para venda.</p>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="card shadow p-4 border-top border-4 border-info">
        <form method="POST">
            <div class="row g-4">
                <div class="col-md-6">
                    <label class="form-label text-white fw-bold">Comissão do Admin (%)</label>
                    <input type="number" name="admin_commission_percent" class="form-control" value="<?php echo $config['admin_commission_percent']; ?>" required min="0" max="100">
                    <div class="form-text text-white-50">Porcentagem do valor da venda que fica para a conta do servidor. Ex: 10% de 1000 PPS = 100 PPS.</div>
                </div>

                <div class="col-md-6">
                    <label class="form-label text-white fw-bold">Storage Key para Itens (Game)</label>
                    <input type="number" name="char_item_storage_key" class="form-control" value="<?php echo $config['char_item_storage_key']; ?>" required>
                    <div class="form-text text-white-50">Chave de Storage usada no jogo para marcar itens de "Char Bazaar". **NÃO ALTERE SE NÃO SOUBER!**</div>
                </div>
                
                <div class="col-md-6">
                    <label class="form-label text-white fw-bold">Nível Mínimo para Vender</label>
                    <input type="number" name="min_level_to_sell" class="form-control" value="<?php echo $config['min_level_to_sell']; ?>" required min="1">
                    <div class="form-text text-white-50">Nível mínimo que o personagem deve ter para ser listado no Bazaar.</div>
                </div>

                <div class="col-md-6">
                    <label class="form-label text-white fw-bold">Preço Mínimo (PPS)</label>
                    <input type="number" name="min_price_pps" class="form-control" value="<?php echo $config['min_price_pps']; ?>" required min="1">
                    <div class="form-text text-white-50">Preço mínimo que um jogador pode definir para seu personagem.</div>
                </div>
                
                <div class="col-12 mt-4">
                    <button type="submit" name="update_config" class="btn btn-info w-100 fw-bold shadow-lg">
                        <i class="fas fa-save me-2"></i> SALVAR CONFIGURAÇÕES
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

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