<?php
// ssiptv.php - Correção de Filmes e Séries (Estrutura Simples)
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 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: Conta Invalida ou Vencida\n$server/erro.mp4");
}

// Configurações de Extensão
$out_param = isset($_GET['output']) ? "&output=".$_GET['output'] : "";
$ext_live  = isset($_GET['output']) ? ".".$_GET['output'] : ".ts";

echo "#EXTM3U\n";

// =================================================================
// 2. MENU PRINCIPAL (Raiz)
// =================================================================
if (!isset($_GET['category']) && !isset($_GET['live']) && !isset($_GET['vod']) && !isset($_GET['series']) && !isset($_GET['series_id'])) {
    
    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$out_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']; 
    
    $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) {
        $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'] . "$out_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";
        echo "$server/live/$username/$password/" . $ch['id'] . "$ext_live\n";
    }
    exit;
}

// =================================================================
// 5. LISTAGEM DE FILMES (VOD) - CORRIGIDO
// =================================================================
if (isset($_GET['vod'])) {
    $catId = $_GET['vod'];
    // Removido 'container_extension' para evitar erro se a coluna não existir
    $stmt = $pdo->prepare("SELECT id, name, cover_url 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'] ?: "";
        // Padrão .mp4 para garantir funcionamento
        echo "#EXTINF:-1 tvg-logo=\"$logo\" size=\"Medium\"," . $mv['name'] . "\n";
        echo "#EXTBG:\n";
        echo "$server/movie/$username/$password/" . $mv['id'] . ".mp4\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 - CORRIGIDO
// =================================================================
if (isset($_GET['series_id'])) {
    $seriesId = $_GET['series_id'];
    
    // Consulta simplificada para evitar erros de colunas inexistentes
    $sql = "SELECT e.id, e.name as ep_name, e.cover_url, 
                   s.name as season_name
            FROM episodes e
            JOIN seasons s ON e.season_id = s.id
            WHERE s.series_id = ?
            ORDER BY s.id ASC, e.id ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$seriesId]);
    $episodes = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($episodes as $ep) {
        // Monta o nome: "Temporada X - Nome do Episódio"
        $fullName = $ep['season_name'] . " - " . $ep['ep_name'];
        
        $logo = $ep['cover_url'] ?: ""; 
        
        echo "#EXTINF:-1 tvg-logo=\"$logo\" size=\"Medium\", $fullName\n";
        echo "#EXTBG:\n";
        // Padrão .mp4
        echo "$server/series/$username/$password/" . $ep['id'] . ".mp4\n";
    }
    exit;
}
?>