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

$pdo = getConexaoAtiva(); // Banco Principal (Xtream ou XUI)
$pdo_int = getConexaoInterna(); // Banco Local (Configs)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

$tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';

// Tenta descobrir qual o nome correto da tabela de categorias no banco atual
$tabela_categorias = 'stream_categories';
try { 
    $pdo->query("SELECT 1 FROM streams_categories LIMIT 1"); 
    $tabela_categorias = 'streams_categories'; 
} catch (Exception $e) {
    try { 
        $pdo->query("SELECT 1 FROM categories LIMIT 1"); 
        $tabela_categorias = 'categories'; 
    } catch (Exception $e2) {
        $tabela_categorias = 'stream_categories';
    }
}

// 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 (COMPATÍVEL MYSQL 5.7 XTREAM UI) ---
try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $colunas_para_adicionar = [
        ['streams', 'direct_source', 'INT(11) DEFAULT 0'],
        ['streams', 'live_started_at', 'INT(11) DEFAULT 0'],
        ['streams', 'ffmpeg_pid', 'INT(11) DEFAULT NULL']
    ];
    
    foreach ($colunas_para_adicionar as $c) {
        $tabela = $c[0]; $coluna = $c[1]; $def = $c[2];
        try {
            $check = $pdo->query("SHOW COLUMNS FROM `$tabela` LIKE '$coluna'");
            if ($check && $check->rowCount() == 0) {
                $pdo->exec("ALTER TABLE `$tabela` ADD COLUMN `$coluna` $def");
            }
        } catch(Exception $e) {}
    }
    
    // NOVA COLUNA PARA SABER QUAL CANAL O CLIENTE ESTÁ ASSISTINDO AGORA
    $t_cli = str_replace('`', '', $tabela_clientes);
    try {
        $check = $pdo->query("SHOW COLUMNS FROM `$t_cli` LIKE 'current_channel'");
        if ($check && $check->rowCount() == 0) {
            $pdo->exec("ALTER TABLE `$t_cli` ADD COLUMN `current_channel` INT(11) DEFAULT NULL");
        }
    } catch(Exception $e) {}
    
} catch (Exception $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];
    }

    $old_pid = 0;
    try {
        $stmt = $pdo->query("SELECT ffmpeg_pid FROM streams WHERE id = $id_canal");
        if ($stmt) { $old_pid = $stmt->fetchColumn(); }
    } catch (Exception $e) {}
    
    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;
    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;
    $pid = 0;
    try {
        $stmt = $pdo->query("SELECT ffmpeg_pid FROM streams WHERE id = $id_canal");
        if ($stmt) { $pid = $stmt->fetchColumn(); }
    } catch (Exception $e) {}
    
    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");
    }
}

$tipos_live = ($modo_ativo === 'xui') ? "1, 3, 4" : "1";

// --- 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);
        try {
            $pdo->prepare("UPDATE streams SET direct_source = 0, live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $id]);
        } catch (Exception $e) {
            try { $pdo->prepare("UPDATE streams SET direct_source = 0, live_started_at = ? WHERE id = ?")->execute([time(), $id]); } catch(Exception $e2) {
                try { $pdo->prepare("UPDATE streams SET direct_source = 0 WHERE id = ?")->execute([$id]); } catch(Exception $e3) {}
            }
        }
    } else { // MUDOU PARA DIRECT
        pararFFmpeg($id);
        try {
            $pdo->prepare("UPDATE streams SET direct_source = 1, live_started_at = 0, ffmpeg_pid = NULL WHERE id = ?")->execute([$id]);
        } catch (Exception $e) {
            try { $pdo->prepare("UPDATE streams SET direct_source = 1, live_started_at = 0 WHERE id = ?")->execute([$id]); } catch(Exception $e2) {
                try { $pdo->prepare("UPDATE streams SET direct_source = 1 WHERE id = ?")->execute([$id]); } catch(Exception $e3) {}
            }
        }
    }
    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 IN ($tipos_live)")->fetchColumn();
    
    if ($source) {
        $pid = iniciarFFmpeg($id, $source);
        try {
            $pdo->prepare("UPDATE streams SET live_started_at = ?, ffmpeg_pid = ? WHERE id = ? AND direct_source = 0")->execute([time(), $pid, $id]);
        } catch (Exception $e) {
            try { $pdo->prepare("UPDATE streams SET live_started_at = ? WHERE id = ? AND direct_source = 0")->execute([time(), $id]); } catch(Exception $e2) {}
        }
        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_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo_int->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) {}

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_int->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'];
    $in = str_repeat('?,', count($ids) - 1) . '?';
    
    if ($action === 'delete') {
        foreach($ids as $id) pararFFmpeg($id);
        $pdo->prepare("DELETE FROM streams WHERE id IN ($in) AND type IN ($tipos_live)")->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);
            try {
                $pdo->prepare("UPDATE streams SET direct_source = 0, live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $id]);
            } catch(Exception $e) {
                try { $pdo->prepare("UPDATE streams SET direct_source = 0, live_started_at = ? WHERE id = ?")->execute([time(), $id]); } catch(Exception $e2) {
                    try { $pdo->prepare("UPDATE streams SET direct_source = 0 WHERE id = ?")->execute([$id]); } catch(Exception $e3) {}
                }
            }
        }
        $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);
        try {
            $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 IN ($tipos_live)")->execute($params);
        } catch(Exception $e) {
            try {
                $params = array_merge([1, 0], $ids);
                $pdo->prepare("UPDATE streams SET direct_source = ?, live_started_at = ? WHERE id IN ($in) AND type IN ($tipos_live)")->execute($params);
            } catch(Exception $e2) {
                $params = array_merge([1], $ids);
                try { $pdo->prepare("UPDATE streams SET direct_source = ? WHERE id IN ($in) AND type IN ($tipos_live)")->execute($params); } catch(Exception $e3) {}
            }
        }
        $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']);
                try {
                    $pdo->prepare("UPDATE streams SET live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $id]);
                } catch(Exception $e) {
                    try { $pdo->prepare("UPDATE streams SET live_started_at = ? WHERE id = ?")->execute([time(), $id]); } catch(Exception $e2) {}
                }
            }
        }
        $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 = (int)($_POST['category_id'] ?? 0);
    $direct = isset($_POST['direct_source']) ? (int)$_POST['direct_source'] : 0;
    $id_canal = $_POST['channel_id'] ?? null;

    $source_banco = $source;
    if ($modo_ativo === 'xui' && substr($source, 0, 1) !== '[') {
        $source_banco = json_encode([$source], JSON_UNESCAPED_SLASHES);
    }
    
    $cat_id_banco = $cat_id;
    if ($modo_ativo === 'xui') {
        $cat_id_banco = json_encode([strval($cat_id)]);
    }

    if (!empty($id_canal)) {
        if ($direct == 0) {
            $pid = iniciarFFmpeg($id_canal, $source);
            try {
                $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 IN ($tipos_live)";
                $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, time(), $pid, $id_canal]);
            } catch(Exception $e) {
                try {
                    $sql = "UPDATE streams SET stream_display_name = ?, stream_source = ?, stream_icon = ?, category_id = ?, direct_source = 0, live_started_at = ? WHERE id = ? AND type IN ($tipos_live)";
                    $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, time(), $id_canal]);
                } catch(Exception $e2) {
                    $sql = "UPDATE streams SET stream_display_name = ?, stream_source = ?, stream_icon = ?, category_id = ?, direct_source = 0 WHERE id = ? AND type IN ($tipos_live)";
                    $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, $id_canal]);
                }
            }
        } else {
            pararFFmpeg($id_canal);
            try {
                $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 IN ($tipos_live)";
                $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, $id_canal]);
            } catch(Exception $e) {
                try {
                    $sql = "UPDATE streams SET stream_display_name = ?, stream_source = ?, stream_icon = ?, category_id = ?, direct_source = 1, live_started_at = 0 WHERE id = ? AND type IN ($tipos_live)";
                    $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, $id_canal]);
                } catch(Exception $e2) {
                    $sql = "UPDATE streams SET stream_display_name = ?, stream_source = ?, stream_icon = ?, category_id = ?, direct_source = 1 WHERE id = ? AND type IN ($tipos_live)";
                    $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, $id_canal]);
                }
            }
        }
    } else {
        try {
            $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_banco, $icon, $cat_id_banco, time(), $direct]);
        } catch(Exception $e) {
            $sql = "INSERT INTO streams (stream_display_name, stream_source, stream_icon, category_id, type, added) VALUES (?, ?, ?, ?, 1, ?)";
            $res = $pdo->prepare($sql)->execute([$nome, $source_banco, $icon, $cat_id_banco, time()]);
        }
        $new_id = $pdo->lastInsertId();
        
        if ($direct == 0) {
            $pid = iniciarFFmpeg($new_id, $source);
            try {
                $pdo->prepare("UPDATE streams SET live_started_at = ?, ffmpeg_pid = ? WHERE id = ?")->execute([time(), $pid, $new_id]);
            } catch(Exception $e) {
                try { $pdo->prepare("UPDATE streams SET live_started_at = ? WHERE id = ?")->execute([time(), $new_id]); } catch(Exception $e2) {}
            }
        }
    }
    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 IN ($tipos_live)")->execute([$id_del]);
    header("Location: canais.php"); exit;
}

// --- CAPTURA DE FILTROS E PAGINAÇÃO ---
$cat_filter = $_GET['category'] ?? 'todos';
$mode_filter = $_GET['mode'] ?? '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;

// --- BUSCA INTELIGENTE DE CATEGORIAS ---
$categorias = [];
try {
    $categorias = $pdo->query("SELECT id as category_id, category_name FROM $tabela_categorias WHERE category_type = 'live' ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    try {
        $categorias = $pdo->query("SELECT id as category_id, category_name FROM $tabela_categorias ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $ex) {}
}

$where = " WHERE s.type IN ($tipos_live)";
if ($cat_filter !== 'todos') {
    $cat_id_clean = (int)$cat_filter;
    $where .= " AND (s.category_id = $cat_id_clean OR s.category_id LIKE '%\"$cat_id_clean\"%' OR s.category_id LIKE '%[$cat_id_clean]%')";
}
if ($mode_filter === 'live') $where .= " AND (s.direct_source = 0 OR s.direct_source IS NULL)";
if ($mode_filter === 'direct') $where .= " AND s.direct_source = 1";
if (!empty($search_filter))  $where .= " AND s.stream_display_name LIKE " . $pdo->quote("%$search_filter%");

// CONTAGEM DE PAGINAÇÃO
$total_registros = 0;
try {
    $total_registros = $pdo->query("SELECT COUNT(*) FROM streams s $where")->fetchColumn();
} catch (Exception $e) {}

$total_paginas = ceil($total_registros / $limit_filter);

// CONSULTA PRINCIPAL COM PROTEÇÃO PARA JSON NO JOIN
$join_cat = "REPLACE(REPLACE(REPLACE(s.category_id, '[', ''), ']', ''), '\"', '') = c.id";
$query = "SELECT s.*, c.category_name FROM streams s LEFT JOIN $tabela_categorias c ON $join_cat $where ORDER BY s.id DESC LIMIT $limit_filter OFFSET $offset";
$canais = [];

try {
    $canais = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // FALLBACK ANTI-FALHA
    try {
        $query_fallback = "SELECT s.* FROM streams s $where ORDER BY s.id DESC LIMIT $limit_filter OFFSET $offset";
        $canais = $pdo->query($query_fallback)->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e2) {}
}

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";
}

$time_limit_online = time() - 35;
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="stylesheet" href="tema.css">
    <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: 0.3s; flex-shrink: 0; z-index: 1001;}
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .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; overflow-y: auto; flex: 1; }
        .menu-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 15px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        .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(23, 162, 184, 0.15); color: var(--info); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--info); 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; }
      
        
        /* ==================================================================== */
        /* FORÇA A COR AZUL NO ADMINISTRADOR E VERDE NO SALDO */
        /* ==================================================================== */
        .user-info > div:nth-child(2), .user-info .badge { background: rgba(0, 123, 255, 0.2) !important; color: var(--accent) !important; padding: 4px 10px !important; border-radius: 4px !important; font-size: 11px !important; text-transform: uppercase !important; font-weight: bold !important; margin-top: 5px !important; margin-bottom: 5px !important; display: inline-block !important; }
        .user-info > div:nth-child(3), .user-info .credits-badge, .user-info i.fa-coins { color: var(--success) !important; font-weight: bold !important; font-size: 13px !important; display: inline-block !important; }
        .user-info > div:nth-child(3) { margin-top: 8px !important; display: block !important; }

        /* ==================================================================== */
        /* FORÇA OS ÍCONES DA SIDEBAR A FICAREM AZUIS */
        /* ==================================================================== */
        .sidebar i, .sidebar span[class*="icon"], .sidebar .fas, .sidebar .fab { color: var(--accent) !important; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--accent) !important; }
        .menu-item:hover, .menu-item.active { background-color: #2c3138 !important; color: white !important; border-left-color: var(--accent) !important; }
        .sidebar .active, .sidebar .menu-item.active, .sidebar li.active > a { border-left-color: var(--accent) !important; color: white !important; background: #24282d !important; }
        .sidebar a:hover, .sidebar .menu-item:hover { border-left-color: var(--accent) !important; color: white !important; background: #2c3138 !important; }
        
       

        @media (max-width: 768px) {
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .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; padding-bottom: 120px; }
            .modal-content { width: 90%; margin: auto; }
            .filter-bar { flex-direction: column; align-items: stretch; }
            #bulkActionsBar { flex-direction: column; align-items: stretch; }
        }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>

    <?php include 'sidebar.php'; ?>

    <div class="main">
        <header class="topbar">
            <div style="display: flex; align-items: center;">
                <button class="menu-toggle" id="btn-menu" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; color: white; margin-left:15px;">Canais Ao Vivo</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> MODO: <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></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>Modo de Transmissão</label>
                    <select name="mode">
                        <option value="todos" <?php echo $mode_filter == 'todos' ? 'selected' : ''; ?>>Todos os Modos</option>
                        <option value="live" <?php echo $mode_filter == 'live' ? 'selected' : ''; ?>>Apenas Modo LIVE</option>
                        <option value="direct" <?php echo $mode_filter == 'direct' ? 'selected' : ''; ?>>Apenas Modo DIRECT</option>
                    </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: 
                                        $id_deste_canal = $c['id'];
                                        $online_agora = 0;
                                        try {
                                            if ($modo_ativo === 'xui') {
                                                $online_agora = $pdo->query("SELECT COUNT(*) FROM `lines_activity` WHERE stream_id = $id_deste_canal AND date_end IS NULL")->fetchColumn();
                                            } else {
                                                $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();
                                            }
                                        } catch (Exception $e) {}
                                    ?>
                                        <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&mode=$mode_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>
        function toggleMenu() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('overlay').classList.toggle('active');
        }

        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_icon').value = c.stream_icon;
            document.getElementById('field_direct').value = c.direct_source || "0";

            // INTELIGÊNCIA DE PARSE DE CATEGORIA (Remove o [] se for XUI)
            let catVal = c.category_id;
            try {
                if (typeof catVal === 'string' && catVal.startsWith('[')) {
                    let parsedCat = JSON.parse(catVal);
                    if (Array.isArray(parsedCat) && parsedCat.length > 0) {
                        catVal = parsedCat[0];
                    }
                }
            } catch (e) { }
            document.getElementById('field_cat').value = catVal;

            // INTELIGÊNCIA DE PARSE DO SOURCE
            let rawSource = c.stream_source;
            try {
                if (rawSource.startsWith('[') && rawSource.endsWith(']')) {
                    let parsedSource = JSON.parse(rawSource);
                    if (Array.isArray(parsedSource) && parsedSource.length > 0) rawSource = parsedSource[0];
                }
            } catch (e) { }
            document.getElementById('field_source').value = rawSource;
            
            document.getElementById('modalChannel').style.display = 'block';
        }

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

        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';
            }
        }

        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>`;
                        
                        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>`;
                        
                        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>`;
                        }
                    }
                }
            });
        }

        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>
    <script src="tema.js"></script>
</body>
</html>
