<?php
// get.php - CANAIS EM .M3U8 + TOKEN + LOAD BALANCER
ini_set('display_errors', 0);
error_reporting(0);

set_time_limit(0); 
ini_set('memory_limit', '1024M'); 

require_once 'config.php';
$pdo = getConexaoAtiva();

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

if (empty($username) || empty($password)) {
    header("HTTP/1.0 400 Bad Request");
    die("Parametros ausentes.");
}

// 1. VALIDAÇÃO DO CLIENTE
$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'] != 0 && $user['exp_date'] < time())) {
    header("HTTP/1.0 401 Unauthorized");
    die("Acesso Negado.");
}

// 2. LÓGICA DE DNS (LOAD BALANCER)
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$server_url = $protocol . "://" . $_SERVER['HTTP_HOST']; 

try {
    $stmtLB = $pdo->query("SELECT ip_servidor, porta FROM servidores_lb WHERE status = 1");
    $todos_lbs = $stmtLB->fetchAll(PDO::FETCH_ASSOC);
    if (count($todos_lbs) > 0) {
        $lb = $todos_lbs[array_rand($todos_lbs)];
        $dns_escolhido = trim($lb['ip_servidor']);
        $porta_escolhida = (int)$lb['porta'];
        $prot_lb = ($porta_escolhida == 443) ? "https" : "http";
        if ($porta_escolhida == 80 || $porta_escolhida == 443) {
            $server_url = "{$prot_lb}://{$dns_escolhido}";
        } else {
            $server_url = "{$prot_lb}://{$dns_escolhido}:{$porta_escolhida}";
        }
    }
} catch (Exception $e) {}

// 3. VERIFICA MODO TOKEN
$usar_token = false;
$token_val = "";
try {
    $stmtCfg = $pdo->query("SELECT m3u_token_mode FROM painel_config LIMIT 1");
    if ($stmtCfg->fetchColumn() == 1) {
        $usar_token = true;
        $token_val = "NBR_" . base64_encode($username . ":" . $password);
    }
} catch (Exception $e) { $usar_token = false; }

// 4. HEADERS M3U
header("Content-Type: application/x-mpegurl; charset=utf-8");
header('Content-Disposition: attachment; filename="lista.m3u"');

echo "#EXTM3U\n";
echo "#EXT-X-SESSION-DATA:DATA-ID=\"com.Koffice.Panel.4.1.23\"\n";

$cats = [];
$resC = $pdo->query("SELECT id, category_name FROM stream_categories");
while($c = $resC->fetch()) { $cats[$c['id']] = $c['category_name']; }

// --- CANAIS AO VIVO (AGORA COM .M3U8) ---
$qLive = $pdo->query("SELECT id, stream_display_name, stream_icon, category_id FROM streams WHERE type IN (1, 3) ORDER BY stream_display_name ASC");
while ($row = $qLive->fetch(PDO::FETCH_ASSOC)) {
    $n_cat = $cats[$row['category_id']] ?? 'Canais';
    echo '#EXTINF:-1 tvg-logo="'.$row['stream_icon'].'" group-title="'.$n_cat.'",'.$row['stream_display_name']."\n";
    
    // MUDANÇA AQUI: .m3u8 no final do link de canais
    if ($usar_token) {
        echo "{$server_url}/play/{$token_val}/{$row['id']}.m3u8\n";
    } else {
        echo "{$server_url}/live/{$username}/{$password}/{$row['id']}.m3u8\n";
    }
}

// --- FILMES (VOD) ---
$qVod = $pdo->query("SELECT id, stream_display_name, stream_icon, category_id, target_container FROM streams WHERE type = 2 ORDER BY id DESC");
while ($row = $qVod->fetch(PDO::FETCH_ASSOC)) {
    $n_cat = $cats[$row['category_id']] ?? 'Filmes';
    $ext = trim(str_replace(['[', ']', '"'], '', $row['target_container'])) ?: "mp4";
    echo '#EXTINF:-1 tvg-logo="'.$row['stream_icon'].'" group-title="'.$n_cat.'",'.$row['stream_display_name']."\n";
    if ($usar_token) {
        echo "{$server_url}/play/{$token_val}/{$row['id']}.{$ext}\n";
    } else {
        echo "{$server_url}/movie/{$username}/{$password}/{$row['id']}.{$ext}\n";
    }
}

// --- SÉRIES ---
$qSeries = $pdo->query("SELECT id, title, cover, category_id FROM series ORDER BY title ASC");
while ($s = $qSeries->fetch(PDO::FETCH_ASSOC)) {
    $id_serie = $s['id'];
    $grupo = $cats[$s['category_id']] ?? 'Series';
    $stmtEp = $pdo->prepare("SELECT e.stream_id, s.stream_display_name, s.target_container, e.season_num, e.sort 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");
    $stmtEp->execute([$id_serie]);
    while ($ep = $stmtEp->fetch(PDO::FETCH_ASSOC)) {
        $nome_ep = $s['title'] . " - S" . sprintf("%02d", $ep['season_num']) . "E" . sprintf("%02d", $ep['sort']) . " " . $ep['stream_display_name'];
        $ext_ep = trim(str_replace(['[', ']', '"'], '', $ep['target_container'])) ?: "mp4";
        echo '#EXTINF:-1 tvg-logo="'.$s['cover'].'" group-title="'.$grupo.'",'.$nome_ep."\n";
        if ($usar_token) {
            echo "{$server_url}/play/{$token_val}/{$ep['stream_id']}.{$ext_ep}\n";
        } else {
            echo "{$server_url}/series/" . $username . "/" . $password . "/" . $ep['stream_id'] . "." . $ext_ep . "\n";
        }
    }
}
exit;