<?php
// admin/suporte.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 page_access, name FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$adminData = $stmt->fetch();

if (!$adminData || $adminData['page_access'] < 3) {
    die("<div style='background:#0b1120; color:white; height:100vh; display:flex; justify-content:center; align-items:center;'>
            <div style='text-align:center;'>
                <h1 style='color:#ef4444; font-size:3rem;'>⛔ Acesso Negado</h1>
                <a href='../index.php' style='color:#3b82f6; text-decoration:none; font-weight:bold; font-size:1.2rem;'>Voltar ao Início</a>
            </div>
         </div>"); 
}

$page_title = "Central de Suporte - Admin";
$adminId = $_SESSION['account_id'];
$msg = '';

// --- 1. LÓGICA AJAX (POLLING DE MENSAGENS) ---
if (isset($_GET['action']) && $_GET['action'] === 'get_new_messages') {
    header('Content-Type: application/json');
    $ticketId = (int)$_GET['ticket_id'];
    $lastTimestamp = (int)$_GET['last_timestamp'];

    // Busca mensagens novas do JOGADOR
    $stmt = $pdo->prepare("SELECT sm.*, a.name as sender_name 
                           FROM support_messages sm 
                           JOIN accounts a ON sm.sender_id = a.id 
                           WHERE sm.ticket_id = ? AND sm.sent_at > ? AND sm.is_admin = 0 
                           ORDER BY sm.sent_at ASC");
    $stmt->execute([$ticketId, $lastTimestamp]);
    $newMessages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Atualiza status se houver resposta nova do jogador
    $statusStmt = $pdo->prepare("SELECT status FROM support_tickets WHERE id = ?");
    $statusStmt->execute([$ticketId]);
    $currentStatus = $statusStmt->fetchColumn();

    if (!empty($newMessages) && $currentStatus === 'Resposta Admin') {
        $pdo->prepare("UPDATE support_tickets SET status = 'Em Atendimento', last_update = ? WHERE id = ?")->execute([time(), $ticketId]);
        $currentStatus = 'Em Atendimento';
    }

    echo json_encode(['success' => true, 'messages' => $newMessages, 'new_status' => $currentStatus, 'last_timestamp' => time()]);
    exit;
}

// --- 2. HEADER E FUNÇÕES ---
// Se usar layout admin separado, inclua-o. Senão, inclua o header padrão.
// Para garantir o design, vamos assumir o header padrão com CSS injetado.
if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

function displayStatusAdmin($status) {
    $map = [
        'Aberto' => ['bg' => 'bg-secondary', 'txt' => 'text-white'],
        'Em Atendimento' => ['bg' => 'bg-warning', 'txt' => 'text-dark'],
        'Resposta Admin' => ['bg' => 'bg-info', 'txt' => 'text-dark'], 
        'Fechado' => ['bg' => 'bg-success', 'txt' => 'text-white'],
    ];
    $s = $map[$status] ?? ['bg' => 'bg-dark', 'txt' => 'text-white'];
    return '<span id="ticket-status-badge" class="badge '.$s['bg'].' '.$s['txt'].' px-3 py-2 rounded-pill shadow-sm">'.htmlspecialchars($status).'</span>';
}

function long2ip_safe($long) {
    return $long ? long2ip($long) : 'N/A';
}

// --- 3. PROCESSAMENTO DE POSTS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ticketId = (int)($_POST['ticket_id'] ?? 0);

    // Limpar Antigos
    if (isset($_POST['action']) && $_POST['action'] === 'clear_closed_tickets') {
        $limitTime = time() - (3 * 86400); 
        $pdo->prepare("DELETE sm FROM support_messages sm JOIN support_tickets st ON sm.ticket_id = st.id WHERE st.status = 'Fechado' AND st.last_update < ?")->execute([$limitTime]);
        $pdo->prepare("DELETE FROM support_tickets WHERE status = 'Fechado' AND last_update < ?")->execute([$limitTime]);
        $msg = '<div class="alert alert-info fw-bold"><i class="fas fa-trash-alt me-2"></i> Limpeza de tickets antigos concluída.</div>';
    }

    // Desbugar Player
    if (isset($_POST['action']) && $_POST['action'] === 'desbug_player') {
        $pName = trim($_POST['player_name']);
        $coordType = $_POST['coord_type'];
        
        // Configurar Coordenadas do CP (Exemplo: Saffron)
        $targetX = ($coordType == 'cp') ? 1060 : (int)$_POST['custom_x'];
        $targetY = ($coordType == 'cp') ? 1052 : (int)$_POST['custom_y'];
        $targetZ = ($coordType == 'cp') ? 7 : (int)$_POST['custom_z'];
        $townId  = ($coordType == 'cp') ? 1 : 0; 

        $stmtP = $pdo->prepare("SELECT id FROM players WHERE name = ?");
        $stmtP->execute([$pName]);
        $pid = $stmtP->fetchColumn();

        if ($pid) {
            $pdo->prepare("UPDATE players SET posx=?, posy=?, posz=?, town_id=?, lastlogout=? WHERE id=?")
                ->execute([$targetX, $targetY, $targetZ, $townId, time(), $pid]);
            
            // Log de Admin
            $logDesc = "Desbugou {$pName} para {$targetX},{$targetY},{$targetZ}";
            $pdo->prepare("INSERT INTO site_admin_logs (admin_id, target_id, action_type, description, ip, date) VALUES (?, ?, 'DESBUG_PLAYER', ?, ?, ?)")
                ->execute([$adminId, $pid, $logDesc, $_SERVER['REMOTE_ADDR'], time()]);

            $msg = '<div class="alert alert-success fw-bold"><i class="fas fa-magic me-2"></i> Jogador teleportado com sucesso!</div>';
        } else {
            $msg = '<div class="alert alert-warning fw-bold">Personagem não encontrado.</div>';
        }
    }

    // Responder ou Fechar
    if ($ticketId > 0) {
        if ($_POST['action'] === 'admin_reply' && !empty($_POST['message'])) {
            $reply = trim($_POST['message']);
            $pdo->prepare("INSERT INTO support_messages (ticket_id, sender_id, message, is_admin, sent_at) VALUES (?, ?, ?, 1, ?)")
                ->execute([$ticketId, $adminId, $reply, time()]);
            $pdo->prepare("UPDATE support_tickets SET last_update = ?, status = 'Resposta Admin' WHERE id = ?")
                ->execute([time(), $ticketId]);
            $msg = '<div class="alert alert-success fw-bold">Resposta enviada!</div>';
        }
        if ($_POST['action'] === 'close_ticket') {
            $pdo->prepare("UPDATE support_tickets SET status = 'Fechado', last_update = ? WHERE id = ?")
                ->execute([time(), $ticketId]);
            header("Location: suporte.php?msg=" . urlencode("Ticket #$ticketId fechado com sucesso."));
            exit;
        }
    }
}

if (isset($_GET['msg'])) $msg = '<div class="alert alert-info fw-bold">' . htmlspecialchars($_GET['msg']) . '</div>';

// --- 4. CARREGAR DADOS ---
$viewTicket = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$lastMessageTimestamp = 0; 
$mainPlayerName = ''; 

if ($viewTicket) {
    // Detalhes do Ticket + Dados do Jogador
    $ticket = $pdo->prepare("
        SELECT t.*, a.name AS player_name, a.creation, a.post_points,
               p.lastlogin, p.lastip, p.level AS player_level, p.name AS main_char_name
        FROM support_tickets t 
        JOIN accounts a ON t.account_id = a.id
        LEFT JOIN players p ON a.id = p.account_id AND p.level = (SELECT MAX(level) FROM players WHERE account_id = a.id)
        WHERE t.id = ? LIMIT 1
    ");
    $ticket->execute([$viewTicket]);
    $currentTicket = $ticket->fetch(PDO::FETCH_ASSOC);

    if (!$currentTicket) {
        $msg = '<div class="alert alert-danger">Ticket não encontrado.</div>';
        $viewTicket = 0;
    } else {
        $mainPlayerName = $currentTicket['main_char_name'] ?? 'Desconhecido';
        
        // Mensagens
        $msgs = $pdo->prepare("SELECT sm.*, a.name as sender_name FROM support_messages sm JOIN accounts a ON sm.sender_id = a.id WHERE ticket_id = ? ORDER BY sent_at ASC");
        $msgs->execute([$viewTicket]);
        $ticketMessages = $msgs->fetchAll(PDO::FETCH_ASSOC);
        if(!empty($ticketMessages)) $lastMessageTimestamp = end($ticketMessages)['sent_at'];

        // Atualiza status se necessário
        if ($currentTicket['status'] === 'Aberto') {
            $pdo->prepare("UPDATE support_tickets SET status = 'Em Atendimento' WHERE id = ?")->execute([$viewTicket]);
            $currentTicket['status'] = 'Em Atendimento';
        }
    }
} else {
    // Lista de Tickets
    $limitTime = time() - (3 * 86400);
    $oldClosedTickets = $pdo->query("SELECT COUNT(*) FROM support_tickets WHERE status = 'Fechado' AND last_update < $limitTime")->fetchColumn();
    $ticketsList = $pdo->query("SELECT t.*, a.name as player_name FROM support_tickets t JOIN accounts a ON t.account_id = a.id ORDER BY (t.status = 'Em Atendimento') DESC, t.last_update DESC")->fetchAll(PDO::FETCH_ASSOC);
}
?>

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>

<style>
    /* DESIGN SYSTEM: Deep Blue & High Contrast */
    :root {
        --bg-dark: #0b1120;
        --bg-card: #162032;
        --primary: #3b82f6;
        --success: #10b981;
        --warning: #facc15;
        --text-bright: #ffffff;
        --text-soft: #e2e8f0; /* Branco suave (NO GREY) */
        --border-light: rgba(255, 255, 255, 0.15);
    }

    body {
        background-color: var(--bg-dark);
        color: var(--text-bright);
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* CARDS & CONTAINERS */
    .card {
        background-color: var(--bg-card);
        border: 1px solid var(--border-light);
        border-radius: 12px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.2);
    }
    .card-header {
        background-color: rgba(0,0,0,0.2);
        border-bottom: 1px solid var(--border-light);
        color: var(--text-bright);
        font-weight: 700;
    }

    /* TYPOGRAPHY - NO GREY */
    .text-white-50 { color: var(--text-soft) !important; opacity: 0.9; }
    .text-muted { color: #bae6fd !important; opacity: 0.8; } /* Azul claro para textos pequenos */
    h1, h2, h3, h4 { color: var(--text-bright); text-shadow: 0 2px 4px rgba(0,0,0,0.5); }

    /* CHAT BOX */
    .chat-box {
        height: 550px;
        overflow-y: auto;
        background: rgba(0,0,0,0.2);
        border-bottom: 1px solid var(--border-light);
        padding: 20px;
        scrollbar-width: thin;
        scrollbar-color: var(--primary) var(--bg-dark);
    }
    
    .message-bubble {
        max-width: 80%;
        margin-bottom: 15px;
        padding: 12px 18px;
        position: relative;
        font-size: 0.95rem;
        line-height: 1.5;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }
    
    .message-player {
        background-color: #334155; /* Slate escuro */
        color: white;
        border-radius: 0px 15px 15px 15px;
        border-left: 3px solid #94a3b8;
        align-self: flex-start;
        margin-right: auto;
    }
    
    .message-admin {
        background-color: var(--primary); /* Azul vibrante */
        color: white;
        border-radius: 15px 0px 15px 15px;
        border-right: 3px solid #60a5fa;
        align-self: flex-end;
        margin-left: auto;
    }

    /* FORMS & TABLES */
    .form-control, .form-select {
        background-color: rgba(255,255,255,0.05) !important;
        border: 1px solid rgba(255,255,255,0.2) !important;
        color: white !important;
        font-weight: 500;
    }
    .form-control:focus {
        background-color: rgba(255,255,255,0.1) !important;
        border-color: var(--primary) !important;
        box-shadow: 0 0 10px rgba(59, 130, 246, 0.3);
    }
    .form-control::placeholder { color: rgba(255,255,255,0.5); }

    .table { color: var(--text-soft); }
    .table thead th {
        color: #bae6fd; /* Azul claro no header */
        border-bottom: 2px solid var(--border-light);
        text-transform: uppercase;
        font-size: 0.85rem;
    }
    .table tbody td {
        border-bottom: 1px solid var(--border-light);
        vertical-align: middle;
    }
    .table-hover tbody tr:hover { background-color: rgba(255,255,255,0.05); }

    /* LIST GROUP (Player Data) */
    .list-group-item {
        background: transparent;
        border-color: var(--border-light);
        color: var(--text-bright);
        padding: 12px 15px;
    }
</style>

<div class="container my-5">

    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-light pb-3" data-aos="fade-down">
        <div>
            <h2 class="fw-bold mb-0"><i class="fas fa-headset text-danger me-2"></i>SUPORTE ADMIN</h2>
            <p class="text-white-50 m-0">Gerencie tickets e resolva problemas dos jogadores.</p>
        </div>
        <?php if ($viewTicket): ?>
            <a href="suporte.php" class="btn btn-outline-light btn-sm fw-bold px-3"><i class="fas fa-arrow-left me-2"></i> VOLTAR</a>
        <?php endif; ?>
    </div>

    <?php if ($msg) echo "<div data-aos='fade-up'>$msg</div>"; ?>

    <?php if ($viewTicket && $currentTicket): ?>
    <div class="row g-4" data-aos="fade-up">
        
        <div class="col-lg-8">
            <div class="card shadow h-100 border-top border-4 border-primary">
                <div class="card-header bg-transparent d-flex justify-content-between align-items-center py-3">
                    <div>
                        <div class="d-flex align-items-center mb-1">
                            <span class="badge bg-primary me-2">#<?php echo $currentTicket['id']; ?></span>
                            <h5 class="fw-bold text-white mb-0"><?php echo htmlspecialchars($currentTicket['subject']); ?></h5>
                        </div>
                        <div class="small text-info fw-bold">
                            <i class="fas fa-tag me-1"></i> <?php echo htmlspecialchars($currentTicket['category']); ?>
                        </div>
                    </div>
                    <div class="text-end">
                        <?php echo displayStatusAdmin($currentTicket['status']); ?>
                        <?php if ($currentTicket['status'] !== 'Fechado'): ?>
                            <form method="POST" class="d-inline ms-2" onsubmit="return confirm('Tem certeza que deseja encerrar este ticket?');">
                                <input type="hidden" name="ticket_id" value="<?php echo $currentTicket['id']; ?>">
                                <input type="hidden" name="action" value="close_ticket">
                                <button class="btn btn-sm btn-success fw-bold"><i class="fas fa-check-circle me-1"></i> RESOLVER</button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="card-body p-0">
                    <div class="d-flex flex-column chat-box" id="chat-messages">
                        <?php foreach ($ticketMessages as $msg): 
                            $isAdmin = $msg['is_admin'];
                            $bubbleClass = $isAdmin ? 'message-admin' : 'message-player';
                            $senderName = $isAdmin ? 'ADMINISTRADOR (Você)' : htmlspecialchars($msg['sender_name']);
                            $senderColor = $isAdmin ? '#e0f2fe' : '#93c5fd'; // Azul muito claro
                        ?>
                        <div class="message-bubble <?php echo $bubbleClass; ?>">
                            <div class="fw-bold mb-1" style="color: <?php echo $senderColor; ?>; font-size: 0.8rem; text-transform: uppercase;">
                                <?php echo $senderName; ?>
                            </div>
                            <div class="text-white" style="white-space: pre-wrap;"><?php echo nl2br(htmlspecialchars($msg['message'])); ?></div>
                            <div class="text-end mt-1" style="font-size: 0.7rem; color: rgba(255,255,255,0.7);">
                                <?php echo date('d/m • H:i', $msg['sent_at']); ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <?php if ($currentTicket['status'] !== 'Fechado'): ?>
                <div class="card-footer bg-transparent p-3">
                    <form method="POST" id="replyForm">
                        <input type="hidden" name="ticket_id" value="<?php echo $currentTicket['id']; ?>">
                        <input type="hidden" name="action" value="admin_reply">
                        <label class="form-label text-white fw-bold small">NOVA RESPOSTA</label>
                        <div class="input-group">
                            <textarea name="message" id="reply-message" class="form-control" rows="3" placeholder="Escreva sua resposta para o jogador..." required></textarea>
                            <button type="submit" class="btn btn-primary fw-bold px-4"><i class="fas fa-paper-plane me-2"></i> ENVIAR</button>
                        </div>
                    </form>
                </div>
                <?php else: ?>
                <div class="card-footer bg-success text-white text-center fw-bold py-3">
                    <i class="fas fa-lock me-2"></i> TICKET FINALIZADO
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-4">
            
            <div class="card shadow mb-4">
                <div class="card-header bg-dark text-white border-bottom border-light">
                    <i class="fas fa-user-circle me-2 text-warning"></i> DADOS DO JOGADOR
                </div>
                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between">
                        <span class="text-white-50">Conta:</span>
                        <span class="fw-bold text-info"><?php echo htmlspecialchars($currentTicket['player_name']); ?></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between">
                        <span class="text-white-50">Main Char:</span>
                        <span class="fw-bold text-white"><?php echo htmlspecialchars($mainPlayerName); ?> <small class="text-warning ms-1">(Lvl <?php echo $currentTicket['player_level']; ?>)</small></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between">
                        <span class="text-white-50">Pontos:</span>
                        <span class="fw-bold text-success"><?php echo number_format($currentTicket['post_points'], 0, ',', '.'); ?> Pts</span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between">
                        <span class="text-white-50">Último Login:</span>
                        <span class="text-white"><?php echo $currentTicket['lastlogin'] ? date('d/m/Y H:i', $currentTicket['lastlogin']) : '-'; ?></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between">
                        <span class="text-white-50">IP Recente:</span>
                        <span class="text-white font-monospace"><?php echo long2ip_safe($currentTicket['lastip']); ?></span>
                    </li>
                </ul>
            </div>

            <div class="card shadow border-info">
                <div class="card-header bg-info text-dark fw-bold">
                    <i class="fas fa-bolt me-2"></i> DESBUGAR / TELEPORTAR
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="desbug_player">
                        
                        <div class="mb-3">
                            <label class="form-label text-white small fw-bold">PERSONAGEM ALVO</label>
                            <input type="text" name="player_name" class="form-control" value="<?php echo htmlspecialchars($mainPlayerName); ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label text-white small fw-bold">DESTINO</label>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="coord_type" id="radioCP" value="cp" checked onchange="toggleCustom()">
                                <label class="form-check-label text-white" for="radioCP">Centro Pokémon (Saffron)</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="coord_type" id="radioCustom" value="custom" onchange="toggleCustom()">
                                <label class="form-check-label text-white" for="radioCustom">Coordenadas Específicas</label>
                            </div>
                        </div>

                        <div id="custom-coords" class="row g-2 mb-3" style="display:none;">
                            <div class="col-4"><input type="number" name="custom_x" class="form-control form-control-sm text-center" placeholder="X"></div>
                            <div class="col-4"><input type="number" name="custom_y" class="form-control form-control-sm text-center" placeholder="Y"></div>
                            <div class="col-4"><input type="number" name="custom_z" class="form-control form-control-sm text-center" value="7" placeholder="Z"></div>
                        </div>

                        <button type="submit" class="btn btn-outline-info text-white w-100 fw-bold border-2" onclick="return confirm('Confirmar teleporte?');">
                            EXECUTAR TELEPORTE
                        </button>
                    </form>
                </div>
            </div>

        </div>
    </div>

    <?php else: ?>
    
    <div class="card shadow border-0" data-aos="fade-up">
        <div class="card-header bg-dark d-flex justify-content-between align-items-center py-3">
            <span class="text-white fw-bold fs-5"><i class="fas fa-list me-2 text-primary"></i> TICKETS RECENTES</span>
            
            <?php if ($oldClosedTickets > 0): ?>
            <form method="POST" onsubmit="return confirm('ATENÇÃO: Isso apagará permanentemente tickets fechados há mais de 3 dias. Continuar?');">
                <input type="hidden" name="action" value="clear_closed_tickets">
                <button class="btn btn-sm btn-outline-danger fw-bold"><i class="fas fa-trash me-2"></i> LIMPAR ANTIGOS (<?php echo $oldClosedTickets; ?>)</button>
            </form>
            <?php endif; ?>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-dark bg-opacity-50">
                    <tr>
                        <th class="ps-4">ID</th>
                        <th>ASSUNTO</th>
                        <th>JOGADOR</th>
                        <th>CATEGORIA</th>
                        <th>STATUS</th>
                        <th>ÚLTIMA ATUALIZAÇÃO</th>
                        <th class="text-end pe-4">AÇÃO</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($ticketsList)): ?>
                        <tr><td colspan="7" class="text-center py-5 text-white-50 fs-5">Nenhum ticket encontrado.</td></tr>
                    <?php else: foreach ($ticketsList as $t): 
                        // Destaque para tickets precisando de atenção
                        $rowClass = ($t['status'] === 'Em Atendimento' || $t['status'] === 'Aberto') ? 'bg-primary bg-opacity-10' : '';
                        $dateColor = ($t['status'] === 'Em Atendimento') ? 'text-warning' : 'text-white-50';
                    ?>
                    <tr class="<?php echo $rowClass; ?>">
                        <td class="ps-4 fw-bold text-white">#<?php echo $t['id']; ?></td>
                        <td class="text-white fw-bold"><?php echo htmlspecialchars($t['subject']); ?></td>
                        <td class="text-info"><?php echo htmlspecialchars($t['player_name']); ?></td>
                        <td><span class="badge bg-dark border border-secondary text-white-50"><?php echo $t['category']; ?></span></td>
                        <td><?php echo displayStatusAdmin($t['status']); ?></td>
                        <td class="<?php echo $dateColor; ?> small fw-bold"><?php echo date('d/m/Y H:i', $t['last_update']); ?></td>
                        <td class="text-end pe-4">
                            <a href="?view=<?php echo $t['id']; ?>" class="btn btn-sm btn-primary fw-bold px-3">
                                <i class="fas fa-eye me-1"></i> VER
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

</div>

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

<script>
    AOS.init();

    // Toggle Custom Coordinates
    function toggleCustom() {
        const isCustom = document.getElementById('radioCustom').checked;
        document.getElementById('custom-coords').style.display = isCustom ? 'flex' : 'none';
    }

    // Polling System (Atualização em Tempo Real)
    const ticketId = <?php echo $viewTicket; ?>;
    let lastTime = <?php echo $lastMessageTimestamp; ?>;
    const chatBox = document.getElementById('chat-messages');

    function scrollToBottom() {
        if(chatBox) chatBox.scrollTop = chatBox.scrollHeight;
    }

    function pollMessages() {
        if(!ticketId) return;
        
        fetch(`suporte.php?action=get_new_messages&ticket_id=${ticketId}&last_timestamp=${lastTime}`)
        .then(r => r.json())
        .then(data => {
            if(data.success && data.messages.length > 0) {
                // Verifica se usuário estava no fundo para rolar automaticamente
                let shouldScroll = (chatBox.scrollTop + chatBox.clientHeight >= chatBox.scrollHeight - 50);
                
                data.messages.forEach(msg => {
                    if(msg.sent_at > lastTime) lastTime = msg.sent_at;
                    
                    const div = document.createElement('div');
                    div.className = 'message-bubble message-player'; // Mensagens novas via ajax são sempre do player
                    div.innerHTML = `
                        <div class="fw-bold mb-1" style="color: #93c5fd; font-size: 0.8rem; text-transform: uppercase;">
                            ${msg.sender_name}
                        </div>
                        <div class="text-white" style="white-space: pre-wrap;">${msg.message}</div>
                        <div class="text-end mt-1" style="font-size: 0.7rem; color: rgba(255,255,255,0.7);">
                            Agora
                        </div>`;
                    chatBox.appendChild(div);
                });

                if(shouldScroll) scrollToBottom();
                
                // Atualiza status visualmente se mudou
                if(data.new_status === 'Em Atendimento') {
                    const badge = document.getElementById('ticket-status-badge');
                    if(badge) {
                        badge.className = 'badge bg-warning text-dark px-3 py-2 rounded-pill shadow-sm';
                        badge.innerText = 'Em Atendimento';
                    }
                }
            }
        });
        setTimeout(pollMessages, 5000); // Verifica a cada 5 segundos
    }

    window.onload = function() {
        scrollToBottom();
        if(ticketId) setTimeout(pollMessages, 5000);
    };
</script>