<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/rtx/';
include 'session_check.php';

$adTypeFile = __DIR__ . '/api/ad_type.json';
// Garantir que o diretório api existe
if (!is_dir(__DIR__ . '/api')) { mkdir(__DIR__ . '/api', 0777, true); }
if (!file_exists($adTypeFile)) { file_put_contents($adTypeFile, json_encode(['adType' => 'manual'])); }

$currentAdType = json_decode(file_get_contents($adTypeFile), true)['adType'] ?? 'manual';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $newAdType = $_POST['ad_type'] ?? '';
    $allowedTypes = ['manual', 'tmdb', 'sport'];
    
    if (in_array($newAdType, $allowedTypes)) {
        file_put_contents($adTypeFile, json_encode(['adType' => $newAdType], JSON_PRETTY_PRINT));
        echo json_encode(['status' => 'success', 'message' => 'Tipo de anúncio atualizado com sucesso!']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Tipo de anúncio inválido']);
    }
    exit;
}

$page_title = "Configuração de Anúncios";

$page_content = '
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="card mb-5">
    <div class="card-header">
        <h3 class="card-title">Selecione o Tipo de Anúncio</h3>
        <div class="card-toolbar">
            <span class="badge badge-light-primary fw-bold">Configuração Ativa: ' . strtoupper($currentAdType) . '</span>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-4 mb-5">
                <div class="card card-custom ad-type-card ' . ($currentAdType === 'manual' ? 'card-active' : '') . '" data-type="manual">
                    <div class="card-body text-center p-10">
                        <div class="symbol symbol-80px mb-5">
                            <img src="' . $static_url . 'img/manual.png" onerror="this.src=\'https://cdn-icons-png.flaticon.com/512/1055/1055661.png\'" class="img-fluid" alt="Manual">
                        </div>
                        <h4 class="fw-bold mb-3">Banner Manual</h4>
                        <div class="fs-7 text-muted mb-5">Controle total sobre as imagens exibidas no app.</div>
                        <button class="btn btn-sm ' . ($currentAdType === 'manual' ? 'btn-success' : 'btn-light-primary') . ' select-ad-type" data-type="manual">
                            ' . ($currentAdType === 'manual' ? '<i class="fa fa-check me-1"></i> Ativo' : 'Selecionar') . '
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-5">
                <div class="card card-custom ad-type-card ' . ($currentAdType === 'tmdb' ? 'card-active' : '') . '" data-type="tmdb">
                    <div class="card-body text-center p-10">
                        <div class="symbol symbol-80px mb-5">
                            <img src="' . $static_url . 'img/tmdb.png" onerror="this.src=\'https://www.themoviedb.org/assets/2/v4/logos/v2/blue_square_2-d537f03683948401121598506530fd3f105bc9c1b097e1ddf16db21b15ad3f48.svg\'" class="img-fluid" alt="TMDB">
                        </div>
                        <h4 class="fw-bold mb-3">Filmes (TMDB)</h4>
                        <div class="fs-7 text-muted mb-5">Sincronização automática com as tendências mundiais.</div>
                        <button class="btn btn-sm ' . ($currentAdType === 'tmdb' ? 'btn-success' : 'btn-light-primary') . ' select-ad-type" data-type="tmdb">
                            ' . ($currentAdType === 'tmdb' ? '<i class="fa fa-check me-1"></i> Ativo' : 'Selecionar') . '
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-5">
                <div class="card card-custom ad-type-card ' . ($currentAdType === 'sport' ? 'card-active' : '') . '" data-type="sport">
                    <div class="card-body text-center p-10">
                        <div class="symbol symbol-80px mb-5">
                            <img src="' . $static_url . 'img/sport.png" onerror="this.src=\'https://cdn-icons-png.flaticon.com/512/857/857418.png\'" class="img-fluid" alt="Esportes">
                        </div>
                        <h4 class="fw-bold mb-3">Guia Esportivo</h4>
                        <div class="fs-7 text-muted mb-5">Destaque os principais eventos de futebol e lutas.</div>
                        <button class="btn btn-sm ' . ($currentAdType === 'sport' ? 'btn-success' : 'btn-light-primary') . ' select-ad-type" data-type="sport">
                            ' . ($currentAdType === 'sport' ? '<i class="fa fa-check me-1"></i> Ativo' : 'Selecionar') . '
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card bg-light-info border-info border-dashed shadow-none">
    <div class="card-body">
        <div class="d-flex align-items-center">
            <i class="ki-outline ki-information-5 fs-2hx text-info me-4"></i>
            <div class="d-flex flex-column">
                <h4 class="text-info fw-bold">Informações do Sistema</h4>
                <div class="fs-6 text-gray-700">
                    O arquivo de configuração está localizado em: <code class="bg-white px-2 py-1 rounded">' . $adTypeFile . '</code><br>
                    <span id="type-description" class="fw-semibold">
                        ' . ($currentAdType === 'manual' ? 'No modo MANUAL, o app lerá as imagens que você cadastrou na galeria.' : ($currentAdType === 'tmdb' ? 'No modo TMDB, o app buscará automaticamente os pôsteres de filmes populares.' : 'No modo SPORT, o app focará na grade de eventos esportivos do dia.')) . '
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .ad-type-card { transition: all 0.3s ease; border: 1px solid #E4E6EF; }
    .ad-type-card:hover { transform: translateY(-5px); border-color: #3699FF; box-shadow: 0 10px 20px rgba(0,0,0,0.05); }
    .card-active { border: 2px solid #50CD89 !important; background-color: #f6fffb !important; }
    .select-ad-type { min-width: 100px; }
</style>

<script>
$(document).ready(function() {
    $(".ad-type-card").click(function() {
        const adType = $(this).data("type");
        selectAdType(adType);
    });

    $(".select-ad-type").click(function(e) {
        e.stopPropagation();
        const adType = $(this).data("type");
        selectAdType(adType);
    });

    function selectAdType(adType) {
        if (adType === "' . $currentAdType . '") {
            Swal.fire({ text: "Este modo já está ativo.", icon: "info", timer: 1500, showConfirmButton: false });
            return;
        }

        Swal.fire({
            title: "Mudar para " + getAdTypeName(adType) + "?",
            text: "O aplicativo começará a exibir anúncios deste tipo imediatamente.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Sim, aplicar!",
            cancelButtonText: "Cancelar",
            customClass: { confirmButton: "btn btn-primary", cancelButton: "btn btn-light" }
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: window.location.href,
                    method: "POST",
                    data: { ad_type: adType },
                    dataType: "json",
                    success: function(response) {
                        if (response.status === "success") {
                            Swal.fire({ title: "Atualizado!", text: response.message, icon: "success", timer: 1500, showConfirmButton: false })
                            .then(() => { location.reload(); });
                        } else {
                            Swal.fire("Erro!", response.message, "error");
                        }
                    },
                    error: function() {
                        Swal.fire("Erro!", "Falha na comunicação com o servidor.", "error");
                    }
                });
            }
        });
    }

    function getAdTypeName(adType) {
        const names = { "manual": "Banner Manual", "tmdb": "Filmes Automáticos", "sport": "Guia Esportivo" };
        return names[adType] || adType;
    }
});
</script>
';

include 'includes/layout.php';
?>