<?php
/*
desenvolvedor: luciano donizeti
mania de script: www.maniadescript.com.br
whatsapp 43998240911
*/

session_start();
require_once __DIR__ . '/db/configdb.php';
require_once __DIR__ . '/admin_permissions_helper.php';
if (!isset($_SESSION["usuario"]) || !isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();
}

$user_id = intval($_SESSION["user_id"]);
try {
    $permPdo = adminPermPdo();
    adminPermEnsureSchema($permPdo);
    if (!adminPermPode($permPdo, $user_id, 'alterar_background')) {
        adminPermRenderAcessoNegado('Acesso negado', 'Este usuário não tem permissão para trocar o background/fundo.');
        exit();
    }
} catch (Exception $e) {
    error_log(date('Y-m-d H:i:s') . ' - Erro ao validar permissão de background: ' . $e->getMessage() . "
", 3, 'session_debug.log');
    die('Erro ao validar permissões. Tente novamente.');
}
$is_admin = isset($_SESSION["nivel"]) && (int)$_SESSION["nivel"] === 1;
$background_types = [
    'fundo_banner_1' => ['name' => 'Fundo Banner 1', 'fixed_filename' => 'background_banner_1'],
    'fundo_banner_2' => ['name' => 'Fundo Banner 2', 'fixed_filename' => 'background_banner_2'],
    'fundo_banner_3' => ['name' => 'Fundo Banner 3', 'fixed_filename' => 'background_banner_3'],
    'fundo_banner_4' => ['name' => 'Fundo Banner 4', 'fixed_filename' => 'background_banner_4'],
    'fundo_banner_5' => ['name' => 'Fundo Banner 5', 'fixed_filename' => 'background_banner_5'],
];

$current_bg_key = $_GET['tipo'] ?? array_key_first($background_types);
if (!array_key_exists($current_bg_key, $background_types)) {
    header("Location: background.php");
    exit();
}

$current_bg_config = $background_types[$current_bg_key];
$user_json_path = "./api/fzstore/user_{$user_id}/{$current_bg_config['fixed_filename']}.json";
$global_json_path = "./api/fzstore/{$current_bg_config['fixed_filename']}.json";
$successMessage = '';
$errorMessage = '';
$redirect_bg_key = $current_bg_key;


function background_update_json($path, $imageName, $uploadType) {
    $json_dir = dirname($path);
    if (!is_dir($json_dir)) mkdir($json_dir, 0755, true);
    $jsonData = json_encode([[
        "ImageName" => $imageName,
        "Upload_type" => $uploadType,
        "UpdatedAt" => date(DATE_ATOM)
    ]], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    return file_put_contents($path, $jsonData) ? true : false;
}

function background_normalize_remote_url($url) {
    $url = html_entity_decode(trim((string)$url), ENT_QUOTES | ENT_HTML5, 'UTF-8');
    if (strpos($url, '//') === 0) { $url = 'https:' . $url; }
    return $url;
}

function background_url_origin($url) {
    $parts = @parse_url($url);
    if (!is_array($parts) || empty($parts['scheme']) || empty($parts['host'])) return '';
    return $parts['scheme'] . '://' . $parts['host'] . '/';
}

function background_extract_meta_image($html) {
    $html = (string)$html;
    $patterns = [
        '/<meta[^>]+property=["\']og:image["\'][^>]+content=["\']([^"\']+)["\']/i',
        '/<meta[^>]+content=["\']([^"\']+)["\'][^>]+property=["\']og:image["\']/i',
        '/<meta[^>]+name=["\']twitter:image["\'][^>]+content=["\']([^"\']+)["\']/i',
        '/<img[^>]+src=["\']([^"\']+)["\']/i',
    ];
    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $html, $m)) {
            $candidate = background_normalize_remote_url($m[1]);
            if (filter_var($candidate, FILTER_VALIDATE_URL)) return $candidate;
        }
    }
    return '';
}

function background_fetch_remote_image($url, $referer = '', &$error = null, $depth = 0) {
    $error = '';
    $url = background_normalize_remote_url($url);
    if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $url)) {
        $error = 'URL inválida.';
        return false;
    }
    if ($depth > 2) {
        $error = 'Redirecionamento de imagem excedido.';
        return false;
    }

    $referer = $referer ?: background_url_origin($url);
    $headers = [
        'Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
        'Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7',
        'Cache-Control: no-cache',
    ];

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 8,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 35,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_ENCODING => '',
        ]);
        if ($referer !== '') {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
        $content = curl_exec($ch);
        $curlError = curl_error($ch);
        $http = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $type = strtolower((string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
        $finalUrl = (string)curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        curl_close($ch);

        if ($content === false || $content === '') {
            $error = 'Falha no download' . ($curlError ? ': ' . $curlError : '.');
            return false;
        }
        if ($http >= 400) {
            $error = 'Servidor da imagem retornou HTTP ' . $http . '.';
            return false;
        }
        if (strlen($content) < 500) {
            $error = 'Arquivo recebido muito pequeno para ser imagem.';
            return false;
        }
        if (strlen($content) > 35 * 1024 * 1024) {
            $error = 'Imagem maior que 35 MB.';
            return false;
        }

        if (stripos($type, 'text/html') !== false || preg_match('/^\s*</', substr($content, 0, 80))) {
            $metaImage = background_extract_meta_image($content);
            if ($metaImage !== '') {
                return background_fetch_remote_image($metaImage, $finalUrl ?: $url, $error, $depth + 1);
            }
            $error = 'O link abriu uma página HTML, não um arquivo de imagem.';
            return false;
        }

        return [
            'content' => $content,
            'content_type' => $type,
            'final_url' => $finalUrl ?: $url,
        ];
    }

    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => 35,
            'ignore_errors' => true,
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36\r\n" .
                        "Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8\r\n" .
                        "Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7\r\n" .
                        ($referer ? "Referer: {$referer}\r\n" : ''),
        ],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
    ]);
    $content = @file_get_contents($url, false, $context);
    if ($content === false || strlen($content) < 500 || strlen($content) > 35 * 1024 * 1024) {
        $error = 'Falha ao baixar com file_get_contents.';
        return false;
    }
    if (preg_match('/^\s*</', substr($content, 0, 80))) {
        $metaImage = background_extract_meta_image($content);
        if ($metaImage !== '') {
            return background_fetch_remote_image($metaImage, $url, $error, $depth + 1);
        }
        $error = 'O link abriu uma página HTML, não uma imagem.';
        return false;
    }
    return ['content' => $content, 'content_type' => '', 'final_url' => $url];
}

function background_image_resource_from_content($content, $contentType = '', $sourceUrl = '') {
    $img = @imagecreatefromstring($content);
    if ($img) return $img;

    $ext = strtolower(pathinfo(parse_url((string)$sourceUrl, PHP_URL_PATH) ?: '', PATHINFO_EXTENSION));
    $type = strtolower((string)$contentType);

    if ((strpos($type, 'webp') !== false || $ext === 'webp') && function_exists('imagecreatefromwebp')) {
        $tmp = tempnam(sys_get_temp_dir(), 'bg_webp_');
        if ($tmp && @file_put_contents($tmp, $content) !== false) {
            $img = @imagecreatefromwebp($tmp);
            @unlink($tmp);
            if ($img) return $img;
        }
    }

    if (class_exists('Imagick')) {
        try {
            $imagick = new Imagick();
            $imagick->readImageBlob($content);
            if (method_exists($imagick, 'setIteratorIndex')) { @$imagick->setIteratorIndex(0); }
            $imagick->setImageFormat('png');
            $png = $imagick->getImagesBlob();
            $imagick->clear();
            $imagick->destroy();
            $img = @imagecreatefromstring($png);
            if ($img) return $img;
        } catch (Throwable $e) {
            // Continua para falha controlada.
        }
    }

    return false;
}

function background_save_remote_as_local_png($imageUrl, $destinationPath, array $fallbackUrls = []) {
    $candidates = array_values(array_unique(array_filter(array_merge([$imageUrl], $fallbackUrls), function($u) {
        return filter_var(background_normalize_remote_url($u), FILTER_VALIDATE_URL);
    })));

    $lastError = '';
    foreach ($candidates as $candidate) {
        $candidate = background_normalize_remote_url($candidate);
        $download = background_fetch_remote_image($candidate, '', $lastError);
        if ($download === false) {
            @error_log('[background] Falha ao baixar candidato: ' . $candidate . ' | ' . $lastError);
            continue;
        }

        $image = background_image_resource_from_content($download['content'], $download['content_type'] ?? '', $download['final_url'] ?? $candidate);
        if (!$image) {
            $lastError = 'Formato de imagem não suportado pelo servidor PHP/GD.';
            @error_log('[background] Imagem baixada, mas GD/Imagick não abriu: ' . $candidate);
            continue;
        }

        $dir = dirname($destinationPath);
        if (!is_dir($dir)) mkdir($dir, 0755, true);

        imagealphablending($image, true);
        imagesavealpha($image, true);
        $ok = imagepng($image, $destinationPath, 8);
        imagedestroy($image);
        if ($ok) {
            @chmod($destinationPath, 0644);
            return true;
        }
        $lastError = 'Falha ao gravar PNG no servidor.';
    }

    @error_log('[background] Nenhum candidato de imagem pôde ser salvo. Último erro: ' . $lastError);
    return false;
}

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $posted_bg_type = $_POST['bg_type'] ?? null;
    if ($posted_bg_type && isset($background_types[$posted_bg_type])) {
        $redirect_bg_key = $posted_bg_type;
        $fixed_filename_base = $background_types[$posted_bg_type]['fixed_filename'];
        $user_json_path_to_update = "./api/fzstore/user_{$user_id}/{$fixed_filename_base}.json";
        $global_json_path_to_update = "./api/fzstore/{$fixed_filename_base}.json";
        $user_upload_dir = "./fzstore/Img/user_{$user_id}/";
        $global_upload_dir = "./fzstore/Img/";

        if (isset($_POST['upload']) && isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $file = $_FILES['image'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (in_array($file['type'], $allowedTypes)) {
                if (!is_dir($user_upload_dir)) mkdir($user_upload_dir, 0755, true);
                if ($is_admin && !is_dir($global_upload_dir)) mkdir($global_upload_dir, 0755, true);
                
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $fileName = $fixed_filename_base . '_' . $user_id . '.' . $extension;
                $user_destination = $user_upload_dir . $fileName;
                $global_fileName = $fixed_filename_base . '.' . $extension;
                $global_destination = $global_upload_dir . $global_fileName;

                if (move_uploaded_file($file['tmp_name'], $user_destination)) {
                    // Salva sempre no espaço próprio do usuário. Apenas o admin atualiza o padrão global.
                    $user_success = background_update_json($user_json_path_to_update, "../fzstore/Img/user_{$user_id}/{$fileName}", "by_file");
                    $global_success = true;
                    if ($is_admin) {
                        @copy($user_destination, $global_destination);
                        $global_success = background_update_json($global_json_path_to_update, "../fzstore/Img/{$global_fileName}", "by_file");
                    }
                    if ($user_success && $global_success) {
                        $successMessage = "Plano de fundo atualizado com sucesso!";
                    } else {
                        $errorMessage = "Erro ao salvar as informações da imagem.";
                    }
                } else {
                    $errorMessage = 'Falha ao mover o arquivo enviado.';
                }
            } else {
                $errorMessage = 'Tipo de arquivo inválido.';
            }
        } elseif (isset($_POST['internet-submit'])) {
            $imageUrl = background_normalize_remote_url($_POST['image-url'] ?? '');
            $thumbUrl = background_normalize_remote_url($_POST['image-thumb-url'] ?? '');
            $fallbackUrls = [];
            if (filter_var($thumbUrl, FILTER_VALIDATE_URL) && $thumbUrl !== $imageUrl) {
                $fallbackUrls[] = $thumbUrl;
            }

            if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
                if (!is_dir($user_upload_dir)) mkdir($user_upload_dir, 0755, true);
                if ($is_admin && !is_dir($global_upload_dir)) mkdir($global_upload_dir, 0755, true);

                $fileName = $fixed_filename_base . '_' . $user_id . '_internet.png';
                $user_destination = $user_upload_dir . $fileName;
                $global_fileName = $fixed_filename_base . '.png';
                $global_destination = $global_upload_dir . $global_fileName;

                if (background_save_remote_as_local_png($imageUrl, $user_destination, $fallbackUrls)) {
                    $user_success = background_update_json($user_json_path_to_update, "../fzstore/Img/user_{$user_id}/{$fileName}", "by_file");
                    $global_success = true;
                    if ($is_admin) {
                        @copy($user_destination, $global_destination);
                        $global_success = background_update_json($global_json_path_to_update, "../fzstore/Img/{$global_fileName}", "by_file");
                    }
                    if ($user_success && $global_success) {
                        $successMessage = "Imagem da internet salva localmente com sucesso!";
                    } else {
                        $errorMessage = "A imagem foi baixada, mas ocorreu erro ao salvar a configuração.";
                    }
                } else {
                    $errorMessage = 'Não foi possível salvar essa imagem. O sistema tentou a imagem original e a miniatura da busca. Tente outra imagem da busca ou cole uma URL direta de JPG/PNG/WebP.';
                }
            } else {
                $errorMessage = 'Selecione uma imagem válida da busca na internet.';
            }
        } elseif (isset($_POST['url-submit'])) {
            $imageUrl = filter_var($_POST['image-url'], FILTER_SANITIZE_URL);
            if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
                $user_success = background_update_json($user_json_path_to_update, $imageUrl, "by_url");
                $global_success = $is_admin ? background_update_json($global_json_path_to_update, $imageUrl, "by_url") : true;
                if ($user_success && $global_success) {
                    $successMessage = "Plano de fundo atualizado com sucesso!";
                } else {
                    $errorMessage = "Erro ao salvar as informações da imagem.";
                }
            } else {
                $errorMessage = 'A URL fornecida não é válida.';
            }
        }
    } else {
        $errorMessage = "Tipo de plano de fundo inválido enviado.";
    }
}

$methord = "Não Definido";
$imageFilex = '';
$showPreview = false;
if (file_exists($user_json_path)) {
    $jsonDatax = json_decode(file_get_contents($user_json_path), true);
    if (isset($jsonDatax) && is_array($jsonDatax) && !empty($jsonDatax) && isset($jsonDatax[0])) {
        $filenamex = $jsonDatax[0]['ImageName'] ?? '';
        $uploadmethord = $jsonDatax[0]['Upload_type'] ?? 'default';
        if ($uploadmethord == "by_file" && !empty($filenamex)) {
            $imageFilex = str_replace('../', './', $filenamex);
            if (file_exists($imageFilex)) {
                $methord = "Arquivo Enviado";
                $showPreview = true;
            }
        } elseif ($uploadmethord == "by_url" && filter_var($filenamex, FILTER_VALIDATE_URL)) {
            $imageFilex = $filenamex;
            $methord = "URL Externa";
            $showPreview = true;
        }
    }
}

$pageTitle = "Gerenciar Fundos";
include "includes/header.php";
?>

<style>
    .two-column-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 30px;
    }
    @media (min-width: 768px) {
        .two-column-grid {
            grid-template-columns: 1fr 1fr;
        }
    }
    .column-box {
        background: rgba(0,0,0,0.15);
        padding: 25px;
        border-radius: 10px;
    }
    .column-box h3 {
        color: var(--accent-color);
        margin-bottom: 20px;
        font-weight: 600;
        border-bottom: 1px solid var(--accent-color);
        padding-bottom: 10px;
    }
    .form-group { margin-bottom: 20px; }
    .form-group label { display: block; color: var(--text-secondary); margin-bottom: 8px; font-weight: 500; }
    .form-select, .form-control {
        width: 100%; padding: 12px 15px; background-color: var(--page-bg);
        border: 1px solid rgba(255,255,255,0.2); border-radius: 8px; color: var(--text-color);
    }
    .form-select:focus, .form-control:focus { outline: none; border-color: var(--accent-color); }
    
    .preview-area {
        width: 100%;
        height: 200px;
        margin-top: 15px;
        background-color: var(--page-bg);
        border: 2px dashed rgba(255,255,255,0.2);
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        position: relative;
    }
    .preview-area img { 
        width: 100%;
        height: 100%;
        object-fit: cover;
        object-position: center;
    }
    .preview-area .no-image {
        color: var(--text-muted);
        font-size: 0.9rem;
    }
    .current-method-info { text-align: center; color: var(--text-muted); font-size: 0.9rem; margin-top: 15px; }
    .current-method-info strong { color: var(--accent-color); }
    
    .method-switcher { display: flex; border-radius: 8px; overflow: hidden; }
    .method-switcher input[type="radio"] { display: none; }
    .method-switcher label {
        flex: 1; text-align: center; padding: 12px; cursor: pointer;
        background-color: rgba(0,0,0,0.2); color: var(--text-muted);
        transition: all 0.3s; font-weight: 500;
    }
    .method-switcher input[type="radio"]:checked + label { background-color: var(--accent-color); color: #fff; }

    .submit-btn {
        width: 100%; padding: 12px; font-size: 1rem; font-weight: 600; color: #fff;
        border: none; border-radius: 8px; cursor: pointer; transition: all 0.3s;
        background-color: var(--success-color);
    }
    .submit-btn:hover { background-color: #218838; transform: translateY(-2px); }

    .search-help { color: var(--text-muted); font-size: 0.88rem; margin-top: -8px; margin-bottom: 14px; line-height: 1.45; }
    .search-row { display: flex; gap: 10px; align-items: stretch; }
    .search-row .form-control { flex: 1; }
    .search-btn {
        padding: 0 16px; border: none; border-radius: 8px; cursor: pointer; font-weight: 700;
        color: #fff; background-color: var(--accent-color); white-space: nowrap;
    }
    .search-btn:disabled, .submit-btn:disabled { opacity: .55; cursor: not-allowed; transform: none; }
    .internet-results {
        display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; margin: 14px 0;
    }
    .internet-card {
        border: 2px solid transparent; border-radius: 10px; overflow: hidden; background: rgba(0,0,0,.22);
        cursor: pointer; transition: all .2s ease; min-height: 150px;
    }
    .internet-card:hover { transform: translateY(-2px); border-color: rgba(255,255,255,.3); }
    .internet-card.selected { border-color: var(--success-color); box-shadow: 0 0 0 2px rgba(40, 167, 69, .25); }
    .internet-card img { width: 100%; height: 105px; object-fit: cover; display: block; background: rgba(255,255,255,.07); }
    .internet-card span { display: block; color: var(--text-color); font-size: .78rem; line-height: 1.25; padding: 7px; min-height: 36px; }
    .search-status { color: var(--text-muted); font-size: .9rem; margin: 10px 0; min-height: 18px; }
    .selected-url-box { display: none; margin-top: 10px; font-size: .82rem; color: var(--text-muted); word-break: break-all; }
    .selected-url-box strong { color: var(--accent-color); }
</style>

<div class="page-header">
    <h1><i class="fas fa-photo-video" style="color: var(--accent-color);"></i> Gerenciar Planos de Fundo</h1>
</div>

<div class="content-card">
    <div class="two-column-grid">
        <div class="column-box">
            <h3>1. Selecione e Visualize</h3>
            <div class="form-group">
                <label for="bg-selector">Plano de Fundo para Editar:</label>
                <select id="bg-selector" class="form-select">
                    <?php foreach ($background_types as $key => $details): ?>
                        <option value="<?= $key ?>" <?= ($key == $current_bg_key) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($details['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <label>Prévia Atual:</label>
            <div class="preview-area">
                <?php if ($showPreview): ?>
                    <img src="<?= $imageFilex ?>?v=<?= time() ?>" alt="Preview do Fundo">
                <?php else: ?>
                    <span class="no-image">Nenhum fundo definido ou imagem não encontrada.</span>
                <?php endif; ?>
            </div>
            <p class="current-method-info">Método Atual: <strong><?= $methord ?></strong></p>
            <?php if ($showPreview && $methord == "Arquivo Enviado"): ?>
                <p class="current-method-info">Caminho: <strong><?= htmlspecialchars($imageFilex) ?></strong></p>
            <?php endif; ?>
        </div>

        <div class="column-box">
            <h3>2. Altere a Imagem</h3>
            <div class="method-switcher">
                <input type="radio" id="upload-radio" name="upload-type" value="file" checked>
                <label for="upload-radio"><i class="fas fa-upload"></i> Enviar Arquivo</label>
                
                <input type="radio" id="url-radio" name="upload-type" value="url">
                <label for="url-radio"><i class="fas fa-link"></i> Usar URL</label>

                <input type="radio" id="internet-radio" name="upload-type" value="internet">
                <label for="internet-radio"><i class="fas fa-search"></i> Buscar Internet</label>
            </div>
            <div class="forms-container" style="margin-top: 20px;">
                <form method="post" enctype="multipart/form-data" id="upload-form" class="method-form" action="background.php?tipo=<?= $current_bg_key ?>">
                    <input type="hidden" name="bg_type" value="<?= $current_bg_key ?>">
                    <div class="form-group">
                        <label for="image">Selecione uma imagem (PNG, JPG, GIF, WebP):</label>
                        <input class="form-control" type="file" name="image" id="image" accept="image/*">
                    </div>
                    <button class="submit-btn" type="submit" name="upload"><i class="fas fa-paper-plane"></i> Enviar</button>
                </form>

                <form method="post" id="url-form" class="method-form" style="display: none;" action="background.php?tipo=<?= $current_bg_key ?>">
                    <input type="hidden" name="bg_type" value="<?= $current_bg_key ?>">
                    <div class="form-group">
                        <label for="image-url">Insira a URL da imagem:</label>
                        <input class="form-control" type="text" name="image-url" id="image-url" placeholder="https://...">
                    </div>
                    <button class="submit-btn" type="submit" name="url-submit"><i class="fas fa-save"></i> Salvar URL</button>
                </form>


                <form method="post" id="internet-form" class="method-form" style="display: none;" action="background.php?tipo=<?= $current_bg_key ?>">
                    <input type="hidden" name="bg_type" value="<?= $current_bg_key ?>">
                    <input type="hidden" name="image-url" id="internet-selected-url" value="">
                    <input type="hidden" name="image-thumb-url" id="internet-selected-thumb" value="">
                    <div class="form-group">
                        <label for="internet-query">Buscar imagem por título na internet:</label>
                        <div class="search-row">
                            <input class="form-control" type="text" id="internet-query" value="<?= htmlspecialchars($current_bg_config['name'] . ' futebol estádio') ?>" placeholder="Ex: futebol estádio, Champions League, Brasileirão, arena lotada">
                            <button class="search-btn" type="button" id="internet-search-btn"><i class="fas fa-search"></i> Buscar</button>
                        </div>
                        <p class="search-help">Você pode alterar o título/termo da busca, escolher uma imagem e salvar. A imagem escolhida será baixada para o sistema, evitando depender do link externo depois.</p>
                    </div>
                    <div id="internet-search-status" class="search-status"></div>
                    <div id="internet-results" class="internet-results"></div>
                    <div id="selected-url-box" class="selected-url-box">Selecionada: <strong id="selected-url-text"></strong></div>
                    <button class="submit-btn" type="submit" name="internet-submit" id="internet-save-btn" disabled><i class="fas fa-save"></i> Salvar Imagem Escolhida</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const bgSelector = document.getElementById('bg-selector');
    bgSelector.addEventListener('change', function() {
        window.location.href = 'background.php?tipo=' + this.value;
    });

    const uploadRadio = document.getElementById('upload-radio');
    const urlRadio = document.getElementById('url-radio');
    const internetRadio = document.getElementById('internet-radio');
    const uploadForm = document.getElementById('upload-form');
    const urlForm = document.getElementById('url-form');
    const internetForm = document.getElementById('internet-form');
    const internetQuery = document.getElementById('internet-query');
    const internetSearchBtn = document.getElementById('internet-search-btn');
    const internetResults = document.getElementById('internet-results');
    const internetStatus = document.getElementById('internet-search-status');
    const internetSelectedUrl = document.getElementById('internet-selected-url');
    const internetSelectedThumb = document.getElementById('internet-selected-thumb');
    const internetSaveBtn = document.getElementById('internet-save-btn');
    const selectedUrlBox = document.getElementById('selected-url-box');
    const selectedUrlText = document.getElementById('selected-url-text');
    let internetAlreadySearched = false;
    let internetSearchTimer = null;
    
    function switchForms() {
        uploadForm.style.display = uploadRadio.checked ? 'block' : 'none';
        urlForm.style.display = urlRadio.checked ? 'block' : 'none';
        internetForm.style.display = internetRadio.checked ? 'block' : 'none';

        if (internetRadio.checked && !internetAlreadySearched) {
            internetAlreadySearched = true;
            searchInternetImages();
        }
    }

    function setInternetStatus(message) {
        internetStatus.textContent = message || '';
    }

    function clearInternetSelection() {
        internetSelectedUrl.value = '';
        internetSelectedThumb.value = '';
        internetSaveBtn.disabled = true;
        selectedUrlBox.style.display = 'none';
        selectedUrlText.textContent = '';
        internetResults.querySelectorAll('.internet-card.selected').forEach(card => card.classList.remove('selected'));
    }

    async function searchInternetImages() {
        const q = (internetQuery.value || '').trim();
        clearInternetSelection();
        internetResults.innerHTML = '';
        if (q.length < 2) {
            setInternetStatus('Digite pelo menos 2 caracteres para buscar.');
            return;
        }
        internetSearchBtn.disabled = true;
        setInternetStatus('Buscando imagens na internet...');

        try {
            const response = await fetch('background_search.php?q=' + encodeURIComponent(q) + '&limit=12', {
                headers: { 'Accept': 'application/json' }
            });
            const data = await response.json();
            if (!data.ok || !Array.isArray(data.results) || data.results.length === 0) {
                setInternetStatus(data.message || 'Nenhuma imagem encontrada. Tente outro termo.');
                return;
            }
            setInternetStatus(data.results.length + ' imagem(ns) encontrada(s). Clique em uma para selecionar.');
            data.results.forEach((item, index) => {
                const card = document.createElement('button');
                card.type = 'button';
                card.className = 'internet-card';
                card.title = item.title || 'Imagem encontrada';
                card.innerHTML = '<img loading="lazy" src="' + String(item.thumb || item.image).replace(/"/g, '&quot;') + '" alt=""><span>' + escapeHtml(item.title || ('Imagem ' + (index + 1))) + '</span>';
                card.addEventListener('click', function() {
                    clearInternetSelection();
                    card.classList.add('selected');
                    internetSelectedUrl.value = item.image;
                    internetSelectedThumb.value = item.thumb || '';
                    internetSaveBtn.disabled = false;
                    selectedUrlBox.style.display = 'block';
                    selectedUrlText.textContent = item.image;
                });
                internetResults.appendChild(card);
            });
        } catch (err) {
            setInternetStatus('Erro ao buscar imagens. Verifique se o servidor permite acesso externo à internet.');
        } finally {
            internetSearchBtn.disabled = false;
        }
    }

    function escapeHtml(text) {
        return String(text).replace(/[&<>"]/g, function(ch) {
            return ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;'}[ch]);
        });
    }
    
    uploadRadio.addEventListener('change', switchForms);
    urlRadio.addEventListener('change', switchForms);
    internetRadio.addEventListener('change', switchForms);
    internetSearchBtn.addEventListener('click', function() {
        internetAlreadySearched = true;
        searchInternetImages();
    });
    internetQuery.addEventListener('input', function() {
        if (!internetRadio.checked) return;
        window.clearTimeout(internetSearchTimer);
        internetSearchTimer = window.setTimeout(function() {
            internetAlreadySearched = true;
            searchInternetImages();
        }, 800);
    });
    internetForm.addEventListener('submit', function(e) {
        if (!internetSelectedUrl.value) {
            e.preventDefault();
            setInternetStatus('Selecione uma imagem antes de salvar.');
        }
    });
    switchForms();

    <?php if (!empty($successMessage)): ?>
    Swal.fire({
        title: 'Sucesso!', text: '<?= addslashes($successMessage) ?>', icon: 'success',
        background: '#2c2f4a', color: '#f1f1f1', confirmButtonColor: 'var(--success-color)'
    }).then(() => {
        window.location.href = window.location.pathname + '?tipo=<?= $redirect_bg_key ?>';
    });
    <?php elseif (!empty($errorMessage)): ?>
    Swal.fire({
        title: 'Erro!', text: '<?= addslashes($errorMessage) ?>', icon: 'error',
        background: '#2c2f4a', color: '#f1f1f1', confirmButtonColor: 'var(--danger-color)'
    });
    <?php endif; ?>
});
</script>

<?php 
include "includes/footer.php"; 
?>