<?php
// Desativa erros na tela para não quebrar o M3U
error_reporting(0);
header("Content-Type: text/plain; charset=utf-8");

// 1. IMPORTA A CONFIGURAÇÃO DO SEU PAINEL
// Certifique-se que o ssiptv.php está na mesma pasta que o config.php
require_once("config.php");

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

if(empty($username) || empty($password)) {
    die("Faltam parametros de usuario e senha");
}

// 2. USA A SUA FUNÇÃO MÁGICA DE CONEXÃO
try {
    $pdo = getConexaoAtiva(); 
} catch (Exception $e) {
    die("Erro ao obter conexao ativa do painel.");
}

// 3. AUTENTICAÇÃO DO USUÁRIO NO XTREAM UI
$stmt = $pdo->prepare("SELECT id, exp_date, enabled FROM users 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'] < time())) {
    die("Usuario invalido ou expirado");
}

// Configurações de URL (Mantendo a pasta invisível)
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$server_url = $protocol . "://" . $_SERVER['HTTP_HOST'];
$base_url = $server_url . "/ssiptv.php";
$output = $_GET['output'] ?? "ts";

echo "#EXTM3U\n";

// --- MENU PRINCIPAL ---
if(isset($_GET['ssiptv'])) {
    $out_param = isset($_GET['output']) ? "&output=".$_GET['output'] : "";
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"\" size=\"Big\", AO VIVO\n";
    echo "#EXTBG:{$server_url}/img/live.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=live{$out_param}\n";
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"\" size=\"Big\", FILMES\n";
    echo "#EXTBG:{$server_url}/img/vod.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=vod\n";
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"\" size=\"Big\", SERIES\n";
    echo "#EXTBG:{$server_url}/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');

    $stmt = $pdo->prepare("SELECT id, category_name FROM stream_categories WHERE category_type = ? ORDER BY cat_order 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";
        $link_extra = ($cat_type == 'live' && isset($_GET['output'])) ? "&output=".$_GET['output'] : "";
        echo "{$base_url}?username={$username}&password={$password}&action_get={$cat_type}&cat_id={$row['id']}{$link_extra}\n";
    }
    exit;
}

// --- LISTAR CANAIS ---
if(isset($_GET['action_get']) && $_GET['action_get'] == 'live') {
    $stmt = $pdo->prepare("SELECT id, stream_display_name, stream_icon FROM streams WHERE category_id = ? AND type IN (1, 3) ORDER BY stream_display_name ASC");
    $stmt->execute([(int)$_GET['cat_id']]);
    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";
        
        // PADRÃO NOVO: Limpo, direto na raiz e sem o .ts no final para rodar liso nas TVs!
        if ($output === 'm3u8') {
            echo "{$server_url}/live/{$username}/{$password}/{$row['id']}.m3u8\n";
        } else {
            echo "{$server_url}/{$username}/{$password}/{$row['id']}\n";
        }
    }
    exit;
}

// --- LISTAR FILMES ---
if(isset($_GET['action_get']) && $_GET['action_get'] == 'vod') {
    $stmt = $pdo->prepare("SELECT id, stream_display_name, stream_icon, target_container FROM streams WHERE category_id = ? AND type = 2 ORDER BY stream_display_name ASC");
    $stmt->execute([(int)$_GET['cat_id']]);
    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";
        echo "{$server_url}/movie/{$username}/{$password}/{$row['id']}.{$ext}\n";
    }
    exit;
}

// --- LISTAR SERIES ---
if(isset($_GET['action_get']) && $_GET['action_get'] == 'series') {
    $stmt = $pdo->prepare("SELECT id, title, cover FROM series WHERE category_id = ? ORDER BY title ASC");
    $stmt->execute([(int)$_GET['cat_id']]);
    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";
    }
    exit;
}

// --- EPISODIOS ---
if(isset($_GET['series_id'])) {
    $stmt = $pdo->prepare("SELECT e.season_num, e.sort, s.id as stream_id, s.stream_display_name, s.stream_icon, s.target_container FROM series_episodes e JOIN streams s ON e.stream_id = s.id WHERE e.series_id = ? ORDER BY e.season_num ASC, e.sort ASC");
    $stmt->execute([(int)$_GET['series_id']]);
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $nome_ep = str_replace('"', '', "T".sprintf("%02d", $row['season_num'])." E".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";
        echo "{$server_url}/series/{$username}/{$password}/{$row['stream_id']}.{$ext}\n";
    }
    exit;
}
?>