<?php
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
include ('includes/header.php');

// Configurações
$config_file = 'api/fundoads.php';
$base_file = 'bg.php';

// Verificar se o arquivo de configuração existe
if (!file_exists($config_file)) {
    die("<div class='alert alert-danger'>Arquivo de configuração não encontrado: $config_file</div>");
}

// Processar a mudança para automático
if (isset($_GET['enable_auto'])) {
    $config_content = <<<EOD
<?php
\$auto_background = true;
\$tmdb_api_key = 'SUA_CHAVE_DE_API';
\$tmdb_language = 'pt-BR';

function getTmdbBackground() {
    global \$tmdb_api_key, \$tmdb_language;
    
    try {
        // Buscar filmes populares
        \$url = "https://api.themoviedb.org/3/movie/popular?api_key={\$tmdb_api_key}&language={\$tmdb_language}";
        \$response = @file_get_contents(\$url);
        
        if (\$response === false) {
            throw new Exception("Falha ao acessar API TMDB");
        }
        
        \$data = json_decode(\$response, true);
        
        if (isset(\$data['results']) && count(\$data['results']) > 0) {
            \$movies = \$data['results'];
            \$randomMovie = \$movies[array_rand(\$movies)];
            
            if (!empty(\$randomMovie['backdrop_path'])) {
                return 'https://image.tmdb.org/t/p/original' . \$randomMovie['backdrop_path'];
            }
        }
    } catch (Exception \$e) {
        error_log("Erro TMDB: " . \$e->getMessage());
    }
    
    // Fallback padrão
    return 'https://image.tmdb.org/t/p/original/wwemzKWzjKYJFfCeiB57q3r4Bcm.png';
}
?>
EOD;

    file_put_contents($config_file, $config_content);
    $_SESSION['alert'] = ['type' => 'success', 'message' => 'Modo automático ativado! Fundos serão buscados do TMDB.'];
    header("Location: $base_file");
    exit;
}

// Processar a mudança para manual
if (isset($_GET['disable_auto'])) {
    $config_content = "<?php\n\$auto_background = false;\n?>";
    file_put_contents($config_file, $config_content);
    $_SESSION['alert'] = ['type' => 'success', 'message' => 'Modo manual ativado! Fundos serão exibidos do banco de dados.'];
    header("Location: $base_file");
    exit;
}

// Verificar o estado atual
$auto_background = false;
if (file_exists($config_file)) {
    include($config_file);
}
?>

<style>
:root {
    --primary-blue: #1a237e;
    --dark-blue: #0d1541;
    --accent-blue: #3d5afe;
    --light-blue: #e8eaf6;
    --danger-red: #dc3545;
    --success-green: #28a745;
    --warning-orange: #fd7e14;
    --white: #ffffff;
    --light-gray: #f8f9fa;
    --medium-gray: #e9ecef;
    --dark-gray: #6c757d;
    --black: #212529;
}

.card {
    border: none;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    margin-bottom: 25px;
    background-color: var(--white);
    border: 1px solid var(--light-blue);
}

.card-header {
    border-radius: 10px 10px 0 0 !important;
    padding: 15px 20px;
    font-weight: 600;
    color: var(--white);
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%) !important;
}

.card-body {
    padding: 25px;
    background-color: var(--white);
}

.btn {
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.9rem;
}

.btn-primary {
    background-color: var(--primary-blue);
    border-color: var(--primary-blue);
    color: var(--white);
}

.btn-primary:hover {
    background-color: var(--dark-blue);
    border-color: var(--dark-blue);
}

.btn-success {
    background-color: var(--success-green);
    border-color: var(--success-green);
    color: var(--white);
}

.btn-success:hover {
    background-color: #218838;
    border-color: #1e7e34;
}

.mode-description {
    background-color: var(--light-blue);
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    border-left: 4px solid var(--accent-blue);
    height: 100%;
}

.mode-icon {
    font-size: 2rem;
    margin-bottom: 15px;
    color: var(--accent-blue);
}

@media (max-width: 768px) {
    .card-body {
        padding: 20px;
    }
    
    .btn {
        width: 100%;
        margin-bottom: 10px;
    }
}
</style>

<div class="container-fluid py-4">
    <?php if (isset($_SESSION['alert'])): ?>
        <div class="alert alert-<?= $_SESSION['alert']['type'] ?> alert-dismissible fade show" role="alert">
            <i class="fas <?= $_SESSION['alert']['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?> me-2"></i>
            <?= $_SESSION['alert']['message'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-8 mx-auto">
            <div class="card shadow-sm">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-sync-alt me-2"></i>Modo de Fundo</h4>
                        <a href="<?= $base_file ?>" class="btn btn-light">
                            <i class="fas fa-arrow-left me-1"></i> Voltar
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-4">
                            <div class="mode-description text-center">
                                <div class="mode-icon">
                                    <i class="fas fa-images"></i>
                                </div>
                                <h5>Modo Manual</h5>
                                <p class="text-muted">Você gerencia os fundos manualmente através do sistema de upload.</p>
                                <?php if ($auto_background): ?>
                                    <a href="?disable_auto" class="btn btn-primary mt-3">
                                        <i class="fas fa-toggle-off me-2"></i> Ativar Modo Manual
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-secondary mt-3" disabled>
                                        <i class="fas fa-check-circle me-2"></i> Modo Atual
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="col-md-6 mb-4">
                            <div class="mode-description text-center">
                                <div class="mode-icon">
                                    <i class="fas fa-film"></i>
                                </div>
                                <h5>Modo Automático (TMDB)</h5>
                                <p class="text-muted">Os fundos são obtidos automaticamente da API do TMDB.</p>
                                <?php if (!$auto_background): ?>
                                    <a href="?enable_auto" class="btn btn-success mt-3">
                                        <i class="fas fa-toggle-on me-2"></i> Ativar Modo Automático
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-secondary mt-3" disabled>
                                        <i class="fas fa-check-circle me-2"></i> Modo Atual
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Como funciona:</strong> No modo automático, o sistema irá buscar imagens de fundo diretamente da API do TMDB. Certifique-se de configurar sua chave de API no arquivo <code>/api/fundoads.php</code>.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
setTimeout(function() {
    document.querySelectorAll('.alert').forEach(function(alert) {
        var closeButton = alert.querySelector('.btn-close');
        if (closeButton) {
            closeButton.click();
        }
    });
}, 5000);
</script>

<?php 
include ('includes/footer.php');
?>