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

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

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

$stmt = $pdo->prepare("SELECT page_access, name FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$adminUser = $stmt->fetch();

if (!$adminUser || $adminUser['page_access'] < 3) {
    die("<div class='container p-5 text-center'><h1>Acesso Negado</h1><a href='../index.php'>Voltar</a></div>");
}

$page_title = "Centro de Controle de Jogadores";

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

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

// --- PROCESSAMENTOS POST ---

// 1. EDITAR DADOS DO PERSONAGEM (Level, Sexo, Nome, Vocation)
if (isset($_POST['edit_player'])) {
    $pid = (int)$_POST['player_id'];
    $newName = trim($_POST['player_name']);
    $newLevel = (int)$_POST['player_level'];
    $newSex = (int)$_POST['player_sex'];
    $newVoc = (int)$_POST['player_voc'];
    $newTown = (int)$_POST['player_town'];

    try {
        $pdo->beginTransaction();
        $upd = $pdo->prepare("UPDATE players SET name=?, level=?, sex=?, vocation=?, town_id=? WHERE id=?");
        $upd->execute([$newName, $newLevel, $newSex, $newVoc, $newTown, $pid]);

        // Log
        $logDesc = "Editou Player ID {$pid}: Nome={$newName}, Lvl={$newLevel}, Sex={$newSex}, Voc={$newVoc}";
        $pdo->prepare("INSERT INTO site_admin_logs (admin_id, target_id, action_type, description, ip, date) VALUES (?, ?, 'EDIT_PLAYER', ?, ?, ?)")
            ->execute([$admin_id, $pid, $logDesc, $_SERVER['REMOTE_ADDR'], time()]);

        $pdo->commit();
        $msg = showMsg('success', 'Dados do personagem atualizados com sucesso!');
    } catch (Exception $e) {
        $pdo->rollBack();
        $msg = showMsg('danger', 'Erro ao editar personagem: ' . $e->getMessage());
    }
}

// 2. EDITAR DADOS DA CONTA (Email, Senha, Pontos)
if (isset($_POST['edit_account'])) {
    $acc_id = (int)$_POST['account_id'];
    $newEmail = trim($_POST['acc_email']);
    $newPass = trim($_POST['acc_pass']);
    $pointsOp = $_POST['points_op']; // add ou remove
    $pointsVal = (int)$_POST['points_val'];
    
    try {
        $pdo->beginTransaction();
        
        // Atualiza Email
        $pdo->prepare("UPDATE accounts SET email = ? WHERE id = ?")->execute([$newEmail, $acc_id]);
        
        // Atualiza Senha (Se preenchida)
        if (!empty($newPass)) {
            $passHash = sha1($newPass); // Padrão Tibia SHA1
            $pdo->prepare("UPDATE accounts SET password = ? WHERE id = ?")->execute([$passHash, $acc_id]);
        }

        // Atualiza Pontos
        if ($pointsVal > 0) {
            if ($pointsOp == 'add') {
                $pdo->prepare("UPDATE accounts SET post_points = post_points + ? WHERE id = ?")->execute([$pointsVal, $acc_id]);
            } else {
                $pdo->prepare("UPDATE accounts SET post_points = GREATEST(0, post_points - ?) WHERE id = ?")->execute([$pointsVal, $acc_id]);
            }
        }

        // Log
        $logDesc = "Editou Conta ID {$acc_id}. Email alterado. Pontos {$pointsOp} {$pointsVal}.";
        if(!empty($newPass)) $logDesc .= " Senha alterada.";
        
        $pdo->prepare("INSERT INTO site_admin_logs (admin_id, target_id, action_type, description, ip, date) VALUES (?, ?, 'EDIT_ACCOUNT', ?, ?, ?)")
            ->execute([$admin_id, $acc_id, $logDesc, $_SERVER['REMOTE_ADDR'], time()]);

        $pdo->commit();
        $msg = showMsg('success', 'Dados da conta atualizados com sucesso!');
    } catch (Exception $e) {
        $pdo->rollBack();
        $msg = showMsg('danger', 'Erro ao editar conta: ' . $e->getMessage());
    }
}

// 3. ALTERAR CARGO (GROUP_ID NA TABLE PLAYERS)
if (isset($_POST['change_group'])) {
    $pid = (int)$_POST['player_id'];
    $newGroup = (int)$_POST['new_group'];
    
    try {
        $pdo->prepare("UPDATE players SET group_id = ? WHERE id = ?")->execute([$newGroup, $pid]);
        
        // Log
        $pdo->prepare("INSERT INTO site_admin_logs (admin_id, target_id, action_type, description, ip, date) VALUES (?, ?, 'CHANGE_GROUP', ?, ?, ?)")
            ->execute([$admin_id, $pid, "Alterou cargo Player ID {$pid} para Group {$newGroup}", $_SERVER['REMOTE_ADDR'], time()]);
            
        $msg = showMsg('success', 'Cargo do personagem alterado!');
    } catch (Exception $e) {
        $msg = showMsg('danger', 'Erro: ' . $e->getMessage());
    }
}

// --- BUSCA ---
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$sql = "SELECT p.*, 
        a.id as acc_id, a.name as acc_name, a.email, a.post_points, a.creation, a.lastday,
        (SELECT value FROM player_storage WHERE player_id = p.id AND `key` = 91000 LIMIT 1) as catch_count
        FROM players p 
        LEFT JOIN accounts a ON p.account_id = a.id 
        WHERE p.name LIKE ? OR a.name LIKE ? 
        ORDER BY p.level DESC LIMIT 15";
$stmt = $pdo->prepare($sql);
$stmt->execute(["%$search%", "%$search%"]);
$players = $stmt->fetchAll();

// Arrays Auxiliares
$groups = [
    1 => ['name' => 'Player', 'badge' => 'secondary'],
    2 => ['name' => 'Tutor', 'badge' => 'info'],
    3 => ['name' => 'Senior Tutor', 'badge' => 'primary'],
    4 => ['name' => 'Gamemaster', 'badge' => 'danger'],
    5 => ['name' => 'Community Manager', 'badge' => 'danger'],
    6 => ['name' => 'God / Admin', 'badge' => 'warning text-dark']
];

$vocations = [
    0 => 'None', 1 => 'Treinador', 2 => 'Master', 3 => 'Elite' // Exemplo, ajuste conforme seu server
];

function showMsg($type, $text) {
    return "<div class='alert alert-{$type} shadow-sm border-0 alert-dismissible fade show'><i class='fas fa-info-circle me-2'></i>{$text}<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
}
?>

<style>
    /* Admin Dark Theme Pro */
    body { background-color: #0f172a; color: #e2e8f0; font-family: 'Poppins', sans-serif; }
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
    .table { color: #cbd5e1; vertical-align: middle; }
    .table-hover tbody tr:hover { background-color: rgba(255,255,255,0.02); }
    .table thead th { background-color: #0f172a; border-bottom: 2px solid #334155; color: #94a3b8; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; }
    .form-control, .form-select { background-color: #0f172a; border: 1px solid #334155; color: #fff; }
    .form-control:focus, .form-select:focus { background-color: #0f172a; color: #fff; border-color: #3b82f6; box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.2); }
    .text-label { font-size: 0.75rem; text-transform: uppercase; color: #64748b; font-weight: 700; display: block; margin-bottom: 4px; }
    .modal-content { background-color: #1e293b; color: #fff; border: 1px solid #334155; }
    .modal-header { border-bottom: 1px solid #334155; }
    .modal-footer { border-top: 1px solid #334155; }
    .btn-close { filter: invert(1); }
    
    .avatar-box { width: 50px; height: 50px; background: #0f172a; border-radius: 8px; display: flex; align-items: center; justify-content: center; border: 1px solid #334155; }
    .status-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 5px; }
    .dot-online { background-color: #10b981; box-shadow: 0 0 5px #10b981; }
    .dot-offline { background-color: #ef4444; }
</style>

<div class="container-fluid px-4 my-5">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-users-cog text-primary me-2"></i>Gestão de Jogadores</h2>
            <p class="text-muted m-0">Gerencie contas, personagens, cargos e saldos.</p>
        </div>
        <div>
            <form method="GET" class="d-flex gap-2">
                <input type="text" name="q" class="form-control" placeholder="Nome, Conta ou Email..." value="<?php echo htmlspecialchars($search); ?>">
                <button type="submit" class="btn btn-primary fw-bold px-4"><i class="fas fa-search"></i></button>
            </form>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="card">
        <div class="table-responsive">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th class="ps-4">Personagem</th>
                        <th>Status</th>
                        <th>Dados da Conta</th>
                        <th>Saldo & VIP</th>
                        <th>Cargo</th>
                        <th class="text-end pe-4">Controles</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($players)): ?>
                        <tr><td colspan="6" class="text-center py-5 text-muted"><i class="fas fa-search fa-2x mb-3"></i><br>Nenhum resultado encontrado.</td></tr>
                    <?php else: foreach($players as $p): 
                        $outfit = "https://outfit-images.ots.me/1285_walk_animation/animoutfit.php?id={$p['looktype']}&head={$p['lookhead']}&body={$p['lookbody']}&legs={$p['looklegs']}&feet={$p['lookfeet']}";
                        $isOnline = ($p['online'] == 1);
                        $statusClass = $isOnline ? 'dot-online' : 'dot-offline';
                        $statusText = $isOnline ? 'Online' : 'Offline';
                        
                        $grpID = $p['group_id'];
                        $grpBadge = $groups[$grpID]['badge'] ?? 'secondary';
                        $grpName = $groups[$grpID]['name'] ?? 'Player';
                    ?>
                    <tr>
                        <td class="ps-4">
                            <div class="d-flex align-items-center">
                                <div class="avatar-box me-3 position-relative">
                                    <img src="<?php echo $outfit; ?>" style="margin-top:-15px;">
                                    <span class="position-absolute bottom-0 end-0 p-1 border border-dark rounded-circle <?php echo $isOnline ? 'bg-success' : 'bg-danger'; ?>" style="width:10px; height:10px;"></span>
                                </div>
                                <div>
                                    <strong class="text-white d-block"><?php echo htmlspecialchars($p['name']); ?></strong>
                                    <small class="text-info">Lvl <?php echo $p['level']; ?> • <?php echo $vocations[$p['vocation']] ?? 'Voc '.$p['vocation']; ?></small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <small class="text-muted d-block">Último Login:</small>
                            <span class="text-white"><?php echo ($p['lastlogin'] > 0) ? date('d/m/y H:i', $p['lastlogin']) : 'Nunca'; ?></span>
                            <div class="small text-muted" style="font-size: 0.7rem;">IP: <?php echo long2ip($p['lastip']); ?></div>
                        </td>
                        <td>
                            <div class="d-flex align-items-center gap-2 mb-1">
                                <span class="badge bg-dark border border-secondary text-light"><i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($p['acc_name']); ?></span>
                            </div>
                            <div class="d-flex align-items-center text-muted small" title="Email">
                                <i class="fas fa-envelope me-2"></i> <?php echo htmlspecialchars($p['email']); ?>
                            </div>
                            <div class="small text-muted mt-1" style="font-size: 0.7rem;">Criada em: <?php echo date('d/m/Y', $p['creation']); ?></div>
                        </td>
                        <td>
                            <div class="mb-1">
                                <span class="text-warning fw-bold"><i class="fas fa-coins"></i> <?php echo number_format($p['post_points']); ?></span> <small class="text-muted">pts</small>
                            </div>
                            <?php if($p['lastday'] > time()): 
                                $daysLeft = ceil(($p['lastday'] - time()) / 86400);
                            ?>
                                <span class="badge bg-warning text-dark"><i class="fas fa-crown"></i> VIP (<?php echo $daysLeft; ?>d)</span>
                            <?php else: ?>
                                <span class="badge bg-secondary opacity-50">Free Acc</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $grpBadge; ?>"><?php echo $grpName; ?></span>
                        </td>
                        <td class="text-end pe-4">
                            <div class="btn-group">
                                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editPlayer<?php echo $p['id']; ?>" title="Editar Personagem">
                                    <i class="fas fa-user-edit"></i>
                                </button>
                                <button type="button" class="btn btn-warning btn-sm text-dark" data-bs-toggle="modal" data-bs-target="#editAcc<?php echo $p['acc_id']; ?>" title="Editar Conta & Pontos">
                                    <i class="fas fa-cog"></i>
                                </button>
                                <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#groupModal<?php echo $p['id']; ?>" title="Cargos">
                                    <i class="fas fa-shield-alt"></i>
                                </button>
                            </div>
                        </td>
                    </tr>

                    <div class="modal fade" id="editPlayer<?php echo $p['id']; ?>" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <form method="POST">
                                    <div class="modal-header bg-primary text-white">
                                        <h5 class="modal-title"><i class="fas fa-user-edit me-2"></i>Editar: <?php echo htmlspecialchars($p['name']); ?></h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="player_id" value="<?php echo $p['id']; ?>">
                                        <div class="row g-3">
                                            <div class="col-12">
                                                <span class="text-label">Nome do Personagem</span>
                                                <input type="text" name="player_name" class="form-control" value="<?php echo htmlspecialchars($p['name']); ?>" required>
                                            </div>
                                            <div class="col-6">
                                                <span class="text-label">Level</span>
                                                <input type="number" name="player_level" class="form-control" value="<?php echo $p['level']; ?>" required>
                                            </div>
                                            <div class="col-6">
                                                <span class="text-label">Sexo</span>
                                                <select name="player_sex" class="form-select">
                                                    <option value="1" <?php echo ($p['sex']==1)?'selected':''; ?>>Masculino</option>
                                                    <option value="0" <?php echo ($p['sex']==0)?'selected':''; ?>>Feminino</option>
                                                </select>
                                            </div>
                                            <div class="col-6">
                                                <span class="text-label">Vocation ID</span>
                                                <input type="number" name="player_voc" class="form-control" value="<?php echo $p['vocation']; ?>">
                                            </div>
                                            <div class="col-6">
                                                <span class="text-label">Town ID (Cidade)</span>
                                                <input type="number" name="player_town" class="form-control" value="<?php echo $p['town_id']; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" name="edit_player" class="btn btn-primary fw-bold">Salvar Alterações</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="modal fade" id="editAcc<?php echo $p['acc_id']; ?>" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <form method="POST">
                                    <div class="modal-header bg-warning text-dark">
                                        <h5 class="modal-title fw-bold"><i class="fas fa-cogs me-2"></i>Conta: <?php echo htmlspecialchars($p['acc_name']); ?></h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="account_id" value="<?php echo $p['acc_id']; ?>">
                                        
                                        <div class="mb-3">
                                            <span class="text-label">E-mail de Acesso</span>
                                            <input type="email" name="acc_email" class="form-control" value="<?php echo htmlspecialchars($p['email']); ?>" required>
                                        </div>
                                        
                                        <div class="mb-4">
                                            <span class="text-label">Nova Senha (Deixe vazio para manter)</span>
                                            <input type="password" name="acc_pass" class="form-control" placeholder="••••••">
                                        </div>

                                        <hr class="border-secondary">
                                        
                                        <div class="bg-dark p-3 rounded border border-secondary">
                                            <h6 class="text-warning fw-bold mb-3"><i class="fas fa-coins me-2"></i>Gerenciar Saldo (Atual: <?php echo $p['post_points']; ?>)</h6>
                                            <div class="input-group">
                                                <select name="points_op" class="form-select bg-dark text-white border-secondary" style="max-width: 120px;">
                                                    <option value="add">Adicionar (+)</option>
                                                    <option value="remove">Remover (-)</option>
                                                </select>
                                                <input type="number" name="points_val" class="form-control bg-dark text-white border-secondary" placeholder="0">
                                            </div>
                                            <small class="text-muted mt-1 d-block"><i class="fas fa-info-circle"></i> Log gravado automaticamente.</small>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" name="edit_account" class="btn btn-warning fw-bold text-dark">Atualizar Conta</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="modal fade" id="groupModal<?php echo $p['id']; ?>" tabindex="-1">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <form method="POST">
                                    <div class="modal-header bg-danger text-white">
                                        <h5 class="modal-title"><i class="fas fa-shield-alt me-2"></i>Cargo</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="player_id" value="<?php echo $p['id']; ?>">
                                        <span class="text-label mb-2">Selecione o novo cargo:</span>
                                        <select name="new_group" class="form-select form-select-lg mb-3">
                                            <?php foreach($groups as $gid => $ginfo): ?>
                                                <option value="<?php echo $gid; ?>" <?php echo ($p['group_id'] == $gid) ? 'selected' : ''; ?>>
                                                    <?php echo $gid . ' - ' . $ginfo['name']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="alert alert-danger bg-opacity-10 border-danger text-danger small p-2 mb-0">
                                            <i class="fas fa-exclamation-circle"></i> Cuidado ao promover jogadores.
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" name="change_group" class="btn btn-danger w-100 fw-bold">Salvar Cargo</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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