<?php
ob_start();
session_start();
require 'includes/conexao.php';

// --- CONFIGURAÇÃO DE SEO ---
$serverName = "Pokemon Relics";
$page_title = "Suporte ao Jogador - $serverName";
$metaDesc   = "Precisa de ajuda? Abra um ticket para nossa equipe de suporte. Estamos prontos para resolver seus problemas em $serverName.";

// --- 1. SEGURANÇA E REGRAS ---
if (!isset($_SESSION['account_id'])) {
    header("Location: login.php?redirect=suporte.php");
    exit;
}

$accountId = $_SESSION['account_id'];
$user_name = isset($_SESSION['name']) ? $_SESSION['name'] : 'Jogador'; // Nome da conta para o chat
$errorMessage = '';
$successMessage = '';

// Verifica se o player tem char level 20+
$checkLevel = $pdo->prepare("SELECT COUNT(*) FROM players WHERE account_id = ? AND level >= 20");
$checkLevel->execute([$accountId]);
$canOpenTicket = $checkLevel->fetchColumn() > 0;

// Verifica se há ticket ATIVO
$activeTicketCount = $pdo->prepare("SELECT COUNT(*) FROM support_tickets WHERE account_id = ? AND status != 'Fechado'");
$activeTicketCount->execute([$accountId]);
$hasActiveTicket = $activeTicketCount->fetchColumn() > 0;

if (!$canOpenTicket) {
    $errorMessage = 'Requisito: Ter pelo menos um personagem Nível 20+.';
} elseif ($hasActiveTicket && !isset($_GET['view'])) {
    $errorMessage = 'Você já possui um ticket em aberto. Aguarde a finalização dele.';
}

// --- 2. LÓGICA AJAX (JSON) ---
if ((isset($_GET['action']) && $_GET['action'] === 'get_new_messages') || (isset($_POST['action']) && ($_POST['action'] === 'new_message' || $_POST['action'] === 'close_ticket_player'))) {
    header('Content-Type: application/json');
    
    // A) Fechar Ticket
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['action'] === 'close_ticket_player') {
        $ticketId = (int)$_POST['ticket_id'];
        try {
            $pdo->prepare("UPDATE support_tickets SET status = 'Fechado', last_update = ? WHERE id = ? AND account_id = ? AND status != 'Fechado'")
                ->execute([time(), $ticketId, $accountId]);
            echo json_encode(['success' => true]);
            exit;
        } catch (Exception $e) { echo json_encode(['success' => false]); exit; }
    }

    // B) Enviar Mensagem
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['action'] === 'new_message') {
        $ticketId = (int)$_POST['ticket_id'];
        $message = trim($_POST['message']);
        if (empty($message)) { echo json_encode(['success' => false, 'message' => 'Vazio.']); exit; }

        try {
            $pdo->prepare("INSERT INTO support_messages (ticket_id, sender_id, message, is_admin, sent_at) VALUES (?, ?, ?, 0, ?)")
                ->execute([$ticketId, $accountId, $message, time()]);
            $pdo->prepare("UPDATE support_tickets SET last_update = ?, status = 'Em Atendimento' WHERE id = ? AND account_id = ?")
                ->execute([time(), $ticketId, $accountId]);
            
            echo json_encode(['success' => true, 'new_message' => [
                'id' => $pdo->lastInsertId(), 'ticket_id' => $ticketId, 'sender_id' => $accountId, 
                'message' => $message, 'is_admin' => '0', 'sent_at' => time()
            ]]);
            exit;
        } catch (Exception $e) { echo json_encode(['success' => false]); exit; }
    }
    
    // C) Polling (Receber)
    if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'get_new_messages') {
        $ticketId = (int)$_GET['ticket_id'];
        $lastTimestamp = (int)$_GET['last_timestamp'];

        $stmt = $pdo->prepare("SELECT * FROM support_messages WHERE ticket_id = ? AND sent_at > ? ORDER BY sent_at ASC");
        $stmt->execute([$ticketId, $lastTimestamp]);
        $newMessages = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $statusStmt = $pdo->prepare("SELECT status FROM support_tickets WHERE id = ?");
        $statusStmt->execute([$ticketId]);
        $currentStatus = $statusStmt->fetchColumn();

        // Atualiza status local se admin respondeu
        foreach($newMessages as $m) {
            if($m['is_admin'] == 1 && $currentStatus === 'Resposta Admin') {
                $pdo->prepare("UPDATE support_tickets SET status = 'Em Atendimento' WHERE id = ?")->execute([$ticketId]);
                $currentStatus = 'Em Atendimento';
                break;
            }
        }
        echo json_encode(['success' => true, 'messages' => $newMessages, 'new_status' => $currentStatus, 'last_timestamp' => time()]);
        exit;
    }
}

// --- 3. CRIAR NOVO TICKET (POST NORMAL) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'new_ticket') {
    if ($canOpenTicket && !$hasActiveTicket) {
        $subject = trim($_POST['subject']);
        $category = $_POST['category'];
        $firstMessage = trim($_POST['first_message']);
        
        if (!empty($subject) && !empty($firstMessage)) {
            try {
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("INSERT INTO support_tickets (account_id, subject, category, last_update, created_at) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$accountId, $subject, $category, time(), time()]);
                $newId = $pdo->lastInsertId();
                $pdo->prepare("INSERT INTO support_messages (ticket_id, sender_id, message, is_admin, sent_at) VALUES (?, ?, ?, 0, ?)")
                    ->execute([$newId, $accountId, $firstMessage, time()]);
                $pdo->commit();
                header("Location: suporte.php?view=" . $newId);
                exit; 
            } catch (Exception $e) { $pdo->rollBack(); $errorMessage = "Erro ao criar ticket."; }
        } else { $errorMessage = "Preencha todos os campos."; }
    }
}

// --- 4. PREPARAÇÃO DO LAYOUT ---
include 'includes/header.php'; // Seu header deve conter Bootstrap + FontAwesome

$viewTicket = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$lastMessageTimestamp = 0;

if ($viewTicket) {
    $ticket = $pdo->prepare("SELECT * FROM support_tickets WHERE id = ? AND account_id = ?");
    $ticket->execute([$viewTicket, $accountId]);
    $currentTicket = $ticket->fetch(PDO::FETCH_ASSOC);

    if (!$currentTicket) {
        $errorMessage = "Ticket não encontrado."; $viewTicket = 0;
    } else {
        $msgs = $pdo->prepare("SELECT * FROM support_messages 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'];
        
        if ($currentTicket['status'] === 'Resposta Admin') {
            $pdo->prepare("UPDATE support_tickets SET status = 'Em Atendimento' WHERE id = ?")->execute([$viewTicket]);
            $currentTicket['status'] = 'Em Atendimento';
        }
    }
}

if (!$viewTicket) {
    $ticketsList = $pdo->prepare("SELECT * FROM support_tickets WHERE account_id = ? ORDER BY last_update DESC");
    $ticketsList->execute([$accountId]);
    $tickets = $ticketsList->fetchAll(PDO::FETCH_ASSOC);
}

// Helpers Visuais
function displayStatus($status) {
    $map = [
        'Aberto' => ['bg'=>'bg-secondary', 'txt'=>'text-white'],
        'Em Atendimento' => ['bg'=>'bg-warning', 'txt'=>'text-dark'],
        'Resposta Admin' => ['bg'=>'bg-danger', 'txt'=>'text-white'],
        '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>';
}
?>

<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>

<meta name="description" content="<?php echo $metaDesc; ?>">
<meta property="og:title" content="<?php echo $page_title; ?>">

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

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

    /* HERO */
    .support-hero {
        background: linear-gradient(180deg, rgba(11,17,32,0.9) 0%, #0b1120 100%), url('images/hero-support.jpg') center/cover;
        padding: 60px 0 40px 0;
        text-align: center;
        border-bottom: 1px solid var(--border-light);
        margin-top: -20px;
    }
    .hero-title {
        font-family: 'Rajdhani', sans-serif;
        font-size: 3rem;
        font-weight: 800;
        text-transform: uppercase;
        color: white;
        text-shadow: 0 0 20px rgba(59, 130, 246, 0.6);
    }

    /* CARDS */
    .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);
    }

    /* INPUTS (Claros) */
    .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 {
        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); }

    /* CHAT */
    .chat-box {
        height: 500px;
        overflow-y: auto;
        background: rgba(0,0,0,0.2);
        border-bottom: 1px solid var(--border-light);
        padding: 20px;
    }
    .message-bubble { margin-bottom: 15px; position: relative; }
    .message-player .card {
        background-color: #334155; 
        color: white; 
        border-radius: 15px 15px 0 15px;
        border: 1px solid var(--border-light);
    }
    .message-admin .card {
        background-color: var(--primary); 
        color: white; 
        border-radius: 15px 15px 15px 0;
        box-shadow: 0 0 15px rgba(59,130,246,0.3);
    }

    /* LISTA TICKETS */
    .list-group-item {
        background: transparent;
        border-color: var(--border-light);
        color: var(--text-bright);
        transition: 0.2s;
    }
    .list-group-item:hover { background: rgba(255,255,255,0.05); }
    
    /* UTILS */
    .text-white-50 { color: var(--text-soft) !important; opacity: 0.9; }
    .text-muted { color: #bae6fd !important; opacity: 0.8; } /* Azul claro em vez de cinza */
</style>

<div class="support-hero">
    <div class="container" data-aos="fade-down">
        <h1 class="hero-title"><i class="fas fa-headset me-2"></i> SUPORTE AO JOGADOR</h1>
        <p class="text-white-50 fs-5">Precisa de ajuda? Nossa equipe está pronta para te atender.</p>
    </div>
</div>

<div class="container my-5">

    <?php if ($errorMessage): ?>
        <div class="alert alert-danger bg-danger text-white border-0 fw-bold shadow mb-4" data-aos="fade-up">
            <i class="fas fa-exclamation-triangle me-2"></i> <?php echo $errorMessage; ?>
        </div>
    <?php endif; ?>

    <?php if ($viewTicket && $currentTicket): ?>
        
        <div class="card shadow h-100 border-top border-4 border-primary" data-aos="fade-up">
            
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center py-3 flex-wrap">
                <div>
                    <a href="suporte.php" class="btn btn-outline-light btn-sm me-2 mb-2"><i class="fas fa-arrow-left"></i> Voltar</a>
                    <span class="badge bg-primary fs-6 me-2">#<?php echo $currentTicket['id']; ?></span>
                    <h5 class="d-inline-block fw-bold text-white mb-0 align-middle"><?php echo htmlspecialchars($currentTicket['subject']); ?></h5>
                </div>
                <div class="mt-2 mt-md-0 text-end">
                    <?php echo displayStatus($currentTicket['status']); ?>
                    <?php if ($currentTicket['status'] !== 'Fechado'): ?>
                        <button class="btn btn-sm btn-danger ms-2 fw-bold" onclick="closeTicket(<?php echo $currentTicket['id']; ?>)">
                            <i class="fas fa-lock me-1"></i> FECHAR
                        </button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="chat-box" id="chat-messages">
                    <?php foreach ($ticketMessages as $msg): 
                        $isAdmin = $msg['is_admin'];
                        $align = $isAdmin ? 'justify-content-start' : 'justify-content-end';
                        $bubbleType = $isAdmin ? 'message-admin' : 'message-player';
                        $sender = $isAdmin ? 'ADMINISTRADOR' : 'VOCÊ';
                        $colorSender = $isAdmin ? 'text-warning' : 'text-info';
                    ?>
                    <div class="d-flex <?php echo $align; ?> message-bubble <?php echo $bubbleType; ?>" data-timestamp="<?php echo $msg['sent_at']; ?>">
                        <div class="card shadow-sm" style="max-width: 80%;">
                            <div class="card-body p-3">
                                <small class="fw-bold d-block mb-1 <?php echo $colorSender; ?>" style="font-size:0.75rem; letter-spacing:1px;">
                                    <?php echo $sender; ?>
                                </small>
                                <div style="white-space: pre-wrap; word-wrap: break-word;">
                                    <?php echo nl2br(htmlspecialchars($msg['message'])); ?>
                                </div>
                                <small class="d-block text-end mt-1 text-white-50" style="font-size: 0.7rem;">
                                    <?php echo date('d/m • H:i', $msg['sent_at']); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php if ($currentTicket['status'] !== 'Fechado'): ?>
            <div class="card-footer bg-transparent p-3">
                <form id="reply-form">
                    <input type="hidden" name="action" value="new_message">
                    <input type="hidden" name="ticket_id" value="<?php echo $currentTicket['id']; ?>">
                    <div class="input-group">
                        <textarea name="message" id="reply-message" class="form-control" rows="2" placeholder="Digite sua mensagem..." required></textarea>
                        <button type="submit" class="btn btn-primary fw-bold px-4" id="send-btn">
                            <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-check-circle me-2"></i> TICKET RESOLVIDO / FECHADO
            </div>
            <?php endif; ?>

        </div>

    <?php else: ?>

        <div class="row g-4" data-aos="fade-up">
            
            <div class="col-lg-4 order-lg-2">
                <div class="card shadow h-100 <?php echo $canOpenTicket && !$hasActiveTicket ? 'border-primary' : 'border-danger opacity-75'; ?>">
                    <div class="card-header fw-bold bg-transparent text-uppercase py-3">
                        <i class="fas fa-edit me-2 text-warning"></i> Novo Ticket
                    </div>
                    <div class="card-body">
                        <?php if ($canOpenTicket && !$hasActiveTicket): ?>
                            <form method="POST">
                                <input type="hidden" name="action" value="new_ticket">
                                <div class="mb-3">
                                    <label class="small text-white-50 mb-1">ASSUNTO</label>
                                    <input type="text" name="subject" class="form-control" placeholder="Resumo do problema..." required>
                                </div>
                                <div class="mb-3">
                                    <label class="small text-white-50 mb-1">CATEGORIA</label>
                                    <select name="category" class="form-select" required>
                                        <option value="Bug">Reportar Bug</option>
                                        <option value="Dúvida">Dúvida Geral</option>
                                        <option value="Denúncia">Denúncia</option>
                                        <option value="Outro">Outros</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="small text-white-50 mb-1">MENSAGEM DETALHADA</label>
                                    <textarea name="first_message" class="form-control" rows="5" required></textarea>
                                </div>
                                <button type="submit" class="btn btn-primary w-100 fw-bold py-2">
                                    <i class="fas fa-paper-plane me-2"></i> ABRIR TICKET
                                </button>
                            </form>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="fas fa-lock fa-3x text-danger mb-3"></i>
                                <h5 class="fw-bold">Abertura Bloqueada</h5>
                                <p class="text-white-50 small mb-0"><?php echo $errorMessage ?: "Você já possui um ticket em andamento."; ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="col-lg-8 order-lg-1">
                <div class="card shadow h-100">
                    <div class="card-header fw-bold bg-transparent text-uppercase py-3">
                        <i class="fas fa-history me-2 text-info"></i> Meus Tickets
                    </div>
                    <div class="list-group list-group-flush">
                        <?php if (!empty($tickets)): foreach ($tickets as $t): ?>
                            <a href="?view=<?php echo $t['id']; ?>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center py-3">
                                <div>
                                    <h6 class="mb-1 fw-bold text-white">
                                        #<?php echo $t['id']; ?> - <?php echo htmlspecialchars($t['subject']); ?>
                                    </h6>
                                    <small class="text-muted"><i class="fas fa-tag me-1"></i> <?php echo htmlspecialchars($t['category']); ?></small>
                                </div>
                                <div class="text-end">
                                    <?php echo displayStatus($t['status']); ?>
                                    <small class="d-block text-white-50 mt-1" style="font-size: 0.7rem;">
                                        <?php echo date('d/m H:i', $t['last_update']); ?>
                                    </small>
                                </div>
                            </a>
                        <?php endforeach; else: ?>
                            <div class="text-center py-5 text-white-50">
                                <i class="fas fa-folder-open fa-3x mb-3 opacity-50"></i>
                                <p>Nenhum ticket encontrado.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>

    <?php endif; ?>

</div>

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

<script>
    AOS.init();

    // Scripts de Chat (Polling e Envio)
    const ticketId = <?php echo $viewTicket; ?>;
    let lastTime = <?php echo $lastMessageTimestamp; ?>;
    const chatBox = document.getElementById('chat-messages');

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

    // POLL
    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) {
                let scroll = (chatBox.scrollTop + chatBox.clientHeight >= chatBox.scrollHeight - 50);
                
                data.messages.forEach(msg => {
                    if(msg.sent_at > lastTime) lastTime = msg.sent_at;
                    
                    const isAdmin = msg.is_admin == 1;
                    const align = isAdmin ? 'justify-content-start' : 'justify-content-end';
                    const bubble = isAdmin ? 'message-admin' : 'message-player';
                    const name = isAdmin ? 'ADMINISTRADOR' : 'VOCÊ';
                    const color = isAdmin ? 'text-warning' : 'text-info';
                    const card = isAdmin ? 'bg-primary text-white' : 'bg-light'; // Ajuste aqui se quiser trocar cor do balão

                    // Template Literal HTML
                    const html = `
                    <div class="d-flex ${align} message-bubble ${bubble}">
                        <div class="card shadow-sm ${isAdmin ? 'bg-primary text-white' : 'bg-secondary text-white'}" style="max-width: 80%;">
                            <div class="card-body p-3">
                                <small class="d-block mb-1 fw-bold ${color}" style="font-size:0.75rem;">${name}</small>
                                <div style="white-space: pre-wrap;">${msg.message}</div>
                                <small class="d-block text-end mt-1 text-white-50" style="font-size: 0.7rem;">Agora</small>
                            </div>
                        </div>
                    </div>`;
                    
                    chatBox.insertAdjacentHTML('beforeend', html);
                });

                if(data.new_status && document.getElementById('ticket-status-badge')) {
                    // Atualizar visualmente o status (reload simples para garantir consistência ou manipulação DOM)
                    // Para simplificar, vou deixar o reload automático se mudar status de fechado
                    if(data.new_status === 'Fechado') location.reload();
                }

                if(scroll) scrollToBottom();
            }
        });
        setTimeout(pollMessages, 5000);
    }

    // ENVIO
    const form = document.getElementById('reply-form');
    if(form) {
        form.onsubmit = function(e) {
            e.preventDefault();
            const btn = document.getElementById('send-btn');
            const txt = document.getElementById('reply-message');
            if(!txt.value.trim()) return;

            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

            const fd = new FormData(form);
            fetch('suporte.php', { method:'POST', body:fd })
            .then(r => r.json())
            .then(d => {
                if(d.success) {
                    txt.value = '';
                    // O poll vai pegar a mensagem, ou podemos forçar aqui. 
                    // Vamos forçar render imediato para UX rápida
                    const msg = d.new_message;
                    lastTime = msg.sent_at;
                    const html = `
                    <div class="d-flex justify-content-end message-bubble message-player">
                        <div class="card shadow-sm bg-secondary text-white" style="max-width: 80%;">
                            <div class="card-body p-3">
                                <small class="d-block mb-1 fw-bold text-info" style="font-size:0.75rem;">VOCÊ</small>
                                <div style="white-space: pre-wrap;">${msg.message}</div>
                                <small class="d-block text-end mt-1 text-white-50" style="font-size: 0.7rem;">Agora</small>
                            </div>
                        </div>
                    </div>`;
                    chatBox.insertAdjacentHTML('beforeend', html);
                    scrollToBottom();
                } else {
                    alert('Erro ao enviar.');
                }
            })
            .finally(() => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i> ENVIAR';
            });
        };
    }

    // FECHAR TICKET
    window.closeTicket = function(id) {
        if(!confirm('Deseja realmente fechar este ticket?')) return;
        const fd = new FormData();
        fd.append('action', 'close_ticket_player');
        fd.append('ticket_id', id);
        fetch('suporte.php', { method:'POST', body:fd })
        .then(r=>r.json())
        .then(d => { if(d.success) location.reload(); });
    };

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