<?php
// ARQUIVO: atualizar_tmdb.php (Com Sidebar e Responsivo)
// LOCAL: Pasta Raiz (public_html/atualizar_tmdb.php)

include('includes/db.php'); 
session_start();

// Verifica login (adicionei caso não tenha, pois é importante)
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }

// --- 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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">

    <style>
        body { background: #1a1c23; color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        
        .card { background-color: #232730; border: 1px solid #333; }
        .stat-box { background: #1a1c23; border: 1px 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; }

        /* RESPONSIVIDADE DO LAYOUT (IGUAL AO CLIENTS.PHP) */
        @media (min-width: 992px) {
            #sidebar { display: block !important; width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .right-column { margin-left: 240px; width: calc(100% - 240px); padding: 0; }
            .btn-voltar-mobile { display: none; }
        }
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { margin-left: 0 !important; width: 100% !important; padding: 0; }
            .btn-voltar-mobile { display: inline-block; margin-right: 10px; color: #fff; font-size: 1.2rem; }
        }
        
        .page-header { padding: 15px 20px; border-bottom: 1px solid #333; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; background-color: #1a1c23; }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <div class="page-header sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h4 class="mb-0 fw-bold text-white"><i class="fa fa-sync text-primary me-2"></i> Sincronização TMDB</h4>
                </div>
                <div>
                    <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block">Voltar</a>
                </div>
            </div>

            <div class="container px-4 pb-5">
                
                <div class="card 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>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>