<?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=Bebas+Neue&family=Montserrat:wght@400;700;900&family=Orbitron:wght@700&family=Oswald:wght@700&family=Pacifico&family=Playfair+Display:wght@700&family=Poppins:wght@400;800&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    
    <style>
        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; flex-wrap: wrap; gap: 10px; }
        .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; flex-wrap: wrap; }
        .controls { flex: 1; min-width: 350px; 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; min-width: 350px; background: #2c3e50; border-radius: 12px; display: flex; align-items: center; justify-content: center; overflow: hidden; position: relative; flex-direction: column; padding: 20px; }
        
        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; }

        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-mini-group { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; margin-bottom: 5px; }
        .btn-banco { background: #6f42c1; color: white; width: auto; padding: 8px 12px; flex: 1; white-space: nowrap; }
        .btn-web { background: #17a2b8; color: white; width: auto; padding: 8px 12px; flex: 1; white-space: nowrap; }
        .btn-save-img { background: #28a745; color: white; width: auto; padding: 8px 12px; flex: 1; white-space: nowrap; }

        .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; }

        /* MODAIS & GALERIA */
        .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; }
        .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; 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; 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%; }
        
        .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-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-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; }

        #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; }
        .close-preview { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }

        /* PREVIEW FRAME */
        #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); }
        .tag-oferta { display: inline-block; padding: 5px 15px; border-radius: 4px; font-weight: bold; margin-bottom: 10px; text-transform: uppercase; font-size: 20px; }
        
        /* PREÇO ESTILIZADO */
        .price-container { display: inline-flex; align-items: baseline; justify-content: center; line-height: 1; }
        .currency { font-size: 0.4em; vertical-align: super; margin-right: 5px; font-weight: 400; opacity: 0.9; }
        .amount { font-size: 1em; font-weight: 900; letter-spacing: -2px; }
        .unit { font-size: 0.3em; margin-left: 5px; font-weight: 600; text-transform: uppercase; opacity: 0.8; }

        .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); }

        /* TEMPLATES */
        .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: 40px; text-transform: uppercase; }
        .tpl-classico .price-container { font-weight: 900; font-size: 55px; background: rgba(0,0,0,0.2); padding: 5px 20px; border-radius: 10px; }

        .tpl-premium .sidebar { background: #111; color: #d4af37; border-right: 2px solid #d4af37; font-family: 'Playfair Display', serif; } .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: 40px; font-style: italic; }
        .tpl-premium .price-container { font-size: 55px; color: #fff; text-shadow: 0 0 10px #d4af37; }

        .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: 40px; }
        .tpl-fresh .price-container { font-weight: 800; font-size: 55px; color: #a5d6a7; }

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

        .tpl-blackfriday .sidebar { background: #111; color: yellow; border-right: 5px solid yellow; font-family: 'Montserrat', sans-serif; }
        .tpl-blackfriday .tag-oferta { background: red; color: white; font-weight:900; letter-spacing: 2px; transform: skew(-10deg); box-shadow: 3px 3px 0px rgba(255,255,255,0.2); }
        .tpl-blackfriday .prod-title { font-weight: 900; font-size: 40px; text-transform: uppercase; color: white; }
        .tpl-blackfriday .price-container { font-family: 'Bebas Neue', sans-serif; font-size: 70px; color: yellow; line-height: 0.9; text-shadow: 2px 2px 0px red; }

        .tpl-padaria .sidebar { background: #5d4037; color: #fbe9e7; border-radius: 0 40px 40px 0; margin-right: -20px; font-family: 'Poppins', sans-serif; } .portrait .tpl-padaria .sidebar { border-radius: 40px 40px 0 0; margin-right:0; margin-top:-20px; }
        .tpl-padaria .tag-oferta { background: #d7ccc8; color: #3e2723; font-family: 'Pacifico', cursive; padding: 5px 20px; text-transform: none; font-size: 1.5em; }
        .tpl-padaria .prod-title { font-weight: 600; font-size: 38px; }
        .tpl-padaria .price-container { font-weight: 800; font-size: 55px; background: #fff; color: #5d4037; padding: 5px 15px; border-radius: 50px; box-shadow: 0 5px 10px rgba(0,0,0,0.1); }

        .tpl-cyber { font-family: 'Orbitron', sans-serif; }
        .tpl-cyber .sidebar { background: linear-gradient(180deg, #240b36 0%, #c31432 100%); color: white; clip-path: polygon(0 0, 100% 0, 85% 100%, 0% 100%); } .portrait .tpl-cyber .sidebar { clip-path: polygon(0 0, 100% 0, 100% 85%, 0 100%); }
        .tpl-cyber .tag-oferta { background: transparent; border: 1px solid #00f2ff; color: #00f2ff; box-shadow: 0 0 10px #00f2ff; text-shadow: 0 0 5px #00f2ff; }
        .tpl-cyber .prod-title { font-size: 38px; text-transform: uppercase; letter-spacing: 1px; }
        .tpl-cyber .price-container { font-size: 55px; color: #fff; text-shadow: 0 0 10px #c31432, 2px 2px 0px #00f2ff; }

        .tpl-acougue { font-family: 'Oswald', sans-serif; }
        .tpl-acougue .sidebar { background: radial-gradient(circle, #8a0000 0%, #300000 100%); color: white; border-right: 4px dashed rgba(255,255,255,0.3); }
        .tpl-acougue .tag-oferta { background: #fff; color: #8a0000; font-weight: bold; border-radius: 4px; }
        .tpl-acougue .prod-title { font-size: 50px; text-transform: uppercase; }
        .tpl-acougue .price-container { color: #ffca28; font-weight: 900; font-size: 70px; text-shadow: 2px 2px 5px rgba(0,0,0,0.8); }

        .tpl-varejo-azul { font-family: 'Montserrat', sans-serif; }
        .tpl-varejo-azul .sidebar { background: #0277bd; color: white; }
        .tpl-varejo-azul .tag-oferta { background: #ffeb3b; color: #01579b; border-radius: 50px; padding: 5px 25px; box-shadow: 0 4px 0 #fbc02d; margin-bottom: 10px; }
        .tpl-varejo-azul .prod-title { font-size: 40px; font-weight: 800; text-transform: uppercase; }
        .tpl-varejo-azul .price-container { font-size: 55px; font-weight: 900; background: yellow; color: #01579b; padding: 0 20px; transform: rotate(-3deg); display: inline-block; box-shadow: 3px 3px 10px rgba(0,0,0,0.3); }

        .tpl-pharma { font-family: 'Poppins', sans-serif; }
        .tpl-pharma .sidebar { background: white; color: #333; border-right: 10px solid #26c6da; } .portrait .tpl-pharma .sidebar { border-right: none; border-top: 10px solid #26c6da; }
        .tpl-pharma .tag-oferta { background: #26c6da; color: white; border-radius: 4px; font-weight: 400; }
        .tpl-pharma .prod-title { font-size: 38px; font-weight: 400; color: #555; }
        .tpl-pharma .price-container { font-size: 55px; font-weight: 700; color: #0097a7; }

        .tpl-bebidas { font-family: 'Bebas Neue', sans-serif; }
        .tpl-bebidas .sidebar { background: linear-gradient(45deg, #00c6ff, #0072ff); color: white; }
        .tpl-bebidas .tag-oferta { background: rgba(255,255,255,0.2); border: 1px solid white; backdrop-filter: blur(5px); border-radius: 20px; letter-spacing: 2px; }
        .tpl-bebidas .prod-title { font-family: 'Montserrat', sans-serif; font-size: 40px; font-weight: 900; text-transform: uppercase; font-style: italic; }
        .tpl-bebidas .price-container { font-size: 70px; text-shadow: 0 5px 10px rgba(0,0,0,0.3); }

        .tpl-organic { font-family: 'Montserrat', sans-serif; }
        .tpl-organic .sidebar { background: #8d6e63; color: white; }
        .tpl-organic .tag-oferta { background: #7cb342; color: white; border-radius: 50% 10% 50% 10%; padding: 10px 20px; }
        .tpl-organic .prod-title { font-size: 40px; font-weight: 700; }
        .tpl-organic .price-container { font-size: 55px; color: #c5e1a5; font-weight: 900; border-bottom: 3px solid #7cb342; }

        /* Tabela Inteligente */
        .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); }
        .listagem-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; flex-wrap: wrap; gap: 10px; }
        .search-box { flex: 1; min-width: 200px; position: relative; }
        .search-box input { width: 100%; padding-left: 35px; border-radius: 20px; border: 1px solid #ccc; }
        .search-icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #888; }
        
        .listagem table { width: 100%; border-collapse: collapse; table-layout: fixed; }
        .listagem th, .listagem td { padding: 12px; border-bottom: 1px solid #eee; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .listagem tr:hover { background: #f9f9f9; }
        
        .listagem th:nth-child(1) { width: 50px; } /* ID */
        .listagem th:nth-child(2) { width: 60px; } /* IMG */
        .listagem th:nth-child(4) { width: 140px; } /* Preço */
        .listagem th:nth-child(5) { width: 110px; } /* Ações */

        .pagination { display: flex; gap: 5px; justify-content: flex-end; margin-top: 15px; }
        .page-btn { padding: 5px 12px; border: 1px solid #ddd; background: white; cursor: pointer; border-radius: 4px; transition: 0.2s; width: auto; }
        .page-btn:hover { background: #f0f0f0; }
        .page-btn.active { background: #007bff; color: white; border-color: #007bff; }
        .page-btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .portrait .prod-title { font-size: 28px !important; margin-bottom: 5px; }
        .portrait .price-container { font-size: 45px !important; }
        .portrait .tag-oferta { font-size: 14px !important; padding: 3px 10px; }
        .portrait .sidebar { padding: 10px; }
    </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 landscape">📺 TV Horizontal</a>
        <a href="tv.php?modo=portrait" target="_blank" class="btn-tv portrait">📱 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 (Template)</legend>
            <select id="template_style" onchange="atualizarPreview()" style="font-weight:bold; font-size:1.1em; height:45px;">
                <optgroup label="Básicos">
                    <option value="classico">🔴 Clássico (Vermelho)</option>
                    <option value="varejo-azul">🔵 Varejo (Azul)</option>
                    <option value="impacto">🟡 Impacto (Amarelo)</option>
                </optgroup>
                <optgroup label="Segmentos">
                    <option value="padaria">🍞 Padaria (Rústico)</option>
                    <option value="acougue">🥩 Açougue (Sangue)</option>
                    <option value="fresh">🥬 Hortifruti (Verde)</option>
                    <option value="organic">🥕 Orgânico (Kraft)</option>
                    <option value="bebidas">🍺 Bebidas (Gelado)</option>
                    <option value="pharma">💊 Farmácia (Clean)</option>
                </optgroup>
                <optgroup label="Especiais">
                    <option value="premium">💎 Premium (Preto/Gold)</option>
                    <option value="blackfriday">⚫ Black Friday (Neon)</option>
                    <option value="cyber">🎮 Cyber Tech (Roxo)</option>
                </optgroup>
            </select>
        </fieldset>

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

        <div style="display:flex; gap:10px;">
            <div style="flex:1"><label>Preço (R$)</label><input type="text" id="preco" placeholder="0,00" onkeyup="mascaraMoeda(this)" oninput="atualizarPreview()"></div>
            <div style="width:100px;"><label>Unidade</label><input type="text" id="medida" placeholder="Ex: Kg" oninput="atualizarPreview()"></div>
            <div style="flex:1"><label>Validade</label><input type="date" id="data_validade" oninput="atualizarPreview()"></div>
        </div>

        <label>Formato</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</label>
        <div class="btn-mini-group">
            <input type="text" id="imgUrl" placeholder="URL da imagem..." oninput="atualizarPreview()">
            <button class="btn-banco" onclick="abrirBanco('produto')">📂 Arquivos</button>
            <button class="btn-web" onclick="abrirBuscaWeb('produto')">🔍 PNG</button>
            <button class="btn-save-img" onclick="salvarImagemProdutoNoBanco()">💾 Salvar</button>
        </div>
        <label style="display:flex;align-items:center;gap:10px;margin-top:5px;cursor:pointer;"><input type="checkbox" id="check_fundo" onchange="atualizarPreview()"> <span style="font-size:12px;">🪄 Remover Fundo Branco</span></label>

        <label>Logo</label> <input type="text" id="logo_url" oninput="atualizarPreview()">
        <label>Tamanho 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" oninput="atualizarPreview()"><div style="display:flex;gap:10px;"><input type="color" id="extra_cor" value="#ffffff" oninput="atualizarPreview()"><input type="number" id="extra_tamanho" value="40" oninput="atualizarPreview()"></div></fieldset>

        <fieldset><legend>🎨 Fundo</legend>
            <select id="bg_tipo" onchange="alternarInputsBackground()"><option value="padrao">Padrão</option><option value="cor">Cor</option><option value="imagem">Imagem</option></select>
            <div id="box_bg_cor" style="display:none;margin-top:5px;"><input type="color" id="bg_cor_input" oninput="atualizarPreview()"></div>
            <div id="box_bg_imagem" style="display:none;margin-top:5px;">
                <div style="display:flex;gap:5px;margin-bottom:5px;"><input type="text" id="bg_img_input" oninput="atualizarPreview()"></div>
                <div class="btn-mini-group">
                    <button class="btn-banco" onclick="abrirBanco('bg')">📂</button>
                    <button class="btn-web" onclick="abrirBuscaWeb('bg')">🔍</button>
                    <button class="btn-save-img" onclick="salvarBackgroundNoBanco()">💾</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 ARTE (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 (Arraste os elementos)</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-price-container" class="price-container">
                        <span class="currency">R$</span>
                        <span class="amount" id="prev-valor">0,00</span>
                        <span class="unit" id="prev-medida"></span>
                    </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">
    <div class="listagem-header">
        <h3 style="margin:0">📋 Gerenciar Ofertas</h3>
        
        <div style="display:flex; gap:10px; align-items:center;">
            <select id="rowsPerPage" onchange="mudarPagina(1)" style="width:auto; padding:5px; margin:0;">
                <option value="5">5 por página</option>
                <option value="10" selected>10 por página</option>
                <option value="20">20 por página</option>
            </select>
            
            <div class="search-box">
                <span class="search-icon">🔍</span>
                <input type="text" id="searchInput" placeholder="Buscar oferta..." onkeyup="filtrarTabela()" style="margin:0;">
            </div>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Img</th>
                <th>Produto</th>
                <th>Preço</th>
                <th>Ações</th>
            </tr>
        </thead>
        <tbody id="tabelaBody">
            <?php
            $stmt = $pdo->query("SELECT * FROM ofertas ORDER BY id DESC LIMIT 500");
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $json = htmlspecialchars(json_encode($row), ENT_QUOTES, 'UTF-8');
                echo "<tr class='oferta-row'>
                        <td>{$row['id']}</td>
                        <td><img src='{$row['imagem_url']}' style='width:30px;height:30px;object-fit:contain' onerror=\"this.src='https://via.placeholder.com/30?text=?'\"></td>
                        <td class='nome-prod'>{$row['produto']}</td>
                        <td>R$ " . number_format($row['preco'], 2, ',', '.') . " <small style='color:#666'>{$row['medida']}</small></td>
                        <td>
                            <button class='btn-edit' onclick='carregarEdicao($json)' title='Editar'>✏️</button>
                            <a href='excluir.php?id={$row['id']}' class='btn-del' onclick='return confirm(\"Excluir oferta permanentemente?\")' title='Excluir'>🗑️</a>
                        </td>
                      </tr>";
            }
            ?>
        </tbody>
    </table>
    
    <div class="pagination" id="paginacaoControls"></div>
    <div id="infoPaginacao" style="text-align:right; font-size:12px; color:#666; margin-top:5px;"></div>
</div>

<script>
    // VARIAVEIS GLOBAIS
    const modal = document.getElementById('modalBanco');
    const modalPreview = document.getElementById('modalPreview');
    let destinoAtual = 'produto';
    let mapaProdutos = {}; // Agora armazena produto completo (preço + imagem)
    let paginaAtual = 1;
    let linhasAtuais = [];

    // --- TABELA INTELIGENTE ---
    function iniciarTabela() {
        const trs = document.querySelectorAll('#tabelaBody .oferta-row');
        linhasAtuais = Array.from(trs);
        mudarPagina(1);
    }

    function filtrarTabela() {
        const termo = document.getElementById('searchInput').value.toLowerCase();
        const todasLinhas = document.querySelectorAll('#tabelaBody .oferta-row');
        linhasAtuais = [];
        todasLinhas.forEach(tr => {
            const produto = tr.querySelector('.nome-prod').innerText.toLowerCase();
            const id = tr.cells[0].innerText;
            if (produto.includes(termo) || id.includes(termo)) {
                tr.style.display = ''; linhasAtuais.push(tr);
            } else { tr.style.display = 'none'; }
        });
        mudarPagina(1);
    }

    function mudarPagina(pag) {
        const porPagina = parseInt(document.getElementById('rowsPerPage').value);
        const totalLinhas = linhasAtuais.length;
        const totalPaginas = Math.ceil(totalLinhas / porPagina);
        if (pag < 1) pag = 1; if (pag > totalPaginas && totalPaginas > 0) pag = totalPaginas;
        paginaAtual = pag;
        linhasAtuais.forEach(tr => tr.style.display = 'none');
        const inicio = (pag - 1) * porPagina; const fim = inicio + porPagina;
        for (let i = inicio; i < fim && i < totalLinhas; i++) { linhasAtuais[i].style.display = 'table-row'; }
        atualizarControlesPaginacao(totalPaginas);
        const info = document.getElementById('infoPaginacao');
        if(totalLinhas===0) info.innerText = "Nenhum resultado."; else info.innerText = `Exibindo ${Math.min(inicio+1,totalLinhas)} a ${Math.min(fim,totalLinhas)} de ${totalLinhas}.`;
    }

    function atualizarControlesPaginacao(totalPaginas) {
        const div = document.getElementById('paginacaoControls'); div.innerHTML = '';
        if (totalPaginas <= 1) return;
        const btnPrev = document.createElement('button'); btnPrev.className = 'page-btn'; btnPrev.innerText = '«'; btnPrev.disabled = (paginaAtual===1); btnPrev.onclick = () => mudarPagina(paginaAtual - 1); div.appendChild(btnPrev);
        let startPage = Math.max(1, paginaAtual - 2); let endPage = Math.min(totalPaginas, paginaAtual + 2);
        if(startPage > 1) { const b1=document.createElement('button'); b1.className='page-btn'; b1.innerText='1'; b1.onclick=()=>mudarPagina(1); div.appendChild(b1); if(startPage>2){const s=document.createElement('span'); s.innerText='...'; div.appendChild(s);} }
        for (let i = startPage; i <= endPage; i++) { const btn = document.createElement('button'); btn.className = `page-btn ${i===paginaAtual?'active':''}`; btn.innerText = i; btn.onclick = () => mudarPagina(i); div.appendChild(btn); }
        if(endPage < totalPaginas) { if(endPage < totalPaginas-1){const s=document.createElement('span'); s.innerText='...'; div.appendChild(s);} const bLast=document.createElement('button'); bLast.className='page-btn'; bLast.innerText=totalPaginas; bLast.onclick=()=>mudarPagina(totalPaginas); div.appendChild(bLast); }
        const btnNext = document.createElement('button'); btnNext.className = 'page-btn'; btnNext.innerText = '»'; btnNext.disabled = (paginaAtual===totalPaginas); btnNext.onclick = () => mudarPagina(paginaAtual + 1); div.appendChild(btnNext);
    }

    // --- MÁSCARA MOEDA ---
    function mascaraMoeda(i) {
        let v = i.value.replace(/\D/g, "");
        v = (v/100).toFixed(2) + "";
        v = v.replace(".", ",");
        v = v.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
        v = v.replace(/(\d)(\d{3}),/g, "$1.$2,");
        i.value = v;
        atualizarPreview();
    }

    // --- AUTOCOMPLETE INTELIGENTE ---
    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 = ''; mapaProdutos = {};
            lista.forEach(item => {
                // Guarda Preço E Imagem no mapa
                mapaProdutos[item.nome] = { price: item.preco, img: item.imagem_url };
                const opt = document.createElement('option'); opt.value = item.nome; dl.appendChild(opt);
            });
        });
    }

    function preencherProdutoAutomatico(input) {
        const nome = input.value;
        if (mapaProdutos[nome]) {
            // Preenche Preço
            const p = mapaProdutos[nome].price;
            document.getElementById('preco').value = parseFloat(p).toFixed(2).replace('.', ',');
            
            // Preenche Imagem (Se existir)
            if(mapaProdutos[nome].img) {
                document.getElementById('imgUrl').value = mapaProdutos[nome].img;
            }
            
            atualizarPreview();
        }
    }

    // --- ARRASTAR E SOLTAR ---
    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';
    }

    // --- GALERIA E BUSCA ---
    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 = '';
            if(imgs.length === 0) { grid.innerHTML = '<p style="padding:20px">Nada encontrado.</p>'; return; }
            imgs.forEach(img => {
                const d = document.createElement('div'); d.className='gallery-item';
                d.innerHTML=`
                    <button class="btn-trash-img" onclick="excluirImagemBanco(${img.id}, event)">🗑️</button>
                    <button class="btn-zoom-img" onclick="verImagemAmpliada('${img.caminho}', event)">🔍</button>
                    <button class="btn-edit-img" onclick="renomearImagemBanco(${img.id}, '${img.nome_arquivo}', event)">✏️</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);
            });
        }).catch(err => { grid.innerHTML = '<p style="padding:20px">Erro ao carregar.</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)">🔍</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();
    }

    // --- UPLOAD / EXCLUIR / SALVAR / RENOMEAR ---
    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.querySelectorAll('.btn-save-img')[1]; btn.innerText="..."; 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.querySelectorAll('.btn-save-img')[0]; 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="💾 Salvar"; btn.disabled=false;
        });
    }

    // --- FUNÇÃO BLINDADA DE DOWNLOAD ---
    function baixarImagem() {
        const frame = document.getElementById('tv-frame');
        const btn = document.querySelector('.success[onclick="baixarImagem()"]');
        const textoOriginal = btn ? btn.innerText : "⬇️ BAIXAR ARTE (PNG)";
        
        if(btn) { btn.innerText = "📸 Processando..."; btn.disabled = true; }

        setTimeout(() => {
            html2canvas(frame, {
                scale: 3,                // Melhora a resolução (HD)
                useCORS: true,           // Permite imagens locais/externas
                allowTaint: false,       // IMPORTANTE: Deve ser false para baixar
                backgroundColor: null,   // Mantém transparência se houver
                logging: false,          // Desativa logs no console
                imageTimeout: 0,         // Espera a imagem carregar
                removeContainer: true    // Limpa lixo de memória
            }).then(canvas => {
                const link = document.createElement('a');
                let nomeProd = document.getElementById('produto').value || 'oferta';
                nomeProd = nomeProd.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-zA-Z0-9]/g, "_").toLowerCase();
                link.download = 'arte_' + nomeProd + '.png';
                link.href = canvas.toDataURL("image/png");
                link.click();
                if(btn) { btn.innerText = textoOriginal; btn.disabled = false; }
            }).catch(err => {
                console.error("Erro html2canvas:", err);
                alert("Não foi possível gerar a imagem.\n\nMotivo mais provável: A imagem do produto tem um formato inválido ou bloqueio de segurança.\n\nTente usar outra imagem salva.");
                if(btn) { btn.innerText = "❌ Erro"; setTimeout(() => { btn.innerText = textoOriginal; btn.disabled = false; }, 2000); }
            });
        }, 100);
    }

    // --- UI E PREVIEW ---
    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 = document.getElementById('preco').value || "0,00";
        const med = document.getElementById('medida').value;
        
        document.getElementById('prev-titulo').innerText = p;
        document.getElementById('prev-valor').innerText = val;
        
        const medDisplay = med ? (med.includes('/') ? med : '/'+med) : ''; 
        document.getElementById('prev-medida').innerText = medDisplay;

        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);
        
        const imgEl = document.getElementById('prev-img');
        imgEl.src = img ? img : 'https://via.placeholder.com/300?text=Sem+Imagem';
        if(document.getElementById('check_fundo').checked) imgEl.classList.add('modo-multiply'); else imgEl.classList.remove('modo-multiply');
        
        const ix = document.getElementById('img_pos_x').value; const iy = document.getElementById('img_pos_y').value;
        if(ix === 'center') { imgEl.style.left='50%'; imgEl.style.top='50%'; imgEl.style.transform='translate(-50%,-50%)'; }
        else { imgEl.style.left=ix; imgEl.style.top=iy; 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 valDt = document.getElementById('data_validade').value;
        if(valDt) { const d = valDt.split('-'); document.getElementById('prev-validade').innerText = `Válido até ${d[2]}/${d[1]}`; }
        else document.getElementById('prev-validade').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 carregarEdicao(d) {
        document.getElementById('id_oferta').value=d.id;
        document.getElementById('produto').value=d.produto;
        document.getElementById('preco').value=parseFloat(d.preco).toFixed(2).replace('.',',');
        document.getElementById('medida').value=d.medida || '';
        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';
        
        document.getElementById('img_pos_x').value = d.img_pos_x || 'center';
        document.getElementById('img_pos_y').value = d.img_pos_y || 'center';
        
        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 = ''; }
        }
        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);
        // VALOR PURO (EX: 4,49)
        fd.append('preco', document.getElementById('preco').value);
        fd.append('medida', document.getElementById('medida').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(); }

    window.addEventListener('load', iniciarTabela);
    alternarInputsBackground(); atualizarPreview();
</script>
</body>
</html>