<?php
// Desativa exibição de erros no output para não quebrar a formatação da lista M3U
ini_set('display_errors', 0);
error_reporting(0);

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

$username = $_GET['username'] ?? '';
$password = $_GET['password'] ?? '';
$type     = $_GET['type'] ?? 'm3u_plus'; 
$output   = $_GET['output'] ?? 'ts';

if (empty($username) || empty($password)) {
    http_response_code(400);
    die("Parâmetros ausentes.");
}

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $check_last = $pdo->query("SHOW COLUMNS FROM `users` LIKE 'last_activity'");
    if (!$check_last->fetch()) {
        $pdo->exec("ALTER TABLE `users` ADD COLUMN `last_activity` INT(11) DEFAULT 0");
    }
} catch (PDOException $e) {}

$stmt = $pdo->prepare("SELECT id, username, exp_date, enabled FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$cliente = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$cliente || $cliente['enabled'] == 0) {
    http_response_code(401);
    die("Usuario bloqueado ou invalido.");
}
if ($cliente['exp_date'] !== null && $cliente['exp_date'] < time()) {
    http_response_code(403);
    die("Conta vencida.");
}

// Marca a atividade inicial ao baixar a lista
$pdo->prepare("UPDATE users SET last_activity = ? WHERE id = ?")->execute([time(), $cliente['id']]);

header('Content-Type: application/vnd.apple.mpegurl');
header('Content-Disposition: attachment; filename="lista_'.$cliente['username'].'.m3u"');
header('Cache-Control: no-cache, must-revalidate');

echo "#EXTM3U\n";

// ==============================================================================
// A MÁGICA: PUXAR O DNS DO LOAD BALANCER AUTOMATICAMENTE
// ==============================================================================
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$server_url = $protocol . "://" . $_SERVER['HTTP_HOST']; // DNS do painel como garantia

try {
    // Procura o LB online na tabela
    $stmtLb = $pdo->query("SELECT ip_servidor, porta FROM servidores_lb WHERE status = 1 ORDER BY id DESC LIMIT 1");
    $lbAtivo = $stmtLb->fetch(PDO::FETCH_ASSOC);
    
    if ($lbAtivo && !empty($lbAtivo['ip_servidor'])) {
        $ip_lb = trim($lbAtivo['ip_servidor']);
        $porta_lb = (isset($lbAtivo['porta']) && $lbAtivo['porta'] != 80) ? ":" . $lbAtivo['porta'] : "";
        
        // Se o seu painel original usa HTTPS, é bom forçar HTTP pro LB para evitar erro de certificado no M3U
        $server_url = "http://" . $ip_lb . $porta_lb;
    }
} catch (Exception $e) {}
// ==============================================================================

try {
    // Busca Canais Ao Vivo (Live)
    $queryLive = "SELECT s.id, s.stream_display_name, s.stream_icon, s.direct_source, c.category_name 
                  FROM streams s 
                  LEFT JOIN stream_categories c ON s.category_id = c.id 
                  WHERE s.type IN (1, 3) OR c.category_type = 'live'";
                  
    $stmtLive = $pdo->query($queryLive);
    
    if ($stmtLive) {
        while ($row = $stmtLive->fetch(PDO::FETCH_ASSOC)) {
            $id_canal = $row['id'];
            $nome     = $row['stream_display_name'];
            $logo     = $row['stream_icon'];
            $grupo    = $row['category_name'];
            $modo_direct = (isset($row['direct_source']) && $row['direct_source'] == 1);
            
            echo '#EXTINF:-1 tvg-id="" tvg-name="'.$nome.'" tvg-logo="'.$logo.'" group-title="'.$grupo.'",'.$nome."\n";
            
            if ($modo_direct) {
                // DIRECT
                echo $server_url . "/live/" . $username . "/" . $password . "/" . $id_canal . "." . $output . "\n";
            } else {
                // MODO LIVE HLS
                echo $server_url . "/hls/" . $username . "/" . $password . "/" . $id_canal . "_.m3u8\n";
            }
        }
    }

    // Busca Filmes (VOD)
    $queryVod = "SELECT s.id, s.stream_display_name, s.stream_icon, c.category_name 
                 FROM streams s 
                 LEFT JOIN stream_categories c ON s.category_id = c.id 
                 WHERE s.type = 2 OR c.category_type = 'movie'";
                 
    $stmtVod = $pdo->query($queryVod);
    
    if ($stmtVod) {
        while ($row = $stmtVod->fetch(PDO::FETCH_ASSOC)) {
            $id_filme = $row['id'];
            $nome     = $row['stream_display_name'];
            $logo     = $row['stream_icon'];
            $grupo    = $row['category_name'];
            
            echo '#EXTINF:-1 tvg-name="'.$nome.'" tvg-logo="'.$logo.'" group-title="'.$grupo.'",'.$nome."\n";
            
            $extensao_vod = ($output == 'm3u8') ? 'm3u8' : 'mp4'; 
            echo $server_url . "/movie/" . $username . "/" . $password . "/" . $id_filme . "." . $extensao_vod . "\n";
        }
    }

} catch (PDOException $e) {
    echo '#EXTINF:-1 tvg-name="ERRO" group-title="ERRO_SQL",'.$e->getMessage()."\n";
}
?>