<?php
/**
 * GESTOR CYBER - debug.php
 * Página de diagnóstico — DELETE após resolver o problema!
 * Acesso: http://seudominio.com/debug.php?key=gestor2025
 */

// Chave de acesso simples para não deixar aberto
$KEY = 'gestor2025';
if (($_GET['key'] ?? '') !== $KEY) {
    http_response_code(403);
    die('<h2>Acesso negado. Use ?key=gestor2025</h2>');
}

define('DB_FILE', __DIR__ . '/database.json');

$db     = json_decode(file_get_contents(DB_FILE), true) ?? [];
$src    = null;
foreach ($db['sources'] ?? [] as $s) {
    if (($s['status'] ?? 'active') === 'active') { $src = $s; break; }
}

// Ação de teste
$action = $_GET['action'] ?? 'info';
$result = [];

if ($action === 'fetch_m3u' && $src) {
    $p    = parse_url($src['url']);
    $base = ($p['scheme'] ?? 'http') . '://' . ($p['host'] ?? '') . (isset($p['port']) ? ':' . $p['port'] : '');
    $u    = urlencode($src['username'] ?? '');
    $pw   = urlencode($src['password'] ?? '');

    $urls_to_try = [
        "get.php"       => "$base/get.php?username=$u&password=$pw&type=m3u_plus&output=ts",
        "player_api"    => "$base/player_api.php?username=$u&password=$pw",
        "xmltv"         => "$base/xmltv.php?username=$u&password=$pw",
        "get_m3u_plain" => "$base/get.php?username=$u&password=$pw&type=m3u",
    ];

    foreach ($urls_to_try as $label => $url) {
        $ctx = stream_context_create([
            'http' => [
                'timeout'         => 15,
                'follow_location' => true,
                'ignore_errors'   => true,
                'user_agent'      => 'Mozilla/5.0',
            ]
        ]);
        $t0      = microtime(true);
        $content = @file_get_contents($url, false, $ctx);
        $elapsed = round((microtime(true) - $t0) * 1000);
        $headers = $http_response_header ?? [];
        $status  = $headers[0] ?? 'N/A';

        $result[$label] = [
            'url'          => $url,
            'status'       => $status,
            'time_ms'      => $elapsed,
            'size_bytes'   => $content !== false ? strlen($content) : 0,
            'success'      => $content !== false && strlen($content) > 20,
            'preview'      => $content !== false ? mb_substr($content, 0, 300) : 'FALHOU - file_get_contents retornou false',
            'has_extinf'   => $content !== false ? (str_contains($content, '#EXTINF') ? 'SIM ✓' : 'NÃO ✗') : 'N/A',
            'has_extm3u'   => $content !== false ? (str_contains($content, '#EXTM3U') ? 'SIM ✓' : 'NÃO ✗') : 'N/A',
        ];
    }
}

if ($action === 'php_info') {
    $result = [
        'php_version'           => PHP_VERSION,
        'allow_url_fopen'       => ini_get('allow_url_fopen') ? 'ON ✓' : 'OFF ✗ (PROBLEMA!)',
        'allow_url_include'     => ini_get('allow_url_include') ? 'ON' : 'OFF',
        'curl_enabled'          => function_exists('curl_init') ? 'SIM ✓' : 'NÃO',
        'openssl_enabled'       => extension_loaded('openssl') ? 'SIM ✓' : 'NÃO',
        'default_socket_timeout'=> ini_get('default_socket_timeout'),
        'max_execution_time'    => ini_get('max_execution_time'),
        'disable_functions'     => ini_get('disable_functions') ?: '(nenhuma)',
        'temp_dir'              => sys_get_temp_dir(),
        'temp_writable'         => is_writable(sys_get_temp_dir()) ? 'SIM ✓' : 'NÃO ✗',
        'db_file_exists'        => file_exists(DB_FILE) ? 'SIM ✓' : 'NÃO ✗',
        'db_file_readable'      => is_readable(DB_FILE) ? 'SIM ✓' : 'NÃO ✗',
        'db_file_writable'      => is_writable(DB_FILE) ? 'SIM ✓' : 'NÃO ✗',
        'sources_count'         => count($db['sources'] ?? []),
        'clients_count'         => count($db['clients'] ?? []),
    ];
}

if ($action === 'curl_test' && $src) {
    if (!function_exists('curl_init')) {
        $result = ['error' => 'cURL não disponível'];
    } else {
        $p    = parse_url($src['url']);
        $base = ($p['scheme'] ?? 'http') . '://' . ($p['host'] ?? '') . (isset($p['port']) ? ':' . $p['port'] : '');
        $u    = urlencode($src['username'] ?? '');
        $pw   = urlencode($src['password'] ?? '');
        $url  = "$base/get.php?username=$u&password=$pw&type=m3u_plus&output=ts";

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_USERAGENT      => 'Mozilla/5.0',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_ENCODING       => '',
        ]);
        $t0      = microtime(true);
        $content = curl_exec($ch);
        $elapsed = round((microtime(true) - $t0) * 1000);
        $info    = curl_getinfo($ch);
        $err     = curl_error($ch);
        curl_close($ch);

        $result = [
            'url'           => $url,
            'http_code'     => $info['http_code'],
            'time_ms'       => $elapsed,
            'size_bytes'    => strlen($content ?: ''),
            'curl_error'    => $err ?: 'nenhum',
            'has_extm3u'    => str_contains($content ?: '', '#EXTM3U') ? 'SIM ✓' : 'NÃO ✗',
            'has_extinf'    => str_contains($content ?: '', '#EXTINF') ? 'SIM ✓' : 'NÃO ✗',
            'preview'       => mb_substr($content ?: '', 0, 400),
            'content_type'  => $info['content_type'] ?? '',
            'redirect_url'  => $info['redirect_url'] ?? '',
            'total_redirects' => $info['redirect_count'] ?? 0,
        ];
    }
}

if ($action === 'parse_test' && $src) {
    // Buscar e contar canais por tipo
    $p    = parse_url($src['url']);
    $base = ($p['scheme'] ?? 'http') . '://' . ($p['host'] ?? '') . (isset($p['port']) ? ':' . $p['port'] : '');
    $u    = urlencode($src['username'] ?? '');
    $pw   = urlencode($src['password'] ?? '');

    // Tentar com file_get_contents
    $ctx     = stream_context_create(['http' => ['timeout' => 30, 'follow_location' => true, 'user_agent' => 'Mozilla/5.0', 'ignore_errors' => true]]);
    $content = @file_get_contents("$base/get.php?username=$u&password=$pw&type=m3u_plus", false, $ctx);

    // Fallback: cURL
    if (($content === false || strlen($content) < 10) && function_exists('curl_init')) {
        $ch = curl_init("$base/get.php?username=$u&password=$pw&type=m3u_plus&output=ts");
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 30, CURLOPT_USERAGENT => 'Mozilla/5.0', CURLOPT_SSL_VERIFYPEER => false, CURLOPT_ENCODING => '']);
        $content = curl_exec($ch);
        curl_close($ch);
        $result['fetch_method'] = 'cURL (fallback)';
    } else {
        $result['fetch_method'] = 'file_get_contents';
    }

    if ($content === false || strlen($content) < 10) {
        $result['error'] = 'Não foi possível buscar a lista M3U';
    } else {
        $lines  = explode("\n", $content);
        $total  = 0; $live = 0; $movie = 0; $series = 0; $groups = [];
        $current_group = '';
        foreach ($lines as $line) {
            $line = trim($line);
            if (str_starts_with($line, '#EXTINF')) {
                $total++;
                if (preg_match('/group-title="([^"]*)"/', $line, $m)) $current_group = $m[1];
                else $current_group = '';
                $lg = strtolower($current_group);
                if (str_contains($lg, 'vod') || str_contains($lg, 'movie') || str_contains($lg, 'filme')) $movie++;
                elseif (str_contains($lg, 'serie')) $series++;
                else $live++;
                $g = $current_group ?: 'Sem grupo';
                $groups[$g] = ($groups[$g] ?? 0) + 1;
            }
        }
        arsort($groups);
        $result += [
            'total_bytes'   => strlen($content),
            'total_lines'   => count($lines),
            'total_channels'=> $total,
            'live_channels' => $live,
            'movie_channels'=> $movie,
            'series_channels'=> $series,
            'unique_groups' => count($groups),
            'top_10_groups' => array_slice($groups, 0, 10, true),
            'first_500_chars' => mb_substr($content, 0, 500),
        ];
    }
}

?><!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GESTOR CYBER — Debug</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
  body { background:#070b14; color:#c8d6e5; font-family:monospace; }
  .card { background:#0f172a; border:1px solid rgba(0,240,255,0.2); border-radius:4px; padding:20px; margin-bottom:16px; }
  .card::before { content:''; display:block; height:2px; background:linear-gradient(90deg,transparent,#00f0ff,transparent); margin-bottom:16px; margin-top:-20px; margin-left:-20px; margin-right:-20px; border-radius:4px 4px 0 0; }
  .label { color:rgba(0,240,255,0.5); font-size:0.7rem; letter-spacing:0.1em; text-transform:uppercase; }
  .val   { color:#e2e8f0; }
  .ok    { color:#39ff14; }
  .bad   { color:#ff2d78; }
  .warn  { color:#ffe600; }
  pre    { background:#050810; border:1px solid rgba(0,240,255,0.1); padding:12px; border-radius:2px; overflow-x:auto; font-size:0.75rem; color:#39ff14; white-space:pre-wrap; word-break:break-all; }
  .btn   { display:inline-block; font-family:monospace; font-size:0.7rem; padding:8px 18px; border:1px solid #00f0ff; color:#00f0ff; background:rgba(0,240,255,0.06); border-radius:2px; text-decoration:none; margin:4px; cursor:pointer; }
  .btn:hover { background:rgba(0,240,255,0.15); }
  .btn-g { border-color:#39ff14; color:#39ff14; background:rgba(57,255,20,0.06); }
  .btn-y { border-color:#ffe600; color:#ffe600; background:rgba(255,230,0,0.06); }
  .btn-p { border-color:#ff2d78; color:#ff2d78; background:rgba(255,45,120,0.06); }
  h1 { font-size:1.2rem; color:#00f0ff; text-shadow:0 0 10px #00f0ff; letter-spacing:0.15em; margin-bottom:4px; }
  h2 { font-size:0.85rem; color:#ffe600; letter-spacing:0.1em; margin-bottom:12px; }
  table { width:100%; border-collapse:collapse; font-size:0.8rem; }
  td,th { padding:7px 10px; border-bottom:1px solid rgba(255,255,255,0.05); text-align:left; vertical-align:top; }
  th { color:rgba(0,240,255,0.4); font-size:0.65rem; letter-spacing:0.1em; text-transform:uppercase; }
</style>
</head>
<body class="p-6 max-w-5xl mx-auto">

<h1>⬡ GESTOR CYBER — DIAGNÓSTICO</h1>
<p class="text-xs text-slate-500 mb-6">⚠️ Delete este arquivo após resolver o problema.</p>

<!-- MENU -->
<div class="card">
  <h2>TESTES DISPONÍVEIS</h2>
  <a href="?key=<?= $KEY ?>&action=php_info"   class="btn">① INFO PHP + SERVIDOR</a>
  <a href="?key=<?= $KEY ?>&action=fetch_m3u"  class="btn btn-g">② FETCH M3U (file_get_contents)</a>
  <a href="?key=<?= $KEY ?>&action=curl_test"  class="btn btn-y">③ FETCH M3U (cURL)</a>
  <a href="?key=<?= $KEY ?>&action=parse_test" class="btn btn-p">④ PARSEAR M3U + CONTAR CANAIS</a>
</div>

<!-- FONTE ATIVA -->
<div class="card">
  <h2>FONTE ATIVA NO DATABASE</h2>
  <?php if ($src): ?>
  <table>
    <tr><th>Campo</th><th>Valor</th></tr>
    <tr><td class="label">Nome</td><td class="val"><?= htmlspecialchars($src['name'] ?? '') ?></td></tr>
    <tr><td class="label">URL</td><td class="val"><?= htmlspecialchars($src['url'] ?? '') ?></td></tr>
    <tr><td class="label">Usuário</td><td class="val"><?= htmlspecialchars($src['username'] ?? '') ?></td></tr>
    <tr><td class="label">Senha</td><td class="val"><?= str_repeat('•', strlen($src['password'] ?? '')) ?> (<?= strlen($src['password'] ?? '') ?> chars)</td></tr>
    <tr><td class="label">Status</td><td class="<?= ($src['status'] ?? '') === 'active' ? 'ok' : 'bad' ?>"><?= $src['status'] ?? '' ?></td></tr>
    <tr><td class="label">URL de teste</td>
      <td><a href="<?= htmlspecialchars(
        (fn($p, $u, $pw) => ($p['scheme']??'http').'://'.($p['host']??'').(isset($p['port'])?':'.$p['port']:'')."/get.php?username=$u&password=$pw&type=m3u_plus")(parse_url($src['url']), urlencode($src['username']??''), urlencode($src['password']??''))
      ) ?>" target="_blank" class="ok">Abrir M3U direto no browser →</a></td></tr>
  </table>
  <?php else: ?>
  <p class="bad">⚠ Nenhuma fonte ativa encontrada no database.json!</p>
  <?php endif; ?>
</div>

<!-- RESULTADO -->
<?php if (!empty($result)): ?>
<div class="card">
  <h2>RESULTADO: <?= strtoupper($action) ?></h2>

  <?php if ($action === 'fetch_m3u'): ?>
    <?php foreach ($result as $label => $r): ?>
    <div style="margin-bottom:20px; padding-bottom:16px; border-bottom:1px solid rgba(0,240,255,0.08)">
      <div class="warn" style="margin-bottom:8px; font-size:0.8rem;">▶ <?= strtoupper($label) ?></div>
      <table>
        <tr><td class="label" style="width:140px">HTTP Status</td><td class="<?= str_contains($r['status'],'200') ? 'ok' : 'bad' ?>"><?= htmlspecialchars($r['status']) ?></td></tr>
        <tr><td class="label">Tempo</td><td class="val"><?= $r['time_ms'] ?>ms</td></tr>
        <tr><td class="label">Tamanho</td><td class="<?= $r['size_bytes'] > 1000 ? 'ok' : 'bad' ?>"><?= number_format($r['size_bytes']) ?> bytes</td></tr>
        <tr><td class="label">Tem #EXTM3U</td><td class="<?= str_contains($r['has_extm3u'],'SIM') ? 'ok' : 'bad' ?>"><?= $r['has_extm3u'] ?></td></tr>
        <tr><td class="label">Tem #EXTINF</td><td class="<?= str_contains($r['has_extinf'],'SIM') ? 'ok' : 'bad' ?>"><?= $r['has_extinf'] ?></td></tr>
      </table>
      <div class="label" style="margin-top:8px; margin-bottom:4px">PREVIEW (300 chars):</div>
      <pre><?= htmlspecialchars($r['preview']) ?></pre>
    </div>
    <?php endforeach; ?>

  <?php elseif ($action === 'curl_test'): ?>
    <table>
      <?php foreach ($result as $k => $v): ?>
      <tr>
        <td class="label" style="width:160px"><?= htmlspecialchars($k) ?></td>
        <td class="<?= (str_contains((string)$v,'✓')||str_contains((string)$v,'SIM')) ? 'ok' : ((str_contains((string)$v,'✗')||str_contains((string)$v,'NÃO')||($k==='http_code'&&$v!=200)) ? 'bad' : 'val') ?>">
          <?= is_array($v) ? json_encode($v) : htmlspecialchars((string)$v) ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
    <?php if (!empty($result['preview'])): ?>
    <div class="label" style="margin-top:12px; margin-bottom:4px">PREVIEW:</div>
    <pre><?= htmlspecialchars($result['preview']) ?></pre>
    <?php endif; ?>

  <?php elseif ($action === 'parse_test'): ?>
    <?php if (!empty($result['error'])): ?>
      <p class="bad">✗ <?= htmlspecialchars($result['error']) ?></p>
    <?php else: ?>
    <table>
      <tr><td class="label">Método de fetch</td><td class="ok"><?= $result['fetch_method'] ?></td></tr>
      <tr><td class="label">Total bytes</td><td class="<?= $result['total_bytes'] > 1000 ? 'ok' : 'bad' ?>"><?= number_format($result['total_bytes']) ?></td></tr>
      <tr><td class="label">Total linhas</td><td class="val"><?= number_format($result['total_lines']) ?></td></tr>
      <tr><td class="label">Total canais</td><td class="<?= $result['total_channels'] > 0 ? 'ok' : 'bad' ?>"><?= number_format($result['total_channels']) ?></td></tr>
      <tr><td class="label">Canais AO VIVO</td><td class="<?= $result['live_channels'] > 0 ? 'ok' : 'warn' ?>"><?= number_format($result['live_channels']) ?></td></tr>
      <tr><td class="label">Filmes (VOD)</td><td class="val"><?= number_format($result['movie_channels']) ?></td></tr>
      <tr><td class="label">Séries</td><td class="val"><?= number_format($result['series_channels']) ?></td></tr>
      <tr><td class="label">Grupos únicos</td><td class="val"><?= number_format($result['unique_groups']) ?></td></tr>
    </table>
    <?php if (!empty($result['top_10_groups'])): ?>
    <div class="label" style="margin-top:12px; margin-bottom:6px">TOP 10 GRUPOS (nome → qtd canais):</div>
    <table>
      <?php foreach ($result['top_10_groups'] as $g => $c): ?>
      <tr><td class="val"><?= htmlspecialchars($g) ?></td><td class="ok"><?= $c ?></td></tr>
      <?php endforeach; ?>
    </table>
    <?php endif; ?>
    <div class="label" style="margin-top:12px; margin-bottom:4px">PRIMEIROS 500 CHARS DA LISTA:</div>
    <pre><?= htmlspecialchars($result['first_500_chars'] ?? '') ?></pre>
    <?php endif; ?>

  <?php else: ?>
    <table>
      <?php foreach ($result as $k => $v): ?>
      <tr>
        <td class="label" style="width:220px"><?= htmlspecialchars($k) ?></td>
        <td class="<?= (str_contains((string)$v,'✓')||str_contains((string)$v,'SIM')) ? 'ok' : ((str_contains((string)$v,'✗')||str_contains((string)$v,'PROBLEMA')) ? 'bad' : 'val') ?>">
          <?= is_array($v) ? implode(', ', $v) : htmlspecialchars((string)$v) ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php endif; ?>
</div>
<?php endif; ?>

<!-- INSTRUÇÕES -->
<div class="card">
  <h2>O QUE FAZER COM OS RESULTADOS</h2>
  <table>
    <tr><th>Sintoma</th><th>Causa provável</th><th>Solução</th></tr>
    <tr><td class="warn">allow_url_fopen = OFF</td><td>PHP bloqueado pelo servidor</td><td class="ok">Ativar no php.ini ou usar cURL</td></tr>
    <tr><td class="warn">size_bytes = 0 ou false</td><td>URL da fonte errada ou servidor offline</td><td class="ok">Abrir URL de teste no browser</td></tr>
    <tr><td class="warn">HTTP 401/403</td><td>Usuário/senha da fonte incorretos</td><td class="ok">Corrigir credenciais na fonte</td></tr>
    <tr><td class="warn">Tem #EXTM3U mas sem #EXTINF</td><td>Lista vazia ou formato diferente</td><td class="ok">Verificar permissões do usuário master</td></tr>
    <tr><td class="warn">cURL OK mas file_get_contents falha</td><td>allow_url_fopen desabilitado</td><td class="ok">Migrar get/player_api para cURL</td></tr>
    <tr><td class="warn">Timeout (ms muito alto)</td><td>Fonte lenta ou bloqueando o IP</td><td class="ok">Verificar firewall do servidor da fonte</td></tr>
  </table>
</div>

<p class="text-xs text-slate-600 text-center mt-8">⚠️ DELETE debug.php após resolver · GESTOR CYBER v2.0</p>
</body>
</html>
