<?php
include('includes/db.php'); 

// --- CONFIGURAÇÃO ---
$tmdb_api_key = 'f99aa9ae1fe7619969cc7db0938c1ae5'; 
$idioma = 'pt-BR';

function limparNome($nome) {
    // Remove termos comuns de canais para não poluir a busca
    $remover = ["FHD", "HD", "SD", "H264", "X264", "DUAL", "AUDIO", "1080P", "720P", "4K"];
    return trim(str_ireplace($remover, "", $nome));
}

function buscarTMDB($nome, $tipo, $key, $lang) {
    $nomeLimpo = urlencode(limparNome($nome));
    $url_tipo = ($tipo == 'movie') ? 'movie' : 'tv';
    $url = "https://api.themoviedb.org/3/search/$url_tipo?api_key=$key&query=$nomeLimpo&language=$lang";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// FILTRO: Ignora nomes que parecem canais (contêm HD ou FHD) e foca em descrições curtas
$sqlF = "SELECT id, name FROM movies WHERE (LENGTH(description) < 15 OR description IS NULL) AND name NOT LIKE '%HD%' AND name NOT LIKE '%FHD%'";
$sqlS = "SELECT id, name FROM series WHERE (LENGTH(description) < 15 OR description IS NULL) AND name NOT LIKE '%HD%' AND name NOT LIKE '%FHD%'";

$totalFilmes = $pdo->query($sqlF)->rowCount();
$totalSeries = $pdo->query($sqlS)->rowCount();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sync Premium - KOffice</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #0a0a0a; color: #fff; }
        .stat-box { background: #161616; border: 2px solid #007bff; border-radius: 10px; padding: 15px; text-align: center; margin-bottom: 10px; }
        .stat-number { font-size: 1.8rem; font-weight: bold; color: #00d4ff; display: block; }
        .log-terminal { background: #000; color: #00ff00; height: 350px; overflow-y: auto; padding: 15px; border-radius: 10px; font-family: monospace; border: 1px solid #333; font-size: 0.8rem; }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header bg-primary text-white text-center">
            <h5 class="mb-0">Sincronização de Filmes e Séries Real</h5>
        </div>
        <div class="card-body">
            <?php if(!isset($_GET['action'])): ?>
                <div class="row g-2 mb-3">
                    <div class="col-6"><div class="stat-box"><span class="stat-number"><?= $totalFilmes ?></span> FILMES</div></div>
                    <div class="col-6"><div class="stat-box"><span class="stat-number"><?= $totalSeries ?></span> SÉRIES</div></div>
                </div>
                <p class="small text-muted text-center italic">*Canais (HD/FHD) serão ignorados automaticamente.</p>
                <a href="?action=start" class="btn btn-primary w-100 fw-bold py-3">INICIAR FILMES E SÉRIES</a>
            <?php else: ?>
                <div class="log-terminal">
                    <?php
                    // PROCESSAR FILMES
                    $stmt = $pdo->query($sqlF);
                    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
                        $dados = buscarTMDB($r['name'], 'movie', $tmdb_api_key, $idioma);
                        if ($info = $dados['results'][0] ?? null) {
                            $upd = $pdo->prepare("UPDATE movies SET description = ?, cover_url = ? WHERE id = ?");
                            $upd->execute([$info['overview'], "https://image.tmdb.org/t/p/w500".$info['poster_path'], $r['id']]);
                            echo "> Filme: {$r['name']} [ATUALIZADO]<br>";
                        } else {
                            echo "<span style='color:gray'>> Ignorado (Não Filme): {$r['name']}</span><br>";
                        }
                        @ob_flush(); flush();
                    }
                    // PROCESSAR SÉRIES
                    $stmt = $pdo->query($sqlS);
                    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
                        $dados = buscarTMDB($r['name'], 'tv', $tmdb_api_key, $idioma);
                        if ($info = $dados['results'][0] ?? null) {
                            $upd = $pdo->prepare("UPDATE series SET description = ?, cover_url = ? WHERE id = ?");
                            $upd->execute([$info['overview'], "https://image.tmdb.org/t/p/w500".$info['poster_path'], $r['id']]);
                            echo "> Série: {$r['name']} [ATUALIZADA]<br>";
                        }
                        @ob_flush(); flush();
                    }
                    echo "<br>--- PROCESSO FINALIZADO ---";
                    ?>
                </div>
                <a href="atualizar_tmdb.php" class="btn btn-secondary w-100 mt-3">VOLTAR</a>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>
