<?php
// Configurações de Força Bruta
set_time_limit(0); 
ini_set('memory_limit', '2048M');
ini_set('display_errors', 0); // Evita lixo no JSON

session_start();
require_once '../includes/db.php';
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['user_id'])) { echo json_encode(['status'=>false, 'msg'=>'Sessão expirada. Recarregue a página.']); exit; }

$action = $_REQUEST['action'] ?? '';
// Pasta temporária com permissão total
$temp_dir = __DIR__ . '/temp';
if (!is_dir($temp_dir)) mkdir($temp_dir, 0777, true);
$temp_file = $temp_dir . '/lista_atual.m3u'; 
$tmdb_key = "f99aa9ae1fe7619969cc7db0938c1ae5";

// --- 1. BAIXAR URL (COM DESCOMPACTAÇÃO E VERIFICAÇÃO) ---
if ($action == 'download_url') {
    $url = $_POST['url'];
    if (strpos($url, 'get.php') !== false && strpos($url, 'type=') === false) { $url .= "&type=m3u_plus&output=ts"; }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Retorna na variável para analisarmos
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
    curl_setopt($ch, CURLOPT_ENCODING, ''); // <--- MÁGICA: Aceita e Descompacta GZIP sozinho
    curl_setopt($ch, CURLOPT_TIMEOUT, 300);
    
    $content = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    if ($content === false || $http_code >= 400) {
        echo json_encode(['status'=>false, 'msg'=>"Erro ao baixar: HTTP $http_code. $err"]);
        exit;
    }

    // --- VERIFICAÇÃO DE ERRO DE LOGIN ---
    $trimContent = trim($content);
    if (substr($trimContent, 0, 1) === '{') {
        $json = json_decode($content, true);
        if (isset($json['user_info']['auth']) && $json['user_info']['auth'] == 0) {
            echo json_encode(['status'=>false, 'msg'=>'ERRO DE LOGIN NA LISTA: Usuário ou Senha inválidos/expirados.']);
            exit;
        }
    }

    // --- VERIFICA SE É M3U ---
    if (strpos($content, '#EXTINF') === false) {
        // Salva os primeiros 100 caracteres para debug
        $preview = substr($content, 0, 100);
        echo json_encode(['status'=>false, 'msg'=>"O link não retornou canais. Retornou: " . htmlspecialchars($preview)]);
        exit;
    }

    // Se chegou aqui, é uma lista válida! Salva no disco DESCOMPACTADA.
    file_put_contents($temp_file, $content);
    analyzeFile($temp_file);
    exit;
}

// --- 2. UPLOAD DE ARQUIVO ---
if ($action == 'upload_file') {
    if (move_uploaded_file($_FILES['file']['tmp_name'], $temp_file)) {
        analyzeFile($temp_file);
    } else {
        echo json_encode(['status'=>false, 'msg'=>'Erro ao salvar upload.']);
    }
    exit;
}

// --- FUNÇÃO DE ANÁLISE ---
function analyzeFile($file) {
    if(!file_exists($file)) { echo json_encode(['status'=>false, 'msg'=>'Arquivo perdido.']); return; }

    $handle = fopen($file, "r");
    $categories = [];
    
    while (($line = fgets($handle)) !== false) {
        // Parser simplificado e rápido
        if (strpos($line, '#EXTINF') !== false) {
            $catName = "Geral";
            if (preg_match('/group-title=["\']?([^"\',]+)/i', $line, $m)) $catName = $m[1];
            elseif (preg_match('/group-title=([^ ,]+)/i', $line, $m)) $catName = $m[1];

            $catName = trim($catName);
            
            // Detecta Tipo
            $type = 'channel';
            $up = strtoupper($catName);
            if (strpos($up, 'FILME')!==false || strpos($up, 'MOVIE')!==false || strpos($up, 'VOD')!==false || strpos($up, 'CINEMA')!==false || strpos($up, '4K')!==false) $type = 'movie';
            elseif (strpos($up, 'SERIE')!==false || strpos($up, 'SÉRIE')!==false || strpos($up, 'SEASON')!==false || strpos($up, 'ANIME')!==false || strpos($up, 'NOVELA')!==false) $type = 'series';

            $key = $type.'|'.$catName;
            if(!isset($categories[$key])) {
                $categories[$key] = ['name'=>$catName, 'type'=>$type, 'count'=>0, 'id'=>md5($key)];
            }
            $categories[$key]['count']++;
        }
    }
    fclose($handle);
    
    ksort($categories);
    echo json_encode(['status'=>true, 'msg'=>'Lista analisada com sucesso!', 'categories'=>array_values($categories)]);
}

// --- 3. PROCESSAR IMPORTAÇÃO ---
if ($action == 'import_process') {
    $selected = json_decode($_POST['categories'], true);
    if (!$selected) { echo json_encode(['status'=>false, 'msg'=>'Nenhuma categoria selecionada']); exit; }

    $allowedMap = [];
    foreach($selected as $s) { $allowedMap[$s['type'].'|'.$s['name']] = true; }

    $handle = fopen($temp_file, "r");
    $count = 0;
    
    global $pdo;
    $sql_chan = $pdo->prepare("INSERT INTO channels (name, stream_url, logo_url, category_id) VALUES (?,?,?,?)");
    $sql_mov  = $pdo->prepare("INSERT INTO movies (name, stream_url, cover_url, description, category_id) VALUES (?,?,?,?,?)");
    // Séries
    $sql_ser_chk = $pdo->prepare("SELECT id FROM series WHERE name LIKE ? LIMIT 1");
    $sql_ser_ins = $pdo->prepare("INSERT INTO series (name, cover_url, description, category_id) VALUES (?,?,?,?)");
    $sql_sea_chk = $pdo->prepare("SELECT id FROM seasons WHERE series_id=? AND name=? LIMIT 1");
    $sql_sea_ins = $pdo->prepare("INSERT INTO seasons (series_id, name) VALUES (?,?)");
    $sql_ep_ins  = $pdo->prepare("INSERT INTO episodes (season_id, name, stream_url, cover_url) VALUES (?,?,?,?)");

    $catIds = [];
    $currentItem = [];
    
    while (($line = fgets($handle)) !== false) {
        $line = trim($line);
        if (strpos($line, '#EXTINF') === 0) {
            $cat = "Geral";
            if (preg_match('/group-title=["\']?([^"\',]+)/i', $line, $m)) $cat = $m[1];
            elseif (preg_match('/group-title=([^ ,]+)/i', $line, $m)) $cat = $m[1];
            
            $logo = "";
            if (preg_match('/tvg-logo=["\']?([^"\']+)/i', $line, $m)) $logo = $m[1];
            
            $parts = explode(',', $line);
            $name = end($parts);
            
            $type = 'channel';
            $up = strtoupper($cat);
            if (strpos($up, 'FILME')!==false || strpos($up, 'MOVIE')!==false || strpos($up, 'VOD')!==false) $type = 'movie';
            elseif (strpos($up, 'SERIE')!==false || strpos($up, 'SÉRIE')!==false || strpos($up, 'SEASON')!==false) $type = 'series';

            if (isset($allowedMap[$type.'|'.$cat])) {
                $currentItem = ['name'=>trim($name), 'logo'=>$logo, 'cat'=>$cat, 'type'=>$type];
            } else {
                $currentItem = [];
            }
        } 
        elseif (strpos($line, 'http') === 0 && !empty($currentItem)) {
            $url = $line;
            $catKey = $currentItem['type'].'_'.$currentItem['cat'];
            
            if(!isset($catIds[$catKey])) {
                $stmt = $pdo->prepare("SELECT id FROM categories WHERE name=? AND type=?");
                $stmt->execute([$currentItem['cat'], $currentItem['type']]);
                $cid = $stmt->fetchColumn();
                if(!$cid) {
                    $pdo->prepare("INSERT INTO categories (name,type) VALUES (?,?)")->execute([$currentItem['cat'], $currentItem['type']]);
                    $cid = $pdo->lastInsertId();
                }
                $catIds[$catKey] = $cid;
            }
            $cid = $catIds[$catKey];

            if($currentItem['type'] == 'channel') {
                $sql_chan->execute([$currentItem['name'], $url, $currentItem['logo'], $cid]);
            }
            elseif($currentItem['type'] == 'movie') {
                $sql_mov->execute([$currentItem['name'], $url, $currentItem['logo'], 'Importado', $cid]);
            }
            elseif($currentItem['type'] == 'series') {
                $s_name = $currentItem['name'];
                $s_num = 1;
                if (preg_match('/(.*?)\s+(?:S|T)(\d+)\s*(?:E|EP|x)(\d+)/i', $s_name, $m)) { 
                    $s_name = trim($m[1]); $s_num = (int)$m[2]; 
                } else { 
                    $s_name = preg_replace('/ S\d+.*| E\d+.*|\d+x\d+.*/i', '', $s_name); 
                }

                $sql_ser_chk->execute([$s_name]); $sid = $sql_ser_chk->fetchColumn();
                if(!$sid) {
                    $sql_ser_ins->execute([$s_name, $currentItem['logo'], 'Importado', $cid]);
                    $sid = $pdo->lastInsertId();
                }
                
                $sea_name = "Temporada $s_num";
                $sql_sea_chk->execute([$sid, $sea_name]); $seaid = $sql_sea_chk->fetchColumn();
                if(!$seaid) {
                    $sql_sea_ins->execute([$sid, $sea_name]);
                    $seaid = $pdo->lastInsertId();
                }
                $sql_ep_ins->execute([$seaid, $currentItem['name'], $url, $currentItem['logo']]);
            }

            $count++;
            $currentItem = [];
        }
    }
    fclose($handle);
    echo json_encode(['status'=>true, 'total'=>$count]);
}
?>
