<?php
// === ATIVAR MODO DE CORREÇÃO (DEBUG) ===
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'includes/db.php';

// Verificação de segurança
if (!isset($_SESSION['logged_in_fxtream']) || $_SESSION['logged_in_fxtream'] !== true) {
    header('Location: index.php');
    exit;
}

// ====================================================================
// === PROCESSADOR DE LIMPEZA AUTOMÁTICA (AJAX) ===
// ====================================================================
// Essa parte roda silenciosamente quando o Javascript pede
if (isset($_GET['auto_clean'])) {
    header('Content-Type: application/json');
    try {
        $tipo = $_GET['auto_clean'];
        
        if ($tipo == 'channels') {
            // Limpa apenas CANAIS (live)
            $stmt = $pdo->prepare("DELETE FROM active_connections WHERE stream_type = 'live'");
            $stmt->execute();
            echo json_encode(['status' => 'success', 'msg' => 'Canais limpos']);
        } 
        elseif ($tipo == 'vod') {
            // Limpa FILMES e SÉRIES (movie, series)
            $stmt = $pdo->prepare("DELETE FROM active_connections WHERE stream_type IN ('movie', 'series')");
            $stmt->execute();
            echo json_encode(['status' => 'success', 'msg' => 'Filmes/Series limpos']);
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]);
    }
    exit; // Para a execução aqui para não carregar a página inteira
}

// === AÇÃO: DERRUBAR UM CLIENTE (KICK MANUAL) ===
if (isset($_GET['kill']) && is_numeric($_GET['kill'])) {
    try {
        $kill_id = $_GET['kill'];
        $stmt = $pdo->prepare("DELETE FROM active_connections WHERE id = ?");
        $stmt->execute([$kill_id]);
        header("Location: monitor.php?msg=killed");
        exit;
    } catch (Exception $e) {
        die("Erro ao derrubar cliente: " . $e->getMessage());
    }
}

// === BUSCA E PAGINAÇÃO ===
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

try {
    $where = "WHERE 1=1";
    $params = [];

    $sql_base = "FROM active_connections ac 
                 LEFT JOIN users u ON ac.user_id = u.id 
                 LEFT JOIN channels c ON ac.stream_id = c.id 
                 LEFT JOIN movies m ON ac.stream_id = m.id
                 LEFT JOIN series s ON ac.stream_id = s.id"; 

    if (!empty($search)) {
        $where .= " AND (u.username LIKE ? OR ac.username LIKE ?)"; 
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    $stmt_count = $pdo->prepare("SELECT COUNT(*) $sql_base $where");
    $stmt_count->execute($params);
    $total_records = $stmt_count->fetchColumn();
    $total_pages = $total_records > 0 ? ceil($total_records / $limit) : 1;

    $sql = "SELECT ac.*, 
            COALESCE(u.username, ac.username, 'Desconhecido') as final_username,
            COALESCE(NULLIF(ac.content_name, ''), c.name, m.name, s.name, 'Conteúdo Desconhecido') as display_name,
            COALESCE(NULLIF(ac.content_image, ''), c.logo_url, m.cover_url, s.cover_url) as display_logo,
            ac.stream_id as debug_id
            $sql_base 
            $where 
            ORDER BY ac.id DESC 
            LIMIT $limit OFFSET $offset";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $connections = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    echo "<div style='background:red;color:white;padding:20px;'><b>Erro SQL:</b> " . $e->getMessage() . "</div>";
    die();
}

function time_elapsed($start_time) {
    if (empty($start_time)) return "00:00:00";
    try {
        if(is_numeric($start_time)) {
            $start = new DateTime("@$start_time");
        } else {
            $start = new DateTime($start_time);
        }
        $now = new DateTime();
        if ($start > $now) return "Conectando...";
        $diff = $now->diff($start);
        if ($diff->d > 0) return $diff->format('%d d, %H:%I:%S');
        return $diff->format('%H:%I:%S');
    } catch (Exception $e) {
        return "--:--:--";
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
    <title>Conexões Ativas</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/mdb.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">
    
    <style>
        body { background-color: #1a1c23; color: #fff; overflow-x: hidden; }
        .card-monitor { background-color: #232730; border: none; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.2); width: 100%; }
        .page-title { font-size: 1.5rem; color: #fff; text-transform: uppercase; font-weight: 500; margin-bottom: 20px; margin-top: 10px; }
        .table-dark-custom { background-color: #232730; color: #ccc; width: 100%; }
        .table-dark-custom thead th { border-top: none; border-bottom: 1px solid #3a3f4b; text-transform: uppercase; font-size: 0.85rem; color: #fff; font-weight: 600; white-space: nowrap; }
        .table-dark-custom td { border-top: 1px solid #3a3f4b; vertical-align: middle; font-size: 0.9rem; white-space: nowrap; }
        .status-badge { display: inline-block; width: 10px; height: 10px; background-color: #00c851; border-radius: 50%; margin-right: 5px; box-shadow: 0 0 5px #00c851; }
        .search-input { background-color: #1a1c23; border: 1px solid #3a3f4b; color: #fff; }
        .search-input:focus { background-color: #1a1c23; color: #fff; border-color: #007bff; }
        .btn-search { background-color: #007bff; color: white; }
        .content-cell { display: flex; align-items: center; }
        .channel-logo { width: 35px; height: 35px; object-fit: contain; border-radius: 5px; background: rgba(255,255,255,0.05); margin-right: 10px; border: 1px solid #3a3f4b; }
        
        .refresh-control { display: flex; align-items: center; background: #2c303a; padding: 5px 15px; border-radius: 20px; border: 1px solid #3a3f4b; }
        .custom-control-label::before { background-color: #444; }
        .custom-control-input:checked ~ .custom-control-label::before { background-color: #00c851; border-color: #00c851; }
        
        /* Indicador de Limpeza Automática */
        #autoCleanStatus { font-size: 0.8rem; margin-left: 15px; color: #ffc107; display: none; }

        @media (min-width: 992px) {
            #sidebar { display: block !important; width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .right-column { margin-left: 240px; width: calc(100% - 240px); padding: 20px; }
            .btn-voltar-mobile { display: none; }
        }
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .navbar { display: none !important; }
            .right-column { margin-left: 0 !important; width: 100% !important; padding: 10px; }
            .btn-voltar-mobile { display: inline-block; margin-bottom: 15px; background: #333; color: #fff; padding: 8px 15px; border-radius: 5px; text-decoration: none; border: 1px solid #444; }
            .table-responsive { overflow-x: auto; }
        }
    </style>
</head>

<body>
    <div class="container-fluid p-0"> 
        <div class="row no-gutters"> 
            <?php include 'includes/sidebar.php'; ?>
            <div class="right-column">
                <nav class="navbar navbar-expand-lg navbar-dark bg-dark border-bottom border-secondary" style="background-color: #1a1c23 !important;">
                    <span class="navbar-brand">Monitoramento</span>
                </nav>

                <main class="main-content">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fas fa-arrow-left"></i> Voltar</a>

                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="d-flex align-items-center">
                            <h3 class="page-title m-0">CONEXÕES ATIVAS</h3>
                            <span id="autoCleanStatus"><i class="fas fa-robot"></i> Limpeza Auto Ativa</span>
                        </div>
                        
                        <div class="refresh-control">
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="autoRefreshSwitch">
                                <label class="custom-control-label text-white small" for="autoRefreshSwitch">
                                    <i class="fas fa-sync-alt mr-1"></i> Atualizar Tela (5s)
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="card card-monitor p-3">
                        <form method="GET" action="monitor.php">
                            <div class="row mb-3 align-items-end">
                                <div class="col-md-2 col-4">
                                    <label class="text-muted small">Mostrar:</label>
                                    <select class="form-control search-input" name="limit" onchange="this.form.submit()">
                                        <option value="10" <?php if($limit==10) echo 'selected'; ?>>10</option>
                                        <option value="50" <?php if($limit==50) echo 'selected'; ?>>50</option>
                                        <option value="100" <?php if($limit==100) echo 'selected'; ?>>100</option>
                                    </select>
                                </div>
                                <div class="col-md-6 offset-md-4 col-8">
                                    <label class="text-muted small">Buscar:</label>
                                    <div class="input-group">
                                        <input type="text" name="search" class="form-control search-input" placeholder="Login..." value="<?php echo htmlspecialchars($search); ?>">
                                        <div class="input-group-append">
                                            <button class="btn btn-search btn-sm m-0" type="submit"><i class="fa fa-search"></i></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <div class="table-responsive">
                            <table class="table table-dark-custom table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th><th>Status</th><th>Login</th><th>Conteúdo</th><th>Tempo</th><th>IP</th><th>App</th><th>Local</th><th>Provedor</th><th class="text-right">Ação</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(!empty($connections)): ?>
                                        <?php foreach($connections as $conn): ?>
                                            <tr>
                                                <td><?php echo $conn['id']; ?></td>
                                                <td><span class="status-badge"></span> On</td>
                                                <td class="font-weight-bold text-white"><?php echo htmlspecialchars($conn['final_username']); ?></td>
                                                <td>
                                                    <div class="content-cell">
                                                        <?php 
                                                            $imgUrl = !empty($conn['display_logo']) ? $conn['display_logo'] : 'https://via.placeholder.com/35x35?text=...';
                                                            $displayName = $conn['display_name'];
                                                            if ($displayName === 'Conteúdo Desconhecido' && $conn['debug_id'] == 0) $displayName = 'Navegando no App';
                                                        ?>
                                                        <img src="<?php echo htmlspecialchars($imgUrl); ?>" class="channel-logo" onerror="this.src='https://via.placeholder.com/35x35?text=Img';">
                                                        <span class="text-white ml-2"><?php echo htmlspecialchars($displayName); ?></span>
                                                    </div>
                                                </td>
                                                <td><?php echo time_elapsed($conn['date_start'] ?? $conn['start_time'] ?? null); ?></td>
                                                <td><span class="ip-address"><?php echo htmlspecialchars($conn['ip'] ?? $conn['user_ip'] ?? '0.0.0.0'); ?></span></td>
                                                <td class="small text-muted" title="<?php echo htmlspecialchars($conn['user_agent'] ?? ''); ?>"><?php echo substr(htmlspecialchars($conn['user_agent'] ?? $conn['ua'] ?? 'Desconhecido'), 0, 10); ?>..</td>
                                                <td class="local-info"><i class="fa fa-spin fa-spinner small"></i></td>
                                                <td class="isp-info text-info small">...</td>
                                                <td class="text-right">
                                                    <a href="monitor.php?kill=<?php echo $conn['id']; ?>" class="btn btn-danger btn-sm px-2 py-1" onclick="return confirm('Derrubar?');"><i class="fa fa-times"></i></a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="10" class="text-center py-4 text-muted">Nenhum cliente online no momento.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <small class="text-muted">Pág <?php echo $page; ?> de <?php echo $total_pages; ?></small>
                            <div>
                                <?php if($page > 1): ?><a href="?page=<?php echo $page-1; ?>&search=<?php echo $search; ?>" class="btn btn-dark btn-sm py-1 px-2"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
                                <?php if($page < $total_pages): ?><a href="?page=<?php echo $page+1; ?>&search=<?php echo $search; ?>" class="btn btn-dark btn-sm py-1 px-2"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="text-center mt-4 text-muted small">Copyright &copy; 2026.</div>
                </main>
            </div>
        </div>
    </div>

    <script src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
    <script src="https://vendedorp2p.com/views/_js/bootstrap/bootstrap.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // ==========================================================
            // === CONFIGURAÇÃO DA LIMPEZA AUTOMÁTICA (AUTO CLEAN) ===
            // ==========================================================
            
            // Intervalo Canais: 5 minutos = 300000 ms
            setInterval(function() {
                $.get('monitor.php?auto_clean=channels', function(data) {
                    console.log('Limpeza Automática: Canais', data);
                });
            }, 300000); 

            // Intervalo Filmes/Series: 70 minutos = 4200000 ms
            setInterval(function() {
                $.get('monitor.php?auto_clean=vod', function(data) {
                    console.log('Limpeza Automática: VOD', data);
                });
            }, 4200000);

            // Mostra aviso que a automação está rodando
            $('#autoCleanStatus').fadeIn();


            // === LÓGICA DO AUTO REFRESH (ATUALIZAR TELA) ===
            var refreshInterval;
            var isAutoRefresh = localStorage.getItem('autoRefreshState') === 'true';

            $('#autoRefreshSwitch').prop('checked', isAutoRefresh);
            
            if(isAutoRefresh) startRefresh();

            $('#autoRefreshSwitch').change(function() {
                if($(this).is(':checked')) {
                    localStorage.setItem('autoRefreshState', 'true');
                    startRefresh();
                } else {
                    localStorage.setItem('autoRefreshState', 'false');
                    stopRefresh();
                }
            });

            function startRefresh() {
                refreshInterval = setInterval(function() { location.reload(); }, 5000); 
            }
            function stopRefresh() { clearInterval(refreshInterval); }

            // === SCRIPT GEOIP ===
            $('.ip-address').each(function() {
                var ip = $(this).text();
                var row = $(this).closest('tr');
                if(ip && ip !== '0.0.0.0') {
                    setTimeout(function(){
                        $.getJSON('http://ip-api.com/json/' + ip, function(data) {
                            if (data.status === 'success') {
                                row.find('.local-info').html(data.city);
                                row.find('.isp-info').text(data.isp.substring(0, 15) + '...');
                            } else {
                                row.find('.local-info').text('-');
                                row.find('.isp-info').text('-');
                            }
                        });
                    }, 100);
                }
            });
        });
    </script>
</body>
</html>