<?php
// ssiptv.php - VERSÃO HÍBRIDA FINAL (TOKEN URL-SAFE + XTREAM + MENU COM IMAGENS)
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->exec("SET NAMES utf8"); 
} catch (Exception $e) { die(); }

// 1. AUTENTICAÇÃO
$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("Acesso negado");
}

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

// --- CORREÇÃO DO TOKEN PARA VLC (URL SAFE) ---
$token_puro = base64_encode($username . ":" . $password);
$token = "NBR_" . str_replace(['+', '/', '='], ['-', '_', ''], $token_puro);

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$server_url = $protocol . "://" . $_SERVER['HTTP_HOST'];
$base_url = $server_url . "/ssiptv.php";

echo "#EXTM3U\n";

// --- MENU PRINCIPAL (COM IMAGENS DA PASTA IMG) ---
if(isset($_GET['ssiptv'])) {
    // Bloco AO VIVO
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$server_url}/img/live.png\" size=\"Big\", AO VIVO\n";
    echo "#EXTBG:{$server_url}/img/live.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=live\n";
    
    // Bloco FILMES
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$server_url}/img/vod.png\" size=\"Big\", FILMES\n";
    echo "#EXTBG:{$server_url}/img/vod.png\n";
    echo "{$base_url}?username={$username}&password={$password}&category=vod\n";
    
    // Bloco SERIES
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"{$server_url}/img/series.png\" 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";
        echo "{$base_url}?username={$username}&password={$password}&action_get={$cat_type}&cat_id={$row['id']}\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";
        
        if ($link_mode === "1") {
            echo "{$server_url}/play/{$token}/{$row['id']}.ts\n";
        } else {
            echo "{$server_url}/live/{$username}/{$password}/{$row['id']}.ts\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";
        
        if ($link_mode === "1") {
            echo "{$server_url}/play/{$token}/{$row['id']}.{$ext}\n";
        } else {
            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 DAS SERIES ---
if(isset($_GET['series_id'])) {
    $stmt = $pdo->prepare("SELECT 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.sort ASC");
    $stmt->execute([(int)$_GET['series_id']]);
    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 "{$server_url}/play/{$token}/{$row['stream_id']}.{$ext}\n";
        } else {
            echo "{$server_url}/series/{$username}/{$password}/{$row['stream_id']}.{$ext}\n";
        }
    }
    exit;
}
?>