<?php
// ssiptv.php - VERSÃO HÍBRIDA FINAL (TOKEN URL-SAFE + XTREAM/XUI + DNS INTELIGENTE CORRIGIDO)
error_reporting(0);
header("Content-Type: application/x-mpegurl; charset=utf-8");
header("Access-Control-Allow-Origin: *");

require_once("config.php");

$username = $_GET['username'] ?? '';
$password = $_GET['password'] ?? '';

if(empty($username) || empty($password)) { die("Faltam parametros"); }

try {
    $pdo = getConexaoAtiva();
    $pdo_int = getConexaoInterna(); // Necessário para configurações e Load Balancer
    $pdo->exec("SET NAMES utf8"); 
} catch (Exception $e) { die(); }

// ====================================================================
// 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`';
$tabela_categorias = 'stream_categories';
$tabela_series = 'series';
$tabela_episodios = 'series_episodes';
$col_sort = 'sort';

if ($modo_ativo === 'xui') {
    $col_sort = 'episode_num';
    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) { } }
    try { $pdo->query("SELECT 1 FROM streams_series LIMIT 1"); $tabela_series = 'streams_series'; } catch (Exception $e) {}
    try { $pdo->query("SELECT 1 FROM streams_episodes LIMIT 1"); $tabela_episodios = 'streams_episodes'; } catch (Exception $e) {}
}

// 1. AUTENTICAÇÃO INTELIGENTE (XUI / XTREAM)
$stmt = $pdo->prepare("SELECT id, exp_date, enabled FROM $tabela_clientes WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$user || $user['enabled'] == 0 || ($user['exp_date'] !== null && $user['exp_date'] != 0 && $user['exp_date'] < time())) {
    die("Acesso negado");
}

// 2. VERIFICA SE O SISTEMA DE TOKEN ESTÁ ATIVADO
$link_mode = "0";
try {
    // Agora busca na tabela correta do banco interno
    $stmtCfg = $pdo_int->query("SELECT value FROM custom_settings WHERE name = 'link_mode'");
    $link_mode = $stmtCfg->fetchColumn() ?: "0";
} catch (Exception $e) { $link_mode = "0"; }

$token_puro = base64_encode($username . ":" . $password);
$token = "NBR_" . str_replace(['+', '/', '='], ['-', '_', ''], $token_puro);

// ====================================================================
// LÓGICA DE URL: PAINEL VS STREAMING (LOAD BALANCER / DNS XUI)
// ====================================================================
$protocolo_painel = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$url_painel = $protocolo_painel . $_SERVER['HTTP_HOST'];
$base_url = $url_painel . "/ssiptv.php";

$url_streaming = $url_painel; // Fallback padrão
$dns_encontrado = false;

// TENTA LOAD BALANCER
try {
    $stmtLb = $pdo->query("SELECT ip_servidor, porta FROM servidores_lb WHERE status = 1 ORDER BY id DESC LIMIT 1");
    $lbAtivo = $stmtLb->fetch(PDO::FETCH_ASSOC);
    if ($lbAtivo && !empty($lbAtivo['ip_servidor'])) {
        $porta_lb = (isset($lbAtivo['porta']) && $lbAtivo['porta'] != 80 && $lbAtivo['porta'] != '') ? ":" . $lbAtivo['porta'] : "";
        $dns_val = trim($lbAtivo['ip_servidor']) . $porta_lb;
        if (strpos($dns_val, 'http') !== 0) { $dns_val = "http://" . $dns_val; }
        $url_streaming = rtrim($dns_val, '/');
        $dns_encontrado = true;
    }
} catch(Exception $e){}

// SE NÃO ACHAR LB, TENTA DNS DOS SERVIDORES OFICIAIS
if (!$dns_encontrado) {
    try {
        $tabela_servidores = ($modo_ativo === 'xui') ? 'servers' : 'streaming_servers';
        $stmtDns = $pdo->query("SELECT * FROM $tabela_servidores ORDER BY id ASC LIMIT 1");
        $serverInfo = $stmtDns->fetch(PDO::FETCH_ASSOC);
        if ($serverInfo) {
            $dns_val = '';
            if (isset($serverInfo['domain_name']) && !empty(trim($serverInfo['domain_name']))) {
                $dns_val = trim($serverInfo['domain_name']);
            } elseif (isset($serverInfo['server_ip']) && !empty(trim($serverInfo['server_ip']))) {
                $dns_val = trim($serverInfo['server_ip']);
            }
            if (!empty($dns_val)) {
                if (strpos($dns_val, 'http') !== 0) { $dns_val = "http://" . $dns_val; }
                $url_streaming = rtrim($dns_val, '/');
            }
        }
    } catch(Exception $e){}
}

// INICIA O ARQUIVO M3U
echo "#EXTM3U\n";

// --- MENU PRINCIPAL (COM IMAGENS DA PASTA IMG - USA O URL DO PAINEL) ---
if(isset($_GET['ssiptv'])) {
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$url_painel}/img/live.png\" size=\"Big\", AO VIVO\n";
    echo "#EXTBG:{$url_painel}/img/live.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=live\n";
    
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$url_painel}/img/vod.png\" size=\"Big\", FILMES\n";
    echo "#EXTBG:{$url_painel}/img/vod.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=vod\n";
    
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$url_painel}/img/series.png\" size=\"Big\", SERIES\n";
    echo "#EXTBG:{$url_painel}/img/series.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=series\n";
    exit;
}

// --- CATEGORIAS ---
if(isset($_GET['category'])) {
    $cat_type = $_GET['category'];
    $db_type = ($cat_type == 'live') ? 'live' : (($cat_type == 'vod') ? 'movie' : 'series');
    
    try {
        $stmt = $pdo->prepare("SELECT id, category_name FROM $tabela_categorias WHERE category_type = ? ORDER BY category_name ASC");
        $stmt->execute([$db_type]);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $nome_cat = str_replace('"', '', $row['category_name']);
            echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"\" size=\"Medium\", {$nome_cat}\n";
            echo "{$base_url}?username={$username}&password={$password}&action_get={$cat_type}&cat_id={$row['id']}\n";
        }
    } catch (Exception $e) {}
    exit;
}

// --- UTILITÁRIO DE FILTRO DE CATEGORIA PARA XUI E XTREAM ---
$cat_id_clean = isset($_GET['cat_id']) ? (int)$_GET['cat_id'] : 0;
$cat_filter = "(category_id = {$cat_id_clean} OR category_id LIKE '%\"{$cat_id_clean}\"%' OR category_id LIKE '%[{$cat_id_clean}]%')";

// --- LISTAR CANAIS ---
if(isset($_GET['action_get']) && $_GET['action_get'] == 'live') {
    try {
        $stmt = $pdo->query("SELECT id, stream_display_name, stream_icon FROM streams WHERE {$cat_filter} AND type IN (1, 3, 4) ORDER BY stream_display_name ASC");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $nome = str_replace('"', '', $row['stream_display_name']);
            echo "#EXTINF:-1 tvg-logo=\"{$row['stream_icon']}\" size=\"Medium\", {$nome}\n";
            
            // CORREÇÃO: SE O MODO OCULTO ESTIVER ON, USA A URL DO PAINEL PARA O PROXY FUNCIONAR
            if ($link_mode === "1") {
                echo "{$url_painel}/play/{$token}/{$row['id']}.ts\n";
            } else {
                echo "{$url_streaming}/live/{$username}/{$password}/{$row['id']}.ts\n";
            }
        }
    } catch (Exception $e) {}
    exit;
}

// --- LISTAR FILMES ---
if(isset($_GET['action_get']) && $_GET['action_get'] == 'vod') {
    try {
        $stmt = $pdo->query("SELECT id, stream_display_name, stream_icon, target_container FROM streams WHERE {$cat_filter} AND type = 2 ORDER BY stream_display_name ASC");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $nome = str_replace('"', '', $row['stream_display_name']);
            $ext = trim(str_replace(['[', ']', '"'], '', $row['target_container'])) ?: "mp4";
            echo "#EXTINF:-1 tvg-logo=\"{$row['stream_icon']}\" size=\"Medium\", {$nome}\n";
            
            if ($link_mode === "1") {
                echo "{$url_painel}/play/{$token}/{$row['id']}.{$ext}\n";
            } else {
                echo "{$url_streaming}/movie/{$username}/{$password}/{$row['id']}.{$ext}\n";
            }
        }
    } catch (Exception $e) {}
    exit;
}

// --- LISTAR SERIES ---
if(isset($_GET['action_get']) && $_GET['action_get'] == 'series') {
    try {
        $stmt = $pdo->query("SELECT id, title, cover FROM $tabela_series WHERE {$cat_filter} ORDER BY title ASC");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $nome = str_replace('"', '', $row['title']);
            echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$row['cover']}\" size=\"Medium\", {$nome}\n";
            echo "{$base_url}?username={$username}&password={$password}&series_id={$row['id']}\n";
        }
    } catch (Exception $e) {}
    exit;
}

// --- EPISODIOS DAS SERIES ---
if(isset($_GET['series_id'])) {
    $series_id_clean = (int)$_GET['series_id'];
    try {
        $stmt = $pdo->query("SELECT e.{$col_sort} as sort, s.id as stream_id, s.stream_display_name, s.stream_icon, s.target_container FROM $tabela_episodios e JOIN streams s ON e.stream_id = s.id WHERE e.series_id = {$series_id_clean} ORDER BY e.{$col_sort} ASC");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $nome_ep = "Ep. ".sprintf("%02d", $row['sort'])." - ".$row['stream_display_name'];
            $ext = trim(str_replace(['[', ']', '"'], '', $row['target_container'])) ?: "mp4";
            echo "#EXTINF:-1 tvg-logo=\"{$row['stream_icon']}\" size=\"Medium\", {$nome_ep}\n";
            
            if ($link_mode === "1") {
                echo "{$url_painel}/play/{$token}/{$row['stream_id']}.{$ext}\n";
            } else {
                echo "{$url_streaming}/series/{$username}/{$password}/{$row['stream_id']}.{$ext}\n";
            }
        }
    } catch (Exception $e) {}
    exit;
}
?>