<?php
// ssiptv.php - Versão Otimizada (Conexão Direta DB)
require_once 'includes/db.php';

header("Content-Type: text/plain");

$username = $_GET['username'] ?? '';
$password = $_GET['password'] ?? '';
$server   = "http://" . $_SERVER['HTTP_HOST'];

// --- 1. VALIDAÇÃO DO USUÁRIO ---
$stmt = $pdo->prepare("SELECT id, active, expire_date FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || $user['active'] != 1) {
    die("#EXTM3U\n#EXTINF:-1,Erro: Usuario Invalido ou Bloqueado\nhttp://localhost/bloqueado.mp4");
}

// Configurações de Output (ts, m3u8, etc)
$output_ext = ""; 
$output_param = "";
if (isset($_GET['output'])) {
    $output_param = "&output=" . $_GET['output'];
    $output_ext   = "." . $_GET['output'];
}

echo "#EXTM3U\n";

// =================================================================
// 2. MENU PRINCIPAL (SSIPTV)
// =================================================================
if (isset($_GET['ssiptv'])) {
    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"$server/img/live.png\" size=\"Big\", CANAIS AO VIVO\n";
    echo "#EXTBG:\n";
    echo "$server/ssiptv.php?username=$username&password=$password&category=live$output_param\n";

    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"$server/img/vod.png\" size=\"Big\", FILMES\n";
    echo "#EXTBG:\n";
    echo "$server/ssiptv.php?username=$username&password=$password&category=vod\n";

    echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"$server/img/series.png\" size=\"Big\", SERIES\n";
    echo "#EXTBG:\n";
    echo "$server/ssiptv.php?username=$username&password=$password&category=series\n";
    exit;
}

// =================================================================
// 3. LISTAGEM DE CATEGORIAS
// =================================================================
if (isset($_GET['category'])) {
    $catType = $_GET['category']; // live, vod, series
    
    // Mapeia o tipo da URL para o tipo do banco de dados
    $dbType = 'channel';
    if ($catType == 'vod') $dbType = 'movie';
    if ($catType == 'series') $dbType = 'series';

    $stmt = $pdo->prepare("SELECT id, name FROM categories WHERE type = ? ORDER BY name ASC");
    $stmt->execute([$dbType]);
    $cats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($cats as $cat) {
        // Define o parâmetro correto para o próximo clique
        $nextParam = "live=";
        if ($catType == 'vod') $nextParam = "vod=";
        if ($catType == 'series') $nextParam = "series=";

        echo "#EXTINF:-1 type='playlist' tvg-logo='' size=\"Medium\", " . $cat['name'] . " \n";
        echo "#EXTBG:\n";
        echo "$server/ssiptv.php?username=$username&password=$password&$nextParam" . $cat['id'] . "$output_param\n";
    }
    exit;
}

// =================================================================
// 4. LISTAGEM DE CANAIS (LIVE)
// =================================================================
if (isset($_GET['live'])) {
    $catId = $_GET['live'];
    $stmt = $pdo->prepare("SELECT id, name, logo_url FROM channels WHERE category_id = ? ORDER BY name ASC");
    $stmt->execute([$catId]);
    $channels = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($channels as $ch) {
        $logo = $ch['logo_url'] ?: "";
        echo "#EXTINF:-1 tvg-logo=\"$logo\" size=\"Medium\"," . $ch['name'] . "\n";
        echo "#EXTBG:\n";
        // Formato: /live/user/pass/id.ts
        echo "$server/live/$username/$password/" . $ch['id'] . "$output_ext\n";
    }
    exit;
}

// =================================================================
// 5. LISTAGEM DE FILMES (VOD)
// =================================================================
if (isset($_GET['vod'])) {
    $catId = $_GET['vod'];
    // Busca extensão se tiver coluna, senão assume mp4/mkv padrão
    // Ajuste conforme seu banco. Supondo que exista 'cover_url' ou 'logo_url'
    $stmt = $pdo->prepare("SELECT id, name, cover_url, container_extension FROM movies WHERE category_id = ? ORDER BY name ASC");
    $stmt->execute([$catId]);
    $movies = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($movies as $mv) {
        $logo = $mv['cover_url'] ?: "";
        $ext = $mv['container_extension'] ?: "mp4";
        echo "#EXTINF:-1 tvg-logo=\"$logo\" size=\"Medium\"," . $mv['name'] . "\n";
        echo "#EXTBG:\n";
        // Formato: /movie/user/pass/id.ext
        echo "$server/movie/$username/$password/" . $mv['id'] . "." . $ext . "\n";
    }
    exit;
}

// =================================================================
// 6. LISTAGEM DE SÉRIES (CAPAS)
// =================================================================
if (isset($_GET['series'])) {
    $catId = $_GET['series'];
    $stmt = $pdo->prepare("SELECT id, name, cover_url FROM series WHERE category_id = ? ORDER BY name ASC");
    $stmt->execute([$catId]);
    $seriesList = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($seriesList as $serie) {
        $logo = $serie['cover_url'] ?: "";
        echo "#EXTINF:-1 type=\"playlist\" tvg-logo=\"$logo\" size=\"Medium\"," . $serie['name'] . "\n";
        echo "#EXTBG:\n";
        echo "$server/ssiptv.php?username=$username&password=$password&series_id=" . $serie['id'] . "\n";
    }
    exit;
}

// =================================================================
// 7. LISTAGEM DE EPISÓDIOS (DENTRO DA SÉRIE)
// =================================================================
if (isset($_GET['series_id'])) {
    $seriesId = $_GET['series_id'];
    
    // Busca episódios ordenados por temporada e número
    $stmt = $pdo->prepare("SELECT id, title, season_num, episode_num, container_extension, cover_url 
                           FROM episodes 
                           WHERE series_id = ? 
                           ORDER BY season_num ASC, episode_num ASC");
    $stmt->execute([$seriesId]);
    $episodes = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($episodes as $ep) {
        $season = str_pad($ep['season_num'], 2, '0', STR_PAD_LEFT);
        $episod = str_pad($ep['episode_num'], 2, '0', STR_PAD_LEFT);
        $name = "S{$season}E{$episod} - " . $ep['title'];
        
        $logo = $ep['cover_url'] ?: ""; 
        $ext = $ep['container_extension'] ?: "mp4";

        echo "#EXTINF:-1 tvg-logo=\"$logo\" size=\"Medium\", $name\n";
        echo "#EXTBG:\n";
        // Formato: /series/user/pass/id.ext
        echo "$server/series/$username/$password/" . $ep['id'] . "." . $ext . "\n";
    }
    exit;
}
?>