<?php
session_start();
require_once 'config.php';

$pdo = getConexaoAtiva();

// DIRETÓRIO ONDE OS PEDAÇOS DE VÍDEO SERÃO SALVOS NA VPS (RAM DISK)
$stream_dir = "/var/www/html/streams/";

// --- LÓGICA DE AUTO-CORREÇÃO AUTOMÁTICA DO BANCO ---
try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("ALTER TABLE `streams` ADD COLUMN IF NOT EXISTS `direct_source` INT(11) DEFAULT 0");
    $pdo->exec("ALTER TABLE `streams` ADD COLUMN IF NOT EXISTS `live_started_at` INT(11) DEFAULT 0");
    $pdo->exec("ALTER TABLE `streams` ADD COLUMN IF NOT EXISTS `ffmpeg_pid` INT(11) DEFAULT NULL");
    
    // NOVA COLUNA PARA SABER QUAL CANAL O CLIENTE ESTÁ ASSISTINDO AGORA
    $pdo->exec("ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `current_channel` INT(11) DEFAULT NULL");
} catch (PDOException $e) {}

// --- FUNÇÃO PARA INICIAR O FFMPEG ---
function iniciarFFmpeg($id_canal, $source_url) {
    global $stream_dir, $pdo;
    
    if (strpos($source_url, '[') === 0) {
        $parsed = json_decode($source_url, true);
        if (is_array($parsed) && count($parsed) > 0) $source_url = $parsed[0];
    }

    $stmt = $pdo->query("SELECT ffmpeg_pid FROM streams WHERE id = $id_canal");
    $old_pid = $stmt->fetchColumn();
    
    // CORREÇÃO: Verifica se a hospedagem permite o uso do exec() antes de rodar
    if (function_exists('exec')) {
        if ($old_pid) @exec("kill -9 $old_pid");
        @exec("rm -f {$stream_dir}{$id_canal}_*");
        @exec("rm -f {$stream_dir}{$id_canal}_.m3u8");
    }

    $m3u8_file = $stream_dir . $id_canal . "_.m3u8";
    $ts_format = $stream_dir . $id_canal . "_%05d.ts";
    
    $cmd = "nohup ffmpeg -nostdin -hide_banner -err_detect ignore_err -reconnect 1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2000 -i \"$source_url\" -vcodec copy -acodec copy -f hls -hls_time 10 -hls_list_size 6 -hls_flags delete_segments+append_list -hls_segment_filename \"$ts_format\" \"$m3u8_file\" > /dev/null 2>&1 & echo $!";
    
    $pid = 0;
    // CORREÇÃO: Verifica se a hospedagem permite o uso do shell_exec() antes de rodar
    if (function_exists('shell_exec')) {
        $pid = trim(@shell_exec($cmd));
    }
    return (int)$pid;
}

// --- FUNÇÃO PARA PARAR O FFMPEG ---
function pararFFmpeg($id_canal) {
    global $stream_dir, $pdo;
    $stmt = $pdo->query("SELECT ffmpeg_pid FROM streams WHERE id = $id_canal");
    $pid = $stmt->fetchColumn();
    
    // CORREÇÃO: Verifica se a hospedagem permite o uso do exec() antes de rodar
    if (function_exists('exec')) {
        if ($pid) @exec("kill -9 $pid");
        @exec("rm -f {$stream_dir}{$id_canal}_*");
        @exec("rm -f {$stream_dir}{$id_canal}_.m3u8");
    }
}

// --- LÓGICA AJAX: MUDAR MODO RAPIDAMENTE ---
if (isset($_POST['ajax_toggle_mode'])) {
    header('Content-Type: application/json');
    $id = (int)$_POST['channel_id'];
    $new_mode = (int)$_POST['new_mode'];
    
    if ($new_mode == 0) { // MUDOU PARA LIVE
        $source = $pdo->query("SELECT stream_source FROM streams WHERE id = $id")->fetchColumn();
        $pid = iniciarFFmpeg($id, $source);
        $pdo->prepare("UPDATE streams SET direct_source = 0, live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $id]);
    } else { // MUDOU PARA DIRECT
        pararFFmpeg($id);
        $pdo->prepare("UPDATE streams SET direct_source = 1, live_started_at = 0, ffmpeg_pid = NULL WHERE id = ?")->execute([$id]);
    }
    echo json_encode(['success' => true]);
    exit;
}

// --- LÓGICA AJAX: REINICIAR CANAL INDIVIDUAL ---
if (isset($_POST['ajax_restart_live'])) {
    header('Content-Type: application/json');
    $id = (int)$_POST['channel_id'];
    $source = $pdo->query("SELECT stream_source FROM streams WHERE id = $id AND type = 1")->fetchColumn();
    
    if ($source) {
        $pid = iniciarFFmpeg($id, $source);
        $pdo->prepare("UPDATE streams SET live_started_at = ?, ffmpeg_pid = ? WHERE id = ? AND direct_source = 0")->execute([time(), $pid, $id]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
    exit;
}

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) {}

$pdo->exec("SET NAMES utf8mb4");
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$role = $_SESSION['user_role'];
$nome_usuario = $_SESSION['username'];
$user_id_logado = $_SESSION['user_id'];
$mensagem = "";

try { $user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = " . intval($user_id_logado))->fetchColumn() ?: 0; } catch (Exception $e) { $user_credits = 0; }

// --- AÇÕES EM MASSA (BULK ACTIONS) ---
if (isset($_POST['bulk_action']) && !empty($_POST['selected_channels'])) {
    $action = $_POST['bulk_action'];
    $ids = $_POST['selected_channels'];
    
    if ($action === 'delete') {
        foreach($ids as $id) pararFFmpeg($id);
        $in = str_repeat('?,', count($ids) - 1) . '?';
        $pdo->prepare("DELETE FROM streams WHERE id IN ($in) AND type = 1")->execute($ids);
        $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Canais excluídos!</div>";
    } elseif ($action === 'set_live') {
        foreach($ids as $id) {
            $source = $pdo->query("SELECT stream_source FROM streams WHERE id = $id")->fetchColumn();
            $pid = iniciarFFmpeg($id, $source);
            $pdo->prepare("UPDATE streams SET direct_source = 0, live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $id]);
        }
        $mensagem = "<div class='alert success'><i class='fas fa-server'></i> Canais iniciados em Modo LIVE com FFmpeg!</div>";
    } elseif ($action === 'set_direct') {
        foreach($ids as $id) pararFFmpeg($id);
        $in = str_repeat('?,', count($ids) - 1) . '?';
        $params = array_merge([1, 0], $ids);
        $pdo->prepare("UPDATE streams SET direct_source = ?, live_started_at = ?, ffmpeg_pid = NULL WHERE id IN ($in) AND type = 1")->execute($params);
        $mensagem = "<div class='alert success'><i class='fas fa-random'></i> Canais alterados para Modo DIRECT (Processos Finalizados)!</div>";
    } elseif ($action === 'restart_live') {
        foreach($ids as $id) {
            $canal = $pdo->query("SELECT stream_source, direct_source FROM streams WHERE id = $id")->fetch();
            if ($canal && $canal['direct_source'] == 0) {
                $pid = iniciarFFmpeg($id, $canal['stream_source']);
                $pdo->prepare("UPDATE streams SET live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $id]);
            }
        }
        $mensagem = "<div class='alert success'><i class='fas fa-sync-alt'></i> Lives reiniciadas com sucesso!</div>";
    }
}

// --- PROCESSAMENTO DE AÇÕES INDIVIDUAIS (SALVAR CANAL) ---
if (isset($_POST['action_save'])) {
    $nome = $_POST['stream_display_name'];
    $source = $_POST['stream_source'] ?? '';
    $icon = $_POST['stream_icon'] ?? '';
    $cat_id = $_POST['category_id'] ?? 0;
    $direct = isset($_POST['direct_source']) ? (int)$_POST['direct_source'] : 0;
    $id_canal = $_POST['channel_id'] ?? null;

    if (!empty($source) && substr($source, 0, 1) !== '[') {
        $source = json_encode([$source], JSON_UNESCAPED_SLASHES);
    }

    if (!empty($id_canal)) {
        if ($direct == 0) {
            $pid = iniciarFFmpeg($id_canal, $source);
            $sql = "UPDATE streams SET stream_display_name = ?, stream_source = ?, stream_icon = ?, category_id = ?, direct_source = 0, live_started_at = ?, ffmpeg_pid = ? WHERE id = ? AND type = 1";
            $res = $pdo->prepare($sql)->execute([$nome, $source, $icon, $cat_id, time(), $pid, $id_canal]);
        } else {
            pararFFmpeg($id_canal);
            $sql = "UPDATE streams SET stream_display_name = ?, stream_source = ?, stream_icon = ?, category_id = ?, direct_source = 1, live_started_at = 0, ffmpeg_pid = NULL WHERE id = ? AND type = 1";
            $res = $pdo->prepare($sql)->execute([$nome, $source, $icon, $cat_id, $id_canal]);
        }
    } else {
        $sql = "INSERT INTO streams (stream_display_name, stream_source, stream_icon, category_id, type, added, direct_source) VALUES (?, ?, ?, ?, 1, ?, ?)";
        $res = $pdo->prepare($sql)->execute([$nome, $source, $icon, $cat_id, time(), $direct]);
        $new_id = $pdo->lastInsertId();
        
        if ($direct == 0) {
            $pid = iniciarFFmpeg($new_id, $source);
            $pdo->prepare("UPDATE streams SET live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $new_id]);
        }
    }
    if($res) $mensagem = "<div class='alert success'>Canal salvo com sucesso!</div>";
}

if (isset($_GET['delete'])) {
    $id_del = (int)$_GET['delete'];
    pararFFmpeg($id_del);
    $pdo->prepare("DELETE FROM streams WHERE id = ? AND type = 1")->execute([$id_del]);
    header("Location: canais.php"); exit;
}

// --- CAPTURA DE FILTROS E PAGINAÇÃO ---
$cat_filter = $_GET['category'] ?? 'todos';
$limit_filter = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
$search_filter = $_GET['search'] ?? '';
$paged = isset($_GET['paged']) ? (int)$_GET['paged'] : 1;
if ($paged < 1) $paged = 1;
$offset = ($paged - 1) * $limit_filter;

$categorias = $pdo->query("SELECT id as category_id, category_name FROM stream_categories WHERE category_type = 'live' ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);

$where = " WHERE s.type = 1";
if ($cat_filter !== 'todos') $where .= " AND s.category_id = " . (int)$cat_filter;
if (!empty($search_filter))  $where .= " AND s.stream_display_name LIKE " . $pdo->quote("%$search_filter%");

$total_registros = $pdo->query("SELECT COUNT(*) FROM streams s $where")->fetchColumn();
$total_paginas = ceil($total_registros / $limit_filter);

$query = "SELECT s.*, c.category_name FROM streams s LEFT JOIN stream_categories c ON s.category_id = c.id $where ORDER BY s.id DESC LIMIT $limit_filter OFFSET $offset";
$canais = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);

function formatUptime($start_time) {
    if (!$start_time) return "Offline";
    $diff = time() - $start_time;
    if ($diff < 0) return "Agora";
    $days = floor($diff / 86400); $diff = $diff % 86400;
    $hours = floor($diff / 3600); $diff = $diff % 3600;
    $minutes = floor($diff / 60);
    if ($days > 0) return "{$days}d {$hours}h";
    if ($hours > 0) return "{$hours}h {$minutes}m";
    return "{$minutes} min";
}

// O TEMPO DE CORTE PARA CONSIDERAR ALGUÉM ONLINE SÃO 35 SEGUNDOS
$time_limit_online = time() - 35;
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Canais - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --bg-dark: #0f1114; 
            --bg-sidebar: #1e2227; 
            --bg-card: #272c33; 
            --text-main: #d1d5da; 
            --text-muted: #8a94a1; 
            --accent: <?php echo $cor_primaria; ?>; 
            --border-color: #3a4149; 
            --success: #28a745; 
            --danger: #dc3545; 
            --warning: #f39c12;
            --info: #17a2b8;
        }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }

        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; transition: all 0.3s ease; z-index: 1001; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; border-bottom: 1px solid var(--border-color); color: white; }
        .sidebar-header span { color: var(--accent); }
        .sidebar-logo { max-width: 180px; max-height: 60px; object-fit: contain; }
        
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .user-info .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; flex: 1; overflow-y: auto; }
        .menu-item { padding: 14px 25px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; font-size: 15px; border-left: 4px solid transparent; cursor: pointer; }
        .menu-item i:first-child { margin-right: 15px; width: 20px; text-align: center; font-size: 16px; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i { color: var(--accent); }
        
        .submenu { display: none; background: #121519; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 14px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 12px; }
        .rotate { transform: rotate(180deg); }
        
        .menu-category { padding: 20px 25px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: var(--danger); color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }

        .main { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .content-area { padding: 25px; flex: 1; }
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); white-space: nowrap; display: inline-block; }

        .filter-bar { background: var(--bg-card); padding: 15px; border-radius: 10px; border: 1px solid var(--border-color); margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; }
        .filter-group { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 150px; }
        .filter-group label { font-size: 11px; color: var(--text-muted); text-transform: uppercase; font-weight: bold; }
        .filter-bar input, .filter-bar select { background: #121519; border: 1px solid var(--border-color); color: white; padding: 10px; border-radius: 5px; font-size: 13px; width: 100%; box-sizing: border-box; }
        .btn-filter { background: var(--accent); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: 0.2s; }
        .btn-filter:hover { filter: brightness(0.8); }

        .table-container { background: var(--bg-card); border-radius: 10px; border: 1px solid var(--border-color); overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; min-width: 700px; }
        th { background: rgba(0,0,0,0.2); padding: 15px; text-align: left; font-size: 11px; color: var(--text-muted); text-transform: uppercase; }
        td { padding: 12px 15px; border-bottom: 1px solid var(--border-color); font-size: 14px; vertical-align: middle; }
        
        .channel-icon { width: 40px; height: 40px; border-radius: 5px; object-fit: contain; background: #000; border: 1px solid var(--border-color); }
        .btn-act { width: 30px; height: 30px; border-radius: 4px; border: none; color: white; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; margin-right: 5px; text-decoration: none; transition: 0.2s; }
        .bg-edit { background: var(--accent); }
        .bg-delete { background: var(--danger); }
        .btn-act:hover { filter: brightness(1.2); }

        input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; accent-color: var(--accent); }

        .bulk-bar { display: none; background: rgba(40, 167, 69, 0.1); border: 1px solid var(--success); padding: 15px; border-radius: 10px; margin-bottom: 20px; align-items: center; gap: 15px; flex-wrap: wrap; }

        .pagination { display: flex; justify-content: center; align-items: center; gap: 5px; margin: 30px 0; }
        .page-link { padding: 8px 16px; background: var(--bg-card); border: 1px solid var(--border-color); color: white; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 13px; }
        .page-link:hover, .page-link.active { background: var(--accent); border-color: var(--accent); }

        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); overflow-y: auto; }
        .modal-content { background: var(--bg-card); width: 95%; max-width: 500px; margin: 5% auto; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-size: 12px; color: var(--text-muted); }
        .form-group input, .form-group select { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; box-sizing: border-box; font-size: 14px; }

        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 24px; cursor: pointer; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .menu-toggle { display: block; margin-right: 15px; }
            .topbar { padding: 15px 20px; justify-content: flex-start; }
            .topbar-right { margin-left: auto; }
            .content-area { padding: 15px; }
        }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay"></div>

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="sidebar-logo">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $role === 'admin' ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

            <div class="menu-category">Integração & Cobrança</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            <a href="cobranca.php" class="menu-item active"><i class="fas fa-comment-dollar"></i> Central de Cobrança</a>
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</a>
            <a href="comprar_creditos.php" class="menu-item active"><i class="fas fa-shopping-cart"></i> Comprar Créditos</a>
            
            <div class="menu-item active" onclick="toggleSubmenu('appsSub')">
                <i class="fas fa-rocket"></i><span>Aplicações</span><i class="fas fa-chevron-down arrow-icon" id="arrow-appsSub"></i>
            </div>
            <div class="submenu" id="appsSub">
                <a href="loja_apps.php" class="menu-item active"><i class="fas fa-store"></i> Loja de Aplicativos</a>
                <?php if($role === 'admin'): ?>
                    <a href="admin_loja.php" class="menu-item active"><i class="fas fa-cogs"></i> Gerenciar Loja</a>
                <?php endif; ?>
                <a href="chatbot.php" class="menu-item active"><i class="fab fa-whatsapp"></i> Chatbot Automático</a>
            </div>
           <a href="admin_player_revenda.php" class="menu-item active"><i class="fas fa-play-circle"></i> WebPlayer</a>
            
   <div class="menu-category">Segurança</div>
            <a href="historico_logins.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sessões Ativas</a>

            <?php if($role === 'admin'): ?>
                <div class="menu-category">Administração</div>
                <a href="admin_monitor.php" class="menu-item active"><i class="fas fa-heartbeat"></i> Monitor do Servidor</a>
                <a href="admin_template.php" class="menu-item active"><i class="fas fa-edit"></i> Editor de Template</a>
                <a href="admin_lb.php" class="menu-item active"><i class="fas fa-server"></i> Load Balancers</a>
                <a href="guia_cloudflare.php" class="menu-item active"><i class="fas fa-cloud"></i> Guia Cloudflare</a>
                 <a href="admin_loja_creditos.php" class="menu-item active"><i class="fas fa-store"></i> Configurar Loja (PIX)</a>
                 <a href="integracoes_api.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</a>
                 <a href="admin_robo.php" class="menu-item active"><i class="fas fa-robot"></i> Robô de Cobrança</a>
                 <a href="admin_anti_bloqueio.php" class="menu-item active"><i class="fas fa-bolt"></i> Botão de Pânico</a>
                 <a href="admin_anti_fraude.php" class="menu-item active"><i class="fas fa-user-secret"></i> Radar Anti-Fraude</a>  
                 <a href="admin_watchdog.php" class="menu-item active"><i class="fas fa-dog"></i> Watchdog LB</a>  
                 
                 <a href="admin_epg_sync.php" class="menu-item active">
        <i class="fas fa-clock"></i> Sincronizar EPG
    </a>
 <div class="menu-item active" onclick="toggleSubmenu('painelSub')">
                    <i class="fas fa-desktop"></i><span>Painel</span><i class="fas fa-chevron-down arrow-icon" id="arrow-painelSub"></i>
                </div>
                <div class="submenu" id="painelSub">
                    <a href="personalizacao.php" class="menu-item active"><i class="fas fa-paint-brush"></i> Personalização</a>
                </div>

                <div class="menu-item active" onclick="toggleSubmenu('adminSub')">
                    <i class="fas fa-toolbox"></i><span>Ferramentas</span><i class="fas fa-chevron-down arrow-icon" id="arrow-adminSub"></i>
                </div>
                <div class="submenu" id="adminSub">
                    <a href="importar.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="mover_conteudos.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Mover Conteúdos</a>
                    <a href="limpeza.php" class="menu-item active"><i class="fas fa-trash-alt"></i> Limpeza de Dados</a>
                    <a href="limpar_duplicados.php" class="menu-item active"><i class="fas fa-copy"></i> Limpeza de Duplicados</a>
                    <a href="backup.php" class="menu-item active"><i class="fas fa-database"></i> Backup do Sistema</a>
                    <a href="seguranca.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sistema de Segurança</a>
                    <a href="configuracoes.php" class="menu-item active"><i class="fas fa-tools"></i> Configurações</a>
                </div>

                <div class="menu-category">Conteúdos</div>
                <a href="categorias.php" class="menu-item active"><i class="fas fa-folder-open"></i><span>Categorias</span></a>
                <div class="menu-item active" onclick="toggleSubmenu('contentSub')">
                    <i class="fas fa-layer-group"></i><span>Mídias</span><i class="fas fa-chevron-down arrow-icon" id="arrow-contentSub"></i>
                </div>
                <div class="submenu" id="contentSub">
                    <a href="bouquets.php" class="menu-item active">Editar Bouquets</a>
                    <a href="canais.php" class="menu-item active">Canais Ao Vivo</a>
                    <a href="filmes.php" class="menu-item active">Filmes (VOD)</a>
                    <a href="series.php" class="menu-item active">Séries</a>
                </div>
                 <a href="admin_autofix_vod.php" class="menu-item active"><i class="fas fa-magic"></i> Auto-Fix TMDB</a>
            <?php endif; ?>
        </div>
        <a href="logout.php" class="logout-btn"><i class="fas fa-power-off"></i> Sair</a>
    </nav>

    <div class="main">
        <header class="topbar">
            <div style="display: flex; align-items: center;">
                <button class="menu-toggle" id="btn-menu"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; color: white;">Canais Ao Vivo</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : 'INTERNO'; ?></span>
            </div>
        </header>

        <div class="content-area">
            <div style="display:flex; justify-content:flex-end; align-items:center; margin-bottom:20px;">
                <button class="btn-filter" style="background: var(--success);" onclick="openModalAdd()">+ NOVO CANAL</button>
            </div>

            <form class="filter-bar" method="GET">
                <div class="filter-group">
                    <label>Pesquisar</label>
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search_filter); ?>" placeholder="Nome do canal...">
                </div>
                <div class="filter-group">
                    <label>Categoria</label>
                    <select name="category">
                        <option value="todos">Todas as Categorias</option>
                        <?php foreach($categorias as $cat): ?>
                            <option value="<?php echo $cat['category_id']; ?>" <?php echo $cat_filter == $cat['category_id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['category_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Exibir</label>
                    <select name="limit">
                        <?php 
                        $opcoes = [10, 20, 50, 100, 250, 500, 1000, 2000, 5000];
                        foreach($opcoes as $op) {
                            $sel = ($limit_filter == $op) ? 'selected' : '';
                            echo "<option value='$op' $sel>$op por página</option>";
                        }
                        ?>
                    </select>
                </div>
                <button type="submit" class="btn-filter"><i class="fas fa-filter"></i> FILTRAR</button>
            </form>

            <?php echo $mensagem; ?>

            <form method="POST" id="bulkForm">
                <div class="bulk-bar" id="bulkActionsBar">
                    <span style="color: white; font-weight: bold; font-size: 14px;"><span id="selCount">0</span> selecionados:</span>
                    
                    <button type="submit" name="bulk_action" value="set_live" class="btn-filter" style="background: var(--success); padding: 8px 15px; font-size: 12px;" onclick="return confirm('Mudar todos os selecionados para Modo LIVE?')">
                        <i class="fas fa-server"></i> TUDO LIVE
                    </button>
                    
                    <button type="submit" name="bulk_action" value="restart_live" class="btn-filter" style="background: #3498db; padding: 8px 15px; font-size: 12px;" onclick="return confirm('Isso irá reiniciar as conexões dos canais LIVE selecionados. Deseja continuar?')">
                        <i class="fas fa-sync-alt"></i> REINICIAR LIVES
                    </button>
                    
                    <button type="submit" name="bulk_action" value="set_direct" class="btn-filter" style="background: var(--warning); color: black; padding: 8px 15px; font-size: 12px;" onclick="return confirm('Mudar todos os selecionados para Modo DIRECT?')">
                        <i class="fas fa-random"></i> TUDO DIRECT
                    </button>
                    
                    <button type="submit" name="bulk_action" value="delete" class="btn-filter" style="background: var(--danger); padding: 8px 15px; font-size: 12px;" onclick="return confirm('Tem certeza que deseja APAGAR os canais selecionados? Essa ação não pode ser desfeita.')">
                        <i class="fas fa-trash"></i> APAGAR SELECIONADOS
                    </button>
                </div>

                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th style="width: 40px; text-align: center;">
                                    <input type="checkbox" id="checkAll" onchange="toggleAllCheckboxes(this)">
                                </th>
                                <th>Logo</th>
                                <th>Nome do Canal</th>
                                <th>Modo <span style="font-size: 9px; color:var(--text-muted); text-transform:none;">(Clique para mudar)</span></th>
                                <th>Status / Uptime</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($canais as $c): ?>
                            <tr>
                                <td style="text-align: center;">
                                    <input type="checkbox" name="selected_channels[]" value="<?php echo $c['id']; ?>" class="chk-item" onchange="updateBulkBar()">
                                </td>
                                <td>
                                    <img src="<?php echo htmlspecialchars($c['stream_icon'] ?: 'https://via.placeholder.com/40?text=TV'); ?>" class="channel-icon">
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($c['stream_display_name']); ?></strong><br>
                                    <span style="font-size:11px; color:var(--text-muted);"><i class="fas fa-folder-open"></i> <?php echo htmlspecialchars($c['category_name'] ?? 'Sem Categoria'); ?></span>
                                </td>
                                
                                <td id="mode-cell-<?php echo $c['id']; ?>">
                                    <?php if(isset($c['direct_source']) && $c['direct_source'] == 1): ?>
                                        <span onclick="toggleModeAjax(<?php echo $c['id']; ?>, 0)" style="cursor:pointer; color:var(--warning); font-size:11px; font-weight:bold; background:rgba(243, 156, 18, 0.1); padding:4px 8px; border-radius:4px; border: 1px solid var(--warning); display:inline-block; transition: 0.2s;" title="Mudar para LIVE">
                                            <i class="fas fa-random"></i> DIRECT
                                        </span>
                                    <?php else: ?>
                                        <span onclick="toggleModeAjax(<?php echo $c['id']; ?>, 1)" style="cursor:pointer; color:var(--success); font-size:11px; font-weight:bold; background:rgba(40, 167, 69, 0.1); padding:4px 8px; border-radius:4px; border: 1px solid var(--success); display:inline-block; transition: 0.2s;" title="Mudar para DIRECT">
                                            <i class="fas fa-server"></i> LIVE
                                        </span>
                                    <?php endif; ?>
                                </td>
                                
                                <td id="uptime-cell-<?php echo $c['id']; ?>">
                                    <?php if(isset($c['direct_source']) && $c['direct_source'] == 1): ?>
                                        <span style="font-size:11px; color:var(--text-muted);">---</span>
                                    <?php else: 
                                        // AQUI FAZEMOS A CONTAGEM DOS CLIENTES ONLINE NESTE CANAL ESPECÍFICO
                                        $id_deste_canal = $c['id'];
                                        $online_agora = $pdo->query("SELECT COUNT(id) FROM users WHERE current_channel = $id_deste_canal AND last_activity >= $time_limit_online AND enabled = 1")->fetchColumn();
                                    ?>
                                        <span style="font-size:12px; color:var(--text-main); font-weight:bold; display:flex; align-items:center; gap:5px;">
                                            <div style="width:8px; height:8px; background:var(--success); border-radius:50%; box-shadow: 0 0 5px var(--success);"></div>
                                            <span id="uptime-text-<?php echo $c['id']; ?>"><?php echo formatUptime($c['live_started_at'] ?? 0); ?></span>
                                            
                                            <?php if ($online_agora > 0): ?>
                                                <span style="margin-left:8px; padding:2px 6px; background:rgba(23, 162, 184, 0.2); color:var(--info); border-radius:4px; font-size:10px; border:1px solid var(--info);">
                                                    <i class="fas fa-eye"></i> <?php echo $online_agora; ?> Online
                                                </span>
                                            <?php else: ?>
                                                <span style="margin-left:8px; padding:2px 6px; background:rgba(255, 255, 255, 0.05); color:var(--text-muted); border-radius:4px; font-size:10px; border:1px solid var(--border-color);">
                                                    <i class="fas fa-eye"></i> 0 Online
                                                </span>
                                            <?php endif; ?>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                
                                <td>
                                    <?php if(!isset($c['direct_source']) || $c['direct_source'] == 0): ?>
                                        <button type="button" id="btn-restart-<?php echo $c['id']; ?>" class="btn-act" style="background:#3498db;" onclick="restartLiveAjax(<?php echo $c['id']; ?>)" title="Reiniciar Conexão (Resetar Uptime)">
                                            <i class="fas fa-sync-alt"></i>
                                        </button>
                                    <?php else: ?>
                                        <span id="btn-restart-<?php echo $c['id']; ?>" style="display:inline-block; width:30px; height:30px; margin-right:5px;"></span>
                                    <?php endif; ?>

                                    <button type="button" class="btn-act bg-edit" onclick='openModalEdit(<?php echo htmlspecialchars(json_encode($c), ENT_QUOTES, "UTF-8"); ?>)'><i class="fas fa-edit"></i></button>
                                    <a href="?delete=<?php echo $c['id']; ?>" class="btn-act bg-delete" onclick="return confirm('Excluir canal?')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; if(empty($canais)) echo "<tr><td colspan='6' style='text-align:center;'>Nenhum canal encontrado.</td></tr>"; ?>
                        </tbody>
                    </table>
                </div>
            </form>

            <?php if($total_paginas > 1): ?>
            <div class="pagination">
                <?php 
                $url_params = "search=" . urlencode($search_filter) . "&category=$cat_filter&limit=$limit_filter";
                if($paged > 1): ?>
                    <a href="?<?php echo $url_params; ?>&paged=<?php echo $paged - 1; ?>" class="page-link">« Anterior</a>
                <?php endif; ?>
                <span style="color:var(--text-muted); margin:0 10px; font-size:13px;">Página <?php echo $paged; ?> de <?php echo $total_paginas; ?></span>
                <?php if($paged < $total_paginas): ?>
                    <a href="?<?php echo $url_params; ?>&paged=<?php echo $paged + 1; ?>" class="page-link">Próxima »</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalChannel" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle" style="margin-top:0;">Novo Canal</h3>
            <form method="POST">
                <input type="hidden" name="channel_id" id="channel_id">
                <div class="form-group">
                    <label>Nome do Canal</label>
                    <input type="text" name="stream_display_name" id="field_name" required>
                </div>
                <div class="form-group">
                    <label>Categoria</label>
                    <select name="category_id" id="field_cat">
                        <?php foreach($categorias as $cat): ?>
                            <option value="<?php echo $cat['category_id']; ?>"><?php echo htmlspecialchars($cat['category_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>URL do Stream (Fonte Original)</label>
                    <input type="text" name="stream_source" id="field_source" required>
                </div>
                
                <div class="form-group">
                    <label>Modo de Transmissão</label>
                    <select name="direct_source" id="field_direct">
                        <option value="0">Modo LIVE (Servidor puxa 1 vez e distribui)</option>
                        <option value="1">Modo DIRECT (Cliente acessa a fonte direto)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>URL do Ícone</label>
                    <input type="text" name="stream_icon" id="field_icon">
                </div>
                <button type="submit" name="action_save" style="width:100%; padding:12px; border:none; border-radius:6px; background:var(--accent); color:white; font-weight:bold; cursor:pointer;">SALVAR CANAL</button>
                <button type="button" onclick="closeModal()" style="background:none; border:none; color:var(--text-muted); width:100%; margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <script>
        const btnMenu = document.getElementById('btn-menu');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        
        function toggleMenu() {
            sidebar.classList.toggle('active');
            overlay.classList.toggle('active');
        }
        btnMenu.onclick = toggleMenu;
        overlay.onclick = toggleMenu;

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            if (sub.style.display === "block") {
                sub.style.display = "none";
                if(arrow) arrow.classList.remove('rotate');
            } else {
                sub.style.display = "block";
                if(arrow) arrow.classList.add('rotate');
            }
        }

        function openModalAdd() {
            document.getElementById('modalTitle').innerText = "Novo Canal";
            document.getElementById('channel_id').value = "";
            document.getElementById('field_name').value = "";
            document.getElementById('field_source').value = "";
            document.getElementById('field_icon').value = "";
            document.getElementById('field_direct').value = "0"; 
            document.getElementById('modalChannel').style.display = 'block';
        }

        function openModalEdit(c) {
            document.getElementById('modalTitle').innerText = "Editar Canal";
            document.getElementById('channel_id').value = c.id;
            document.getElementById('field_name').value = c.stream_display_name;
            document.getElementById('field_cat').value = c.category_id;
            document.getElementById('field_icon').value = c.stream_icon;
            document.getElementById('field_direct').value = c.direct_source || "0";

            let rawSource = c.stream_source;
            try {
                if (rawSource.startsWith('[') && rawSource.endsWith(']')) {
                    let parsed = JSON.parse(rawSource);
                    if (Array.isArray(parsed) && parsed.length > 0) rawSource = parsed[0];
                }
            } catch (e) { }
            document.getElementById('field_source').value = rawSource;
            document.getElementById('modalChannel').style.display = 'block';
        }

        function closeModal() { document.getElementById('modalChannel').style.display = 'none'; }

        // --- FUNÇÕES DE SELEÇÃO E AÇÃO EM MASSA ---
        function toggleAllCheckboxes(source) {
            const checkboxes = document.querySelectorAll('.chk-item');
            checkboxes.forEach(chk => chk.checked = source.checked);
            updateBulkBar();
        }

        function updateBulkBar() {
            const checkedCount = document.querySelectorAll('.chk-item:checked').length;
            const bar = document.getElementById('bulkActionsBar');
            document.getElementById('selCount').innerText = checkedCount;
            
            if (checkedCount > 0) {
                bar.style.display = 'flex';
            } else {
                bar.style.display = 'none';
            }
        }

        // --- FUNÇÃO AJAX: ALTERAR MODO ---
        function toggleModeAjax(id, newMode) {
            const formData = new FormData();
            formData.append('ajax_toggle_mode', '1');
            formData.append('channel_id', id);
            formData.append('new_mode', newMode);

            fetch('canais.php', { method: 'POST', body: formData })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const cell = document.getElementById('mode-cell-' + id);
                    const uptimeCell = document.getElementById('uptime-cell-' + id);
                    const btnRestart = document.getElementById('btn-restart-' + id);

                    if (newMode === 1) {
                        cell.innerHTML = `<span onclick="toggleModeAjax(${id}, 0)" style="cursor:pointer; color:var(--warning); font-size:11px; font-weight:bold; background:rgba(243, 156, 18, 0.1); padding:4px 8px; border-radius:4px; border: 1px solid var(--warning); display:inline-block; transition: 0.2s;" title="Mudar para LIVE"><i class="fas fa-random"></i> DIRECT</span>`;
                        uptimeCell.innerHTML = `<span style="font-size:11px; color:var(--text-muted);">---</span>`;
                        
                        // Oculta o botão de reiniciar se virar Direct
                        if(btnRestart) {
                            btnRestart.outerHTML = `<span id="btn-restart-${id}" style="display:inline-block; width:30px; height:30px; margin-right:5px;"></span>`;
                        }
                    } else {
                        cell.innerHTML = `<span onclick="toggleModeAjax(${id}, 1)" style="cursor:pointer; color:var(--success); font-size:11px; font-weight:bold; background:rgba(40, 167, 69, 0.1); padding:4px 8px; border-radius:4px; border: 1px solid var(--success); display:inline-block; transition: 0.2s;" title="Mudar para DIRECT"><i class="fas fa-server"></i> LIVE</span>`;
                        uptimeCell.innerHTML = `<span style="font-size:12px; color:var(--text-main); font-weight:bold; display:flex; align-items:center; gap:5px;"><div style="width:8px; height:8px; background:var(--success); border-radius:50%; box-shadow: 0 0 5px var(--success);"></div><span id="uptime-text-${id}">Agora</span><span style="margin-left:8px; padding:2px 6px; background:rgba(255, 255, 255, 0.05); color:var(--text-muted); border-radius:4px; font-size:10px; border:1px solid var(--border-color);"><i class="fas fa-eye"></i> 0 Online</span></span>`;
                        
                        // Mostra o botão de reiniciar se virar Live
                        const emptySpan = document.getElementById(`btn-restart-${id}`);
                        if(emptySpan && emptySpan.tagName === 'SPAN') {
                            emptySpan.outerHTML = `<button type="button" id="btn-restart-${id}" class="btn-act" style="background:#3498db;" onclick="restartLiveAjax(${id})" title="Reiniciar Conexão (Resetar Uptime)"><i class="fas fa-sync-alt"></i></button>`;
                        }
                    }
                }
            });
        }

        // --- FUNÇÃO AJAX: REINICIAR CANAL (ZERAR TIMER) ---
        function restartLiveAjax(id) {
            const icon = document.querySelector(`#btn-restart-${id} i`);
            icon.classList.add('fa-spin'); 
            
            const formData = new FormData();
            formData.append('ajax_restart_live', '1');
            formData.append('channel_id', id);

            fetch('canais.php', { method: 'POST', body: formData })
            .then(response => response.json())
            .then(data => {
                icon.classList.remove('fa-spin');
                if (data.success) {
                    document.getElementById('uptime-text-' + id).innerText = "Agora";
                }
            });
        }
    </script>
</body>
</html>