<?php require 'conexao.php'; ?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Gestor de Ofertas Pro</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700;900&family=Oswald:wght@700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    
    <style>
        /* --- CSS GERAL --- */
        body { font-family: 'Segoe UI', sans-serif; background: #eef2f5; padding: 20px; margin: 0; box-sizing: border-box; }
        
        .header-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .btn-tv { text-decoration: none; padding: 10px 20px; border-radius: 6px; font-weight: bold; color: white; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .btn-tv.landscape { background: #2c3e50; }
        .btn-tv.portrait { background: #e67e22; }
        .btn-tv:hover { transform: translateY(-2px); box-shadow: 0 6px 10px rgba(0,0,0,0.2); }

        .container { display: flex; gap: 20px; max-width: 1600px; margin: 0 auto; min-height: 85vh; }
        .controls { flex: 1; background: white; padding: 25px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); overflow-y: auto; max-height: 95vh; }
        .preview-area { flex: 2; background: #2c3e50; border-radius: 12px; display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; flex-direction: column; }
        
        /* Formulários */
        input, select, button { width: 100%; padding: 10px; margin: 5px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; }
        label { font-weight: 600; font-size: 0.9em; color: #555; margin-top: 10px; display: block; }
        fieldset { border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-top: 15px; background: #f8f9fa; }
        legend { font-weight: bold; color: #666; padding: 0 5px; }

        /* Botões */
        button { cursor: pointer; transition: 0.2s; font-weight: bold; border: none; } button:hover { opacity: 0.9; }
        .primary { background: #007bff; color: white; margin-top: 15px; padding: 12px; font-size: 1.1em; }
        .secondary { background: #6c757d; color: white; }
        .success { background: #28a745; color: white; } 
        .btn-banco { background: #6f42c1; color: white; width: auto; flex: 1; }
        .btn-edit { background: #ffc107; color: #333; width: auto; padding: 5px 10px; margin-right: 5px; }
        .btn-del { background: #dc3545; color: white; width: auto; padding: 5px 10px; }

        /* --- MODAL BANCO DE IMAGENS --- */
        .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1000; align-items: center; justify-content: center; }
        .modal-content { background: white; width: 900px; max-width: 95%; height: 700px; border-radius: 10px; padding: 20px; display: flex; flex-direction: column; gap: 10px; }
        
        /* GRID DE IMAGENS */
        .gallery-grid { flex: 1; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; padding: 10px; border: 1px solid #eee; border-radius: 6px; background: #fafafa; }
        .gallery-item { 
            cursor: pointer; border: 2px solid transparent; border-radius: 6px; overflow: hidden; position: relative; 
            background-color: #fff;
            /* Fundo xadrez para ver transparência */
            background-image: linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(-45deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(-45deg, transparent 75%, #ccc 75%);
            background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1); height: 140px; 
        }
        .gallery-item:hover { border-color: #007bff; transform: scale(1.02); }
        .gallery-item img { width: 100%; height: 100%; object-fit: contain; display: block; padding: 5px; box-sizing: border-box; }
        .gallery-item span { display: block; font-size: 11px; padding: 4px; text-align: center; background: rgba(255,255,255,0.9); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; position: absolute; bottom: 0; width: 100%; }
        
        /* Botões Galeria */
        .btn-trash-img { position: absolute; top: 5px; right: 5px; background: #dc3545; color: white; border: none; border-radius: 4px; width: 25px; height: 25px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px; z-index: 10; opacity: 0.8; }
        .btn-trash-img:hover { opacity: 1; transform: scale(1.1); }

        .btn-zoom-img { position: absolute; top: 5px; left: 5px; background: #007bff; color: white; border: none; border-radius: 4px; width: 25px; height: 25px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px; z-index: 10; opacity: 0.8; }
        .btn-zoom-img:hover { opacity: 1; transform: scale(1.1); }

        .btn-edit-img { position: absolute; top: 5px; left: 35px; background: #ffc107; color: #333; border: none; border-radius: 4px; width: 25px; height: 25px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 14px; z-index: 10; opacity: 0.8; }
        .btn-edit-img:hover { opacity: 1; transform: scale(1.1); }

        /* Modal Preview Zoom */
        #modalPreview { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); z-index: 2000; align-items: center; justify-content: center; flex-direction: column; }
        #modalPreview img { max-width: 90%; max-height: 85%; object-fit: contain; background: white; border-radius: 5px; 
            background-image: linear-gradient(45deg, #ccc 25%, transparent 25%), linear-gradient(-45deg, #ccc 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ccc 75%), linear-gradient(-45deg, transparent 75%, #ccc 75%);
            background-size: 30px 30px;
        }
        .close-preview { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }

        /* --- TEMPLATES E PREVIEW --- */
        #tv-frame { background: radial-gradient(circle at center, #ffffff 0%, #dcdcdc 100%); font-family: 'Montserrat', sans-serif; position: relative; overflow: hidden; display: flex; box-shadow: 0 0 50px rgba(0,0,0,0.5); transition: 0.3s; background-size: cover; background-position: center; }
        #tv-frame.landscape { width: 800px; height: 450px; flex-direction: row; }
        #tv-frame.portrait { width: 315px; height: 560px; flex-direction: column-reverse; }
        .sidebar { z-index: 2; display: flex; flex-direction: column; justify-content: center; padding: 20px; box-sizing: border-box; transition: 0.3s; }
        .visual { position: relative; overflow: hidden; flex: 1; }
        .landscape .sidebar { width: 40%; height: 100%; } .portrait .sidebar { width: 100%; height: 40%; text-align: center; }

        .prod-title { line-height: 1; margin: 0 0 10px 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.2); }
        .prod-price { display: inline-block; }
        .tag-oferta { display: inline-block; padding: 5px 15px; border-radius: 4px; font-weight: bold; margin-bottom: 10px; text-transform: uppercase; }

        /* === TEMPLATES === */
        /* Clássico */
        .tpl-classico .sidebar { background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%); color: white; clip-path: polygon(0 0, 100% 0, 90% 100%, 0% 100%); } 
        .portrait .tpl-classico .sidebar { clip-path: polygon(0 15%, 100% 0, 100% 100%, 0% 100%); }
        .tpl-classico .tag-oferta { background: #ffeb3b; color: #d32f2f; }
        .tpl-classico .prod-title { font-weight: 900; font-size: 28px; text-transform: uppercase; }
        .tpl-classico .prod-price { font-weight: 900; font-size: 50px; background: rgba(0,0,0,0.2); padding: 5px 20px; border-radius: 10px; }

        /* Premium */
        .tpl-premium { font-family: 'Playfair Display', serif; }
        .tpl-premium .sidebar { background: #111; color: #d4af37; border-right: 2px solid #d4af37; }
        .portrait .tpl-premium .sidebar { border-right: none; border-top: 2px solid #d4af37; }
        .tpl-premium .tag-oferta { background: #d4af37; color: #000; letter-spacing: 2px; }
        .tpl-premium .prod-title { font-size: 32px; font-style: italic; }
        .tpl-premium .prod-price { font-size: 55px; color: #fff; text-shadow: 0 0 10px #d4af37; }

        /* Fresh */
        .tpl-fresh { font-family: 'Montserrat', sans-serif; }
        .tpl-fresh .sidebar { background: linear-gradient(to bottom, #4caf50, #2e7d32); color: white; border-radius: 0 50px 50px 0; margin-right: -30px; }
        .portrait .tpl-fresh .sidebar { border-radius: 50px 50px 0 0; margin-right: 0; margin-top: -30px; }
        .tpl-fresh .tag-oferta { background: white; color: #2e7d32; border-radius: 20px; }
        .tpl-fresh .prod-title { font-weight: 700; font-size: 26px; }
        .tpl-fresh .prod-price { font-weight: 800; font-size: 48px; color: #a5d6a7; }

        /* Impacto */
        .tpl-impacto { font-family: 'Oswald', sans-serif; }
        .tpl-impacto .sidebar { background: #ffeb3b; color: #d32f2f; }
        .tpl-impacto .tag-oferta { background: #d32f2f; color: #fff; transform: skew(-10deg); }
        .tpl-impacto .prod-title { font-size: 40px; line-height: 0.9; text-transform: uppercase; transform: skew(-5deg); }
        .tpl-impacto .prod-price { font-size: 70px; color: #000; font-weight: 900; letter-spacing: -2px; }

        .draggable { position: absolute; cursor: move; user-select: none; transition: transform 0.1s; }
        .draggable:active { transform: scale(1.02); filter: brightness(1.1); }
        .img-produto-prev { max-width: 80%; max-height: 80%; object-fit: contain; filter: drop-shadow(0 10px 20px rgba(0,0,0,0.4)); }
        .modo-multiply { mix-blend-mode: multiply; filter: contrast(1.1); }
        .logo-area-prev { position: absolute; width: 80px; height: 80px; background: white; border-radius: 50%; display: none; align-items: center; justify-content: center; box-shadow: 0 5px 10px rgba(0,0,0,0.1); z-index: 100; }
        .logo-img-prev { max-width: 80%; max-height: 80%; object-fit: contain; }
        #prev-extra-text { font-weight: bold; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); white-space: nowrap; padding: 5px; border: 2px dashed transparent; }
        #prev-extra-text:hover { border-color: rgba(255,255,255,0.5); }

        .listagem { max-width: 1600px; margin: 30px auto; background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        table { width: 100%; border-collapse: collapse; } th, td { padding: 12px; border-bottom: 1px solid #eee; text-align: left; } tr:hover { background: #f9f9f9; }
    </style>
</head>
<body>

<div id="modalPreview" onclick="fecharPreview()">
    <span class="close-preview">&times;</span>
    <img id="imgExpandida" src="">
</div>

<div id="modalBanco" class="modal-overlay">
    <div class="modal-content">
        <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #eee; padding-bottom:10px;">
            <h3 style="margin:0" id="modalTitulo">🏦 Banco de Arquivos</h3>
            <span onclick="fecharBanco()" style="font-size:25px; cursor:pointer;">&times;</span>
        </div>
        
        <div id="areaUpload" style="background:#f9f9f9; padding:15px; border-radius:6px; border:2px dashed #ccc; text-align:center;">
            <input type="file" id="uploadFile" accept="image/*" style="display:none" onchange="realizarUpload()">
            <button onclick="document.getElementById('uploadFile').click()" class="secondary" style="width:auto">📤 Enviar do PC</button>
            <span id="uploadStatus" style="font-size:12px; margin-left:10px;"></span>
        </div>

        <div id="areaBuscaWeb" style="display:none; background:#e3f2fd; padding:15px; border-radius:6px; border:1px solid #90caf9;">
            <div style="display:flex; gap:10px;">
                <input type="text" id="termoBuscaReal" placeholder="Ex: Sabão Omo, Coca Cola..." style="margin:0;">
                <button class="primary" onclick="executarBuscaReal()" style="margin:0; width:auto;">🔍 Buscar PNG</button>
            </div>
            <p style="font-size:12px; color:#555; margin:5px 0 0 0;">O sistema filtrará automaticamente por imagens <b>TRANSPARENTES (PNG)</b>.</p>
        </div>

        <input type="text" id="buscaBanco" placeholder="🔎 Filtrar nos meus arquivos..." oninput="carregarGaleria()">
        <div id="galeriaGrid" class="gallery-grid"></div>
    </div>
</div>

<div class="header-top">
    <h1 style="margin:0; color:#333;">Gestor de Ofertas</h1>
    <div style="display:flex; gap:10px;">
        <a href="tv.php?modo=landscape" target="_blank" class="btn-tv">📺 TV Horizontal</a>
        <a href="tv.php?modo=portrait" target="_blank" class="btn-tv">📱 TV Vertical</a>
    </div>
</div>

<div class="container">
    <div class="controls">
        <h2 id="titulo-form" style="margin-top:0; color:#333;">Nova Oferta</h2>
        <input type="hidden" id="id_oferta">
        
        <input type="hidden" id="img_pos_x" value="center"><input type="hidden" id="img_pos_y" value="center">
        <input type="hidden" id="extra_pos_x" value="center"><input type="hidden" id="extra_pos_y" value="center">
        <input type="hidden" id="logo_pos_x" value="default"><input type="hidden" id="logo_pos_y" value="default">

        <fieldset style="background:#e3f2fd; border:1px solid #90caf9;">
            <legend>🎨 Estilo do Anúncio (Template)</legend>
            <select id="template_style" onchange="atualizarPreview()" style="font-weight:bold; font-size:1.1em;">
                <option value="classico">🔴 Clássico (Mercado Padrão)</option>
                <option value="premium">⚫ Premium (Preto e Dourado)</option>
                <option value="fresh">🟢 Fresh (Hortifruti/Saúde)</option>
                <option value="impacto">🟡 Impacto (Amarelo Varejo)</option>
            </select>
        </fieldset>

        <label>Produto</label>
        <input type="text" id="produto" list="listaProdutos" placeholder="Digite para buscar..." oninput="buscarSugestoes(this); atualizarPreview()">
        <datalist id="listaProdutos"></datalist>

        <div style="display:flex; gap:10px">
            <div style="flex:1"><label>Preço</label><input type="number" id="preco" step="0.01" oninput="atualizarPreview()"></div>
            <div style="flex:1"><label>Validade</label><input type="date" id="data_validade" oninput="atualizarPreview()"></div>
        </div>

        <label>Formato da Tela</label>
        <select id="formato" onchange="atualizarPreview()">
            <option value="landscape">Horizontal (TV 16:9)</option>
            <option value="portrait">Vertical (Stories 9:16)</option>
        </select>

        <label>Imagem Produto (Arraste no Preview)</label>
        <div style="display:flex; gap:5px">
            <input type="text" id="imgUrl" placeholder="URL da imagem..." oninput="atualizarPreview()">
            <button class="btn-banco" onclick="abrirBanco('produto')" title="Meus Arquivos">📂</button>
            <button class="secondary" onclick="abrirBuscaWeb('produto')" title="Buscar PNG na Internet">🔍 PNG</button>
            <button class="success" onclick="salvarImagemProdutoNoBanco()" title="Salvar imagem atual na galeria">💾</button>
        </div>
        <label style="display:flex; align-items:center; gap:10px; background:#fff3cd; padding:8px; border-radius:5px; margin-top:5px; cursor:pointer;">
            <input type="checkbox" id="check_fundo" onchange="atualizarPreview()" style="width:20px; height:20px; margin:0;" checked>
            <span style="font-size:12px; color:#856404;">🪄 Remover Fundo Branco (Multiplicação)</span>
        </label>

        <label>Logomarca (Arraste no Preview)</label>
        <input type="text" id="logo_url" placeholder="URL da Logo..." oninput="atualizarPreview()">
        <label>Tamanho da Logo:</label>
        <input type="range" id="logo_tamanho" min="50" max="300" value="100" oninput="atualizarPreview()">

        <fieldset>
            <legend>🔤 Texto Extra</legend>
            <input type="text" id="extra_texto" placeholder="Ex: Oferta Relâmpago" oninput="atualizarPreview()">
            <div style="display:flex; gap:10px;">
                <div style="flex:1"><label>Cor:</label><input type="color" id="extra_cor" value="#ffffff" oninput="atualizarPreview()" style="height:40px;"></div>
                <div style="flex:1"><label>Tamanho:</label><input type="number" id="extra_tamanho" value="40" oninput="atualizarPreview()"></div>
            </div>
        </fieldset>

        <fieldset>
            <legend>🎨 Fundo (Background)</legend>
            <select id="bg_tipo" onchange="alternarInputsBackground()">
                <option value="padrao">✨ Padrão</option>
                <option value="cor">🟥 Cor Sólida</option>
                <option value="imagem">🖼️ Imagem/Textura</option>
            </select>
            <div id="box_bg_cor" style="display:none; margin-top:5px;"><input type="color" id="bg_cor_input" value="#e63946" oninput="atualizarPreview()" style="height:40px;"></div>
            <div id="box_bg_imagem" style="display:none; margin-top:5px;">
                <div style="display:flex; gap:5px;">
                    <input type="text" id="bg_img_input" placeholder="http://..." oninput="atualizarPreview()">
                </div>
                <div style="display:flex; gap:5px; margin-top:5px;">
                    <button class="btn-banco" onclick="abrirBanco('bg')">📂 Banco</button>
                    <button class="secondary" onclick="abrirBuscaWeb('bg')">🔍 Web</button>
                    <button class="success" onclick="salvarBackgroundNoBanco()">💾 Salvar</button>
                </div>
            </div>
        </fieldset>

        <div style="display:flex; flex-direction:column; gap:10px; margin-top:20px;">
            <button class="primary" id="btn-salvar" onclick="salvarOferta()">💾 SALVAR NO SISTEMA</button>
            <button class="success" onclick="baixarImagem()">⬇️ BAIXAR IMAGEM (PNG)</button>
            <button class="secondary" id="btn-cancelar" onclick="limparFormulario()" style="display:none;">Cancelar Edição</button>
        </div>
    </div>

    <div class="preview-area">
        <h4 style="color:#aaa; margin-bottom:10px;">Preview Interativo</h4>
        <div id="tv-frame" class="landscape tpl-classico">
            <div id="prev-sidebar" class="sidebar sidebar-padrao">
                <div>
                    <div class="tag-oferta">OFERTA</div>
                    <div id="prev-titulo" class="prod-title">PRODUTO</div>
                    <div id="prev-valor" class="prod-price">0,00</div>
                    <div id="prev-validade" style="margin-top:10px; font-size:12px; opacity:0.8;"></div>
                </div>
            </div>
            
            <div class="visual" id="visual-container">
                <div id="prev-logo-container" class="logo-area-prev draggable"><img id="prev-logo" class="logo-img-prev" src=""></div>
                <img id="prev-img" class="img-produto-prev draggable" src="https://via.placeholder.com/300?text=Foto" crossorigin="anonymous">
                <div id="prev-extra-text" class="draggable" style="display:none;">Texto</div>
            </div>
        </div>
    </div>
</div>

<div class="listagem">
    <h3>📋 Ofertas Cadastradas</h3>
    <table>
        <thead><tr><th>ID</th><th>Img</th><th>Produto</th><th>Preço</th><th>Ações</th></tr></thead>
        <tbody>
            <?php
            $stmt = $pdo->query("SELECT * FROM ofertas ORDER BY id DESC LIMIT 30");
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $json = htmlspecialchars(json_encode($row), ENT_QUOTES, 'UTF-8');
                echo "<tr><td>{$row['id']}</td><td><img src='{$row['imagem_url']}' style='width:30px;height:30px;object-fit:contain'></td><td>{$row['produto']}</td><td>R$ ".number_format($row['preco'],2,',','.')."</td><td><button class='btn-edit' onclick='carregarEdicao($json)'>✏️</button><a href='excluir.php?id={$row['id']}' class='btn-del' onclick='return confirm(\"Excluir?\")'>🗑️</a></td></tr>";
            }
            ?>
        </tbody>
    </table>
</div>

<script>
    const modal = document.getElementById('modalBanco');
    const modalPreview = document.getElementById('modalPreview');
    let destinoAtual = 'produto';

    // --- AUTOCOMPLETE DE PRODUTOS ---
    function buscarSugestoes(input) {
        if(input.value.length < 2) return;
        fetch('api_produtos.php?term=' + input.value)
            .then(r => r.json())
            .then(lista => {
                const dl = document.getElementById('listaProdutos');
                dl.innerHTML = '';
                lista.forEach(nome => {
                    const opt = document.createElement('option');
                    opt.value = nome;
                    dl.appendChild(opt);
                });
            });
    }

    // --- ARRASTAR E SOLTAR (EM %) ---
    function makeElementDraggable(elementId, containerId, inputXId, inputYId) {
        let pos1=0, pos2=0, pos3=0, pos4=0;
        const el = document.getElementById(elementId);
        const container = document.getElementById(containerId);
        if(!el || !container) return;
        el.onmousedown = (e) => { e.preventDefault(); pos3=e.clientX; pos4=e.clientY; document.onmouseup=closeDrag; document.onmousemove=elementDrag; };
        function elementDrag(e) {
            e.preventDefault(); pos1=pos3-e.clientX; pos2=pos4-e.clientY; pos3=e.clientX; pos4=e.clientY;
            el.style.top = (el.offsetTop - pos2) + "px"; el.style.left = (el.offsetLeft - pos1) + "px";
            el.style.transform = 'none'; el.style.right = 'auto';
        }
        function closeDrag() {
            document.onmouseup=null; document.onmousemove=null;
            const leftPct = (el.offsetLeft / container.offsetWidth) * 100;
            const topPct = (el.offsetTop / container.offsetHeight) * 100;
            document.getElementById(inputXId).value = leftPct.toFixed(2) + "%";
            document.getElementById(inputYId).value = topPct.toFixed(2) + "%";
        }
    }
    makeElementDraggable("prev-img", "visual-container", "img_pos_x", "img_pos_y");
    makeElementDraggable("prev-extra-text", "visual-container", "extra_pos_x", "extra_pos_y");
    makeElementDraggable("prev-logo-container", "visual-container", "logo_pos_x", "logo_pos_y");

    // --- MODAIS ---
    function fecharBanco() { modal.style.display='none'; }
    function fecharPreview() { modalPreview.style.display='none'; }
    modal.onclick = (e) => { if(e.target==modal) fecharBanco(); }

    function abrirBanco(d) { 
        destinoAtual=d; modal.style.display='flex'; 
        document.getElementById('areaUpload').style.display = 'block';
        document.getElementById('areaBuscaWeb').style.display = 'none';
        document.getElementById('buscaBanco').style.display = 'block';
        document.getElementById('modalTitulo').innerText = "🏦 Meus Arquivos";
        carregarGaleria(); 
    }

    function abrirBuscaWeb(d) {
        destinoAtual=d; modal.style.display='flex';
        document.getElementById('areaUpload').style.display = 'none';
        document.getElementById('areaBuscaWeb').style.display = 'block';
        document.getElementById('buscaBanco').style.display = 'none'; 
        document.getElementById('modalTitulo').innerText = (d === 'produto') ? "🔍 Buscar PNG" : "🔍 Buscar Textura";
        
        if(d === 'produto') {
            const nomeProd = document.getElementById('produto').value;
            document.getElementById('termoBuscaReal').value = nomeProd;
            if(nomeProd.trim().length > 0) executarBuscaReal();
        } else {
            document.getElementById('termoBuscaReal').value = "Textura madeira";
        }
        document.getElementById('galeriaGrid').innerHTML = '';
    }

    function verImagemAmpliada(url, event) {
        event.stopPropagation();
        document.getElementById('imgExpandida').src = url;
        modalPreview.style.display = 'flex';
    }

    function carregarGaleria() {
        const busca = document.getElementById('buscaBanco').value;
        const grid = document.getElementById('galeriaGrid');
        grid.innerHTML = '<p style="padding:20px">Carregando...</p>';
        fetch(`gestor_imagens.php?acao=listar&busca=${busca}`).then(r=>r.json()).then(imgs=>{
            grid.innerHTML = '';
            imgs.forEach(img => {
                const d = document.createElement('div'); d.className='gallery-item';
                d.innerHTML=`
                    <button class="btn-trash-img" onclick="excluirImagemBanco(${img.id}, event)" title="Excluir">🗑️</button>
                    <button class="btn-zoom-img" onclick="verImagemAmpliada('${img.caminho}', event)" title="Ampliar">🔍</button>
                    <button class="btn-edit-img" onclick="renomearImagemBanco(${img.id}, '${img.nome_arquivo}', event)" title="Renomear">✏️</button>
                    <img src="${img.caminho}"><span>${img.nome_arquivo}</span>
                `;
                d.onclick=(e)=>{ 
                    if(e.target.tagName==='BUTTON') return;
                    aplicarImagem(img.caminho);
                };
                grid.appendChild(d);
            });
            if(imgs.length===0) grid.innerHTML='<p style="padding:20px">Nada encontrado.</p>';
        });
    }

    function executarBuscaReal() {
        const termo = document.getElementById('termoBuscaReal').value;
        const grid = document.getElementById('galeriaGrid');
        if(!termo) return alert("Digite o que procura.");
        grid.innerHTML = '<p style="padding:20px; text-align:center">🔍 Buscando PNGs...<br>Aguarde...</p>';
        fetch(`buscador.php?termo=${encodeURIComponent(termo)}`).then(r => r.json()).then(urls => {
            grid.innerHTML = '';
            if(urls.length === 0) { grid.innerHTML = '<p style="padding:20px">Nada encontrado.</p>'; return; }
            urls.forEach(url => {
                const d = document.createElement('div'); d.className='gallery-item';
                d.innerHTML=`
                    <button class="btn-zoom-img" onclick="verImagemAmpliada('${url}', event)" title="Ampliar">🔍</button>
                    <img src="${url}" onerror="this.parentElement.style.display='none'">
                `;
                d.onclick = () => aplicarImagem(url);
                grid.appendChild(d);
            });
        }).catch(e => { grid.innerHTML = '<p style="padding:20px">Erro na busca.</p>'; });
    }

    function aplicarImagem(url) {
        if(destinoAtual === 'produto') {
            document.getElementById('imgUrl').value = url;
            document.getElementById('img_pos_x').value = 'center';
            document.getElementById('img_pos_y').value = 'center';
            document.getElementById('check_fundo').checked = false; 
        } else {
            document.getElementById('bg_img_input').value = url;
        }
        atualizarPreview();
        fecharBanco();
    }

    function realizarUpload() {
        const file = document.getElementById('uploadFile').files[0]; if(!file) return;
        const fd = new FormData(); fd.append('arquivo', file); fd.append('acao', 'upload');
        document.getElementById('uploadStatus').innerText="Enviando...";
        fetch('gestor_imagens.php',{method:'POST',body:fd}).then(r=>r.json()).then(r=>{
            document.getElementById('uploadStatus').innerText=r.msg; if(r.sucesso) carregarGaleria();
        });
    }
    
    function excluirImagemBanco(id, event) {
        event.stopPropagation(); if(!confirm("Apagar permanentemente?")) return;
        const fd = new FormData(); fd.append('acao', 'excluir'); fd.append('id', id);
        fetch('gestor_imagens.php',{method:'POST',body:fd}).then(r=>r.json()).then(r=>{ if(r.sucesso) carregarGaleria(); });
    }

    function renomearImagemBanco(id, nomeAtual, event) {
        event.stopPropagation();
        const novoNome = prompt("Novo nome:", nomeAtual);
        if(!novoNome) return;
        const fd = new FormData(); fd.append('acao', 'renomear'); fd.append('id', id); fd.append('nome', novoNome);
        fetch('gestor_imagens.php', {method:'POST', body:fd}).then(r=>r.json()).then(r=>{ if(r.sucesso) carregarGaleria(); else alert(r.msg); });
    }

    function salvarBackgroundNoBanco() {
        const url = document.getElementById('bg_img_input').value;
        if(!url) return alert("Sem URL.");
        let nomeBg = prompt("Nome do Fundo:", "Fundo Novo"); if(!nomeBg) return;
        const btn = document.querySelector('button[onclick="salvarBackgroundNoBanco()"]'); btn.innerText="Baixando..."; btn.disabled=true;
        const fd = new FormData(); fd.append('acao', 'salvar_url'); fd.append('url', url); fd.append('nome', nomeBg);
        fetch('gestor_imagens.php',{method:'POST',body:fd}).then(r=>r.json()).then(r=>{
            alert(r.msg); if(r.sucesso) { document.getElementById('bg_img_input').value = r.caminho; atualizarPreview(); }
            btn.innerText="💾 Salvar"; btn.disabled=false;
        });
    }

    function salvarImagemProdutoNoBanco() {
        const url = document.getElementById('imgUrl').value;
        let nomeProd = document.getElementById('produto').value;
        if(!url) return alert("Sem URL."); if(!nomeProd) nomeProd = "Produto sem nome";
        const btn = document.querySelector('button[onclick="salvarImagemProdutoNoBanco()"]'); btn.innerText="⏳"; btn.disabled=true;
        const fd = new FormData(); fd.append('acao', 'salvar_url'); fd.append('url', url); fd.append('nome', nomeProd);
        fetch('gestor_imagens.php', { method: 'POST', body: fd }).then(r => r.json()).then(resp => {
            if (resp.sucesso) { alert("Salvo: " + nomeProd); document.getElementById('imgUrl').value = resp.caminho; atualizarPreview(); } else { alert("Erro: " + resp.msg); }
            btn.innerText="💾"; btn.disabled=false;
        });
    }

    function alternarInputsBackground() { const t = document.getElementById('bg_tipo').value; document.getElementById('box_bg_cor').style.display=(t==='cor')?'block':'none'; document.getElementById('box_bg_imagem').style.display=(t==='imagem')?'block':'none'; atualizarPreview(); }
    
    function atualizarPreview() {
        const p = document.getElementById('produto').value || "PRODUTO";
        const val = parseFloat(document.getElementById('preco').value||0).toFixed(2).replace('.',',');
        const img = document.getElementById('imgUrl').value;
        const logo = document.getElementById('logo_url').value;
        const data = document.getElementById('data_validade').value;
        const fmt = document.getElementById('formato').value;
        const checkFundo = document.getElementById('check_fundo').checked;
        const tpl = document.getElementById('template_style').value;

        const frame = document.getElementById('tv-frame'); frame.className = ""; frame.classList.add(fmt); frame.classList.add('tpl-' + tpl);
        document.getElementById('prev-titulo').innerText = p;
        document.getElementById('prev-valor').innerText = "R$ " + val;
        
        const imgEl = document.getElementById('prev-img');
        imgEl.src = img ? img : 'https://via.placeholder.com/300?text=Sem+Imagem';
        if(checkFundo) imgEl.classList.add('modo-multiply'); else imgEl.classList.remove('modo-multiply');
        
        const posX = document.getElementById('img_pos_x').value;
        const posY = document.getElementById('img_pos_y').value;
        if(posX === 'center') {
            imgEl.style.left = '50%'; imgEl.style.top = '50%'; imgEl.style.transform = 'translate(-50%, -50%)';
        } else {
            imgEl.style.left = posX; imgEl.style.top = posY; imgEl.style.transform = 'none';
        }

        const logoCont = document.getElementById('prev-logo-container');
        const logoSize = document.getElementById('logo_tamanho').value;
        if(logo) { document.getElementById('prev-logo').src = logo; logoCont.style.display='flex'; logoCont.style.width=logoSize+'px'; logoCont.style.height=logoSize+'px'; } else { logoCont.style.display='none'; }

        const valDiv = document.getElementById('prev-validade');
        if(data) { const pt=data.split('-'); valDiv.innerText=`Válido até ${pt[2]}/${pt[1]}`; } else valDiv.innerText="";

        const extraTxt = document.getElementById('extra_texto').value;
        const extraEl = document.getElementById('prev-extra-text');
        if(extraTxt) { extraEl.innerText=extraTxt; extraEl.style.color=document.getElementById('extra_cor').value; extraEl.style.fontSize=(document.getElementById('extra_tamanho').value*(fmt==='landscape'?0.5:0.3))+'px'; extraEl.style.display='block'; } else { extraEl.style.display='none'; }

        const bgTipo = document.getElementById('bg_tipo').value;
        frame.style.background = '';
        if(bgTipo==='cor'){ frame.style.background=document.getElementById('bg_cor_input').value; } 
        else if(bgTipo==='imagem'){ const u = document.getElementById('bg_img_input').value; if(u) frame.style.background=`url('${u}') center/cover no-repeat`; }
    }

    function baixarImagem() { const frame = document.getElementById('tv-frame'); const btn = document.querySelector('.success[onclick="baixarImagem()"]'); const txtOriginal = btn.innerText; btn.innerText = "⏳ Gerando..."; html2canvas(frame, { scale: 2, useCORS: true, backgroundColor: null }).then(canvas => { const link = document.createElement('a'); link.download = 'oferta_' + document.getElementById('produto').value + '.png'; link.href = canvas.toDataURL("image/png"); link.click(); btn.innerText = txtOriginal; }).catch(err => { alert("Erro ao gerar imagem."); console.error(err); btn.innerText = txtOriginal; }); }
    
    function carregarEdicao(d) {
        document.getElementById('id_oferta').value=d.id;
        document.getElementById('produto').value=d.produto;
        document.getElementById('preco').value=d.preco;
        document.getElementById('formato').value=d.formato;
        document.getElementById('imgUrl').value=d.imagem_url;
        document.getElementById('logo_url').value=d.logo_url;
        document.getElementById('data_validade').value=d.data_validade;
        document.getElementById('check_fundo').checked=(d.efeito_visual==='multiply');
        document.getElementById('bg_tipo').value=d.bg_tipo;
        if(d.bg_tipo==='cor') document.getElementById('bg_cor_input').value=d.bg_valor;
        if(d.bg_tipo==='imagem') document.getElementById('bg_img_input').value=d.bg_valor;
        document.getElementById('extra_texto').value = d.extra_texto;
        document.getElementById('extra_cor').value = d.extra_cor;
        document.getElementById('extra_tamanho').value = d.extra_tamanho;
        document.getElementById('logo_tamanho').value = d.logo_tamanho || 100;
        document.getElementById('template_style').value = d.template_style || 'classico';

        function setPos(el, x, y, inputX, inputY) {
            document.getElementById(inputX).value = x; document.getElementById(inputY).value = y;
            if(x && x !== 'center' && x !== 'default') { el.style.left = x; el.style.transform='none'; el.style.right='auto'; } else { el.style.left = ''; el.style.transform=''; }
            if(y && y !== 'center' && y !== 'default') { el.style.top = y; } else { el.style.top = ''; }
        }
        
        document.getElementById('img_pos_x').value = d.img_pos_x || 'center';
        document.getElementById('img_pos_y').value = d.img_pos_y || 'center';
        
        setPos(document.getElementById('prev-extra-text'), d.extra_pos_x, d.extra_pos_y, 'extra_pos_x', 'extra_pos_y');
        
        const logoEl = document.getElementById('prev-logo-container');
        if (d.logo_pos_x && d.logo_pos_x !== 'default') { logoEl.style.left = d.logo_pos_x; logoEl.style.top = d.logo_pos_y; logoEl.style.right = 'auto'; document.getElementById('logo_pos_x').value=d.logo_pos_x; document.getElementById('logo_pos_y').value=d.logo_pos_y; } else { logoEl.style.top = '15px'; logoEl.style.right = '15px'; logoEl.style.left = ''; document.getElementById('logo_pos_x').value='default'; }

        alternarInputsBackground();
        document.getElementById('titulo-form').innerText="Editando #"+d.id;
        document.getElementById('btn-salvar').innerText="SALVAR ALTERAÇÕES";
        document.getElementById('btn-salvar').style.background="#28a745";
        document.getElementById('btn-cancelar').style.display="block";
        window.scrollTo({top:0, behavior:'smooth'});
        atualizarPreview();
    }

    function salvarOferta() {
        const fd = new FormData();
        fd.append('id_oferta', document.getElementById('id_oferta').value);
        fd.append('produto', document.getElementById('produto').value);
        fd.append('preco', document.getElementById('preco').value);
        fd.append('formato', document.getElementById('formato').value);
        fd.append('imagem_url', document.getElementById('imgUrl').value); 
        fd.append('logo_url', document.getElementById('logo_url').value);
        fd.append('data_validade', document.getElementById('data_validade').value);
        fd.append('efeito_visual', document.getElementById('check_fundo').checked ? 'multiply' : 'normal');
        fd.append('bg_tipo', document.getElementById('bg_tipo').value);
        fd.append('bg_cor_input', document.getElementById('bg_cor_input').value);
        fd.append('bg_img_input', document.getElementById('bg_img_input').value);
        fd.append('extra_texto', document.getElementById('extra_texto').value);
        fd.append('extra_cor', document.getElementById('extra_cor').value);
        fd.append('extra_tamanho', document.getElementById('extra_tamanho').value);
        fd.append('logo_tamanho', document.getElementById('logo_tamanho').value);
        fd.append('template_style', document.getElementById('template_style').value);
        fd.append('img_pos_x', document.getElementById('img_pos_x').value);
        fd.append('img_pos_y', document.getElementById('img_pos_y').value);
        fd.append('extra_pos_x', document.getElementById('extra_pos_x').value);
        fd.append('extra_pos_y', document.getElementById('extra_pos_y').value);
        fd.append('logo_pos_x', document.getElementById('logo_pos_x').value);
        fd.append('logo_pos_y', document.getElementById('logo_pos_y').value);

        const btn = document.getElementById('btn-salvar');
        const txtOriginal = btn.innerText; btn.innerText = "Salvando..."; btn.disabled = true;

        fetch('salvar.php', { method: 'POST', body: fd }).then(r => r.text()).then(msg => {
            alert(msg); location.reload();
        }).catch(err => {
            alert("Erro."); console.error(err); btn.innerText = txtOriginal; btn.disabled = false;
        });
    }
    
    function limparFormulario() { location.reload(); }

    alternarInputsBackground(); atualizarPreview();
</script>
</body>
</html>