<?php
/**
 * GESTOR CYBER - get.php
 * Entrega de lista M3U e proxy de streams.
 *
 * Rotas:
 *   /get.php?username=X&password=X&type=m3u_plus  → lista M3U
 *   /get.php?username=X&password=X&type=xmltv     → EPG
 *   /live/USER/PASS/ID.ts   (via .htaccess → ?_route=live/USER/PASS/ID.ts)
 *   /movie/USER/PASS/ID.mkv
 *   /series/USER/PASS/ID.mkv
 */

define('GESTOR_CYBER', true);
require_once __DIR__ . '/_core.php';

if (ob_get_level()) ob_end_clean();
header('Access-Control-Allow-Origin: *');

// ══════════════════════════════════════════════════════════════════════════════
// ROTA DE STREAM: /live/USER/PASS/ID.ts
// .htaccess reescreve para get.php?_route=live/USER/PASS/ID.ts
// ══════════════════════════════════════════════════════════════════════════════
$route = $_GET['_route'] ?? '';

// Fallback: tentar pegar da REQUEST_URI
if (!$route) {
    $uri = strtok($_SERVER['REQUEST_URI'] ?? '', '?');
    $uri = preg_replace('#^.*?/get\.php#', '', $uri); // remove prefixo
    if (preg_match('#^/(live|movie|series)/#', $uri)) {
        $route = ltrim($uri, '/');
    }
}

if ($route && preg_match('#^(live|movie|series)/([^/]+)/([^/]+)/(\d+)(\.\w+)?$#', $route, $m)) {
    $type_path = $m[1];
    $u         = urldecode($m[2]);
    $p         = urldecode($m[3]);
    $stream_id = $m[4];
    $ext       = ltrim($m[5] ?? '.ts', '.');

    $auth = gc_auth($u, $p);
    if (!$auth) { http_response_code(403); echo 'Acesso negado'; exit; }

    $src = gc_source($auth['db']);
    if (!$src) { http_response_code(503); echo 'Sem fonte'; exit; }

    $base     = gc_base($src);
    $src_user = urlencode($src['username'] ?? '');
    $src_pass = urlencode($src['password'] ?? '');
    $dest     = "$base/$type_path/$src_user/$src_pass/$stream_id.$ext";

    // Redirect 302 — mais leve, deixa o app conectar direto na fonte
    header('Location: ' . $dest, true, 302);
    exit;
}

// ══════════════════════════════════════════════════════════════════════════════
// ENTREGA DE LISTA M3U
// ══════════════════════════════════════════════════════════════════════════════
$username = trim($_GET['username'] ?? '');
$password = trim($_GET['password'] ?? '');
$type     = $_GET['type'] ?? 'm3u_plus';
$output   = $_GET['output'] ?? 'ts';

$auth = gc_auth($username, $password);
if (!$auth) {
    http_response_code(403);
    header('Content-Type: text/plain');
    echo '#EXTM3U' . PHP_EOL . '# ERRO: credenciais inválidas ou assinatura expirada.';
    exit;
}

$client = $auth['client'];
$db     = $auth['db'];
$src    = gc_source($db);

if (!$src) {
    http_response_code(503);
    header('Content-Type: text/plain');
    echo '#EXTM3U' . PHP_EOL . '# ERRO: nenhuma fonte ativa.';
    exit;
}

$base     = gc_base($src);
$src_user = urlencode($src['username'] ?? '');
$src_pass = urlencode($src['password'] ?? '');
$our      = gc_our();
$allow_adult = ($client['adult_content'] ?? false) === true;

// ── EPG / XMLTV ───────────────────────────────────────────────────────────────
if ($type === 'xmltv' || $type === 'epg') {
    header('Content-Type: application/xml; charset=utf-8');
    $content = gc_fetch("$base/xmltv.php?username=$src_user&password=$src_pass", 30);
    echo $content ?: '<?xml version="1.0" encoding="utf-8"?><tv></tv>';
    exit;
}

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

// Usar cache compartilhado com player_api
$content = gc_m3u($src);

if (!$content) {
    echo '#EXTM3U' . PHP_EOL . '# ERRO: falha ao buscar lista da fonte. Verifique as configurações.';
    exit;
}

// ── Processar e reescrever URLs ───────────────────────────────────────────────
$src_host = parse_url($base, PHP_URL_HOST) ?? '';
$lines    = explode("\n", str_replace("\r", '', $content));
$out      = [];
$skip     = false;

foreach ($lines as $line) {
    $line = rtrim($line);

    if (str_starts_with($line, '#EXTINF')) {
        $lower = strtolower($line);
        $skip  = !$allow_adult && (
            str_contains($lower, 'xxx')    ||
            str_contains($lower, '+18')    ||
            str_contains($lower, 'adult')  ||
            str_contains($lower, 'erotic') ||
            str_contains($lower, 'porno')  ||
            str_contains($lower, 'sex')
        );
        if (!$skip) $out[] = $line;
        continue;
    }

    if (!str_starts_with($line, '#') && trim($line) !== '') {
        if ($skip) { $skip = false; continue; }
        // Reescrever URLs Xtream da fonte
        if ($src_host && str_contains($line, $src_host)) {
            $rewritten = preg_replace_callback(
                '#https?://[^/]+/(live|movie|series)/[^/]+/[^/]+/(\d+)(\.\w+)?#',
                fn($m) => "$our/{$m[1]}/$username/$password/{$m[2]}" . ($m[3] ?? '.ts'),
                $line
            );
            $out[] = $rewritten ?: $line;
        } else {
            $out[] = $line;
        }
        continue;
    }

    if (!$skip && $line !== '') $out[] = $line;
}

echo implode("\n", $out);
