<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso Denegado"); }

$idu_sesion = $_SESSION['IDUg'] ?? 'ANONIMO'; 
$nombre_bd  = "MS_Datos";
$idu=$idu_sesion;
?>

<style>
    :root { --accent: #6366f1; --bg: #f1f5f9; }
    body { background-color: var(--bg); font-family: 'Poppins', sans-serif; margin: 0; }
    
    /* Ocupar todo el ancho disponible */
    .main-wrapper { width: 100%; padding: 15px; box-sizing: border-box; }
    .editor-grid { 
        display: grid; 
        grid-template-columns: 1fr 400px; /* El formulario se expande, el preview queda fijo */
        gap: 20px; 
        align-items: start;
    }

    .panel-glass { 
        background: white; 
        border-radius: 24px; 
        padding: 30px; 
        box-shadow: 0 4px 15px rgba(0,0,0,0.05); 
        border: 1px solid #e2e8f0; 
    }
    
    .section-header { 
        font-size: 0.75rem; font-weight: 800; color: var(--accent); 
        text-transform: uppercase; letter-spacing: 1.5px; 
        margin: 25px 0 15px; display: flex; align-items: center;
        background: #f8fafc; padding: 12px 20px; border-radius: 12px;
    }
    
    .form-custom { border-radius: 12px; border: 1px solid #cbd5e1; padding: 12px; font-size: 0.85rem; width: 100%; transition: 0.3s; }
    .form-custom:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1); }
    
    .color-box { height: 45px; padding: 5px; cursor: pointer; border-radius: 10px; }
    
    /* Mockup y Preview Area */
    .preview-side { position: sticky; top: 20px; }
    .mockup-phone { 
        width: 340px; height: 620px; background: #0f172a; border: 12px solid #1e293b; 
        border-radius: 50px; overflow: hidden; margin: 0 auto; 
        box-shadow: 0 30px 60px rgba(0,0,0,0.4); 
    }

    /* Contenedor QR debajo del Celular */
    .qr-container {
        background: white; margin-top: 20px; padding: 20px; border-radius: 20px;
        border: 1px solid #e2e8f0; text-align: center; box-shadow: 0 10px 20px rgba(0,0,0,0.05);
    }
    #qrcode_preview img { margin: 0 auto; border-radius: 12px; border: 4px solid #f8fafc; }
</style>

<div class="main-wrapper">
    <div class="editor-grid">
        
        <div class="main-editor">
            <div class="panel-glass mb-4 d-flex align-items-center justify-content-between">
                <select id="sel_lista" class="form-custom font-weight-bold text-primary w-75" onchange="gestionarSeleccion(this.value)">
                    <option value="NEW">+ CREAR NUEVA IDENTIDAD</option>
                </select>
                <div class="text-right ml-3">
                    <small class="font-weight-bold text-muted uppercase">Token Activo</small>
                    <input type="text" id="t_token" class="border-0 font-weight-bold text-primary text-right" style="width:120px; background:transparent;" readonly>
                </div>
            </div>

            <div class="panel-glass">
                <form id="form_premium">
                    <input type="hidden" id="idt_actual">
                    
                    <div class="row align-items-end">
                        <div class="col-md-9">
                            <label class="small font-weight-bold text-muted uppercase">Nombre del Titular o Marca</label>
                            <input type="text" id="p_titular" class="form-custom" placeholder="Ej. Juan Pérez" onkeyup="updatePreview()">
                        </div>
                        <div class="col-md-3">
                            <label class="small font-weight-bold">Estado</label>
                            <select id="t_estado" class="form-custom"><option>Activa</option><option>Inactiva</option></select>
                        </div>
                    </div>

                    <div class="section-header"><i class="fas fa-magic mr-2"></i> 1. Identidad Visual, Estilo y Colores</div>
                    <div class="row mb-4">
                        <div class="col-md-3"><label class="small font-weight-bold">Fondo App</label><input type="color" id="p_color_bg" class="form-custom color-box" value="#0f172a" oninput="updatePreview()"></div>
                        <div class="col-md-3"><label class="small font-weight-bold">Acento 1</label><input type="color" id="p_color_1" class="form-custom color-box" value="#6366f1" oninput="updatePreview()"></div>
                        <div class="col-md-3"><label class="small font-weight-bold">Acento 2</label><input type="color" id="p_color_2" class="form-custom color-box" value="#a855f7" oninput="updatePreview()"></div>
                        <div class="col-md-3">
                            <label class="small font-weight-bold">Efecto Fondo</label>
                            <select id="p_efecto" class="form-custom" onchange="updatePreview()">
                                <option value="0">Red Neuronal</option>
                                <option value="1">Nieve</option>
                                <option value="2">Polígonos</option>
                                <option value="3">Bokeh</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3"><input type="text" id="p_puesto" class="form-custom" placeholder="Cargo Profesional / Descripción corta" onkeyup="updatePreview()"></div>
                        <div class="col-md-6 mb-3"><input type="text" id="p_foto" class="form-custom" placeholder="URL de tu Foto de Perfil (Avatar)" onchange="updatePreview()"></div>
                        <div class="col-md-12"><input type="text" id="p_slogan" class="form-custom" placeholder="Slogan o frase de impacto profesional" onkeyup="updatePreview()"></div>
                    </div>

                    <div class="section-header"><i class="fas fa-comment-dots mr-2"></i> 2. Canales de Comunicación Directa</div>
                    <div class="row">
                        <div class="col-md-4 mb-3"><input type="text" id="c_wa" class="form-custom" placeholder="WhatsApp (Ej: 521...)" onkeyup="updatePreview()"></div>
                        <div class="col-md-4 mb-3"><input type="text" id="c_email" class="form-custom" placeholder="Correo Electrónico" onkeyup="updatePreview()"></div>
                        <div class="col-md-4 mb-3"><input type="text" id="c_web" class="form-custom" placeholder="Sitio Web o Portafolio" onkeyup="updatePreview()"></div>
                    </div>

                    <div class="section-header"><i class="fas fa-university mr-2"></i> 3. Información para Pagos y Transferencias</div>
                    <div class="row">
                        <div class="col-md-4 mb-3"><input type="text" id="b_banco" class="form-custom" placeholder="Nombre del Banco" onkeyup="updatePreview()"></div>
                        <div class="col-md-4 mb-3"><input type="text" id="b_titular" class="form-custom" placeholder="Titular de la Cuenta" onkeyup="updatePreview()"></div>
                        <div class="col-md-4 mb-3"><input type="text" id="b_clabe" class="form-custom" placeholder="Número CLABE (18 dígitos)" onkeyup="updatePreview()"></div>
                    </div>

                    <button type="button" class="btn btn-primary btn-block btn-lg mt-5 shadow-lg font-weight-bold py-3" onclick="guardarTodo()">
                        <i class="fas fa-save mr-2"></i> GUARDAR Y ACTUALIZAR IDENTIDAD DIGITAL
                    </button>
                </form>
            </div>
        </div>

        <div class="preview-side">
            <div class="mockup-phone">
                <iframe id="frame_preview" src="about:blank" style="width:100%; height:100%; border:none;"></iframe>
            </div>

            <div class="qr-container">
                <p class="small font-weight-bold text-muted uppercase mb-3">Escanea para Probar</p>
                <div id="qrcode_preview"></div>
                <p class="text-[9px] font-mono text-primary mt-2" id="url_label">?id=<?php echo $idu_sesion; ?>&t=...</p>
                <button class="btn btn-sm btn-outline-secondary mt-2 border-0" onclick="descargarQR()">
                    <i class="fas fa-download"></i> Bajar QR
                </button>
            </div>
        </div>

    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

<script>
    const DB = "<?php echo $nombre_bd; ?>";
    const IDU_USER = "<?php echo $idu_sesion; ?>";
    let qrInstancia = null;

    document.addEventListener('DOMContentLoaded', () => {
        cargarLista();
        generarToken();
        updatePreview();
    });

    async function cargarLista(idToSelect = null) {
        const sql = `SELECT IDT, Titular, Token FROM \`<?php echo $idu;?>-Tarjetas\` WHERE IDU = '${IDU_USER}' ORDER BY IDT DESC`;
        const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB}` }).then(r => r.json());
        const sel = document.getElementById('sel_lista');
        sel.innerHTML = '<option value="NEW">+ CREAR NUEVA IDENTIDAD</option>';
        if(res.data) res.data.forEach(t => { sel.innerHTML += `<option value="${t.IDT}">${t.Titular} (${t.Token})</option>`; });
        if(idToSelect) sel.value = idToSelect;
    }

    function gestionarSeleccion(val) { (val === 'NEW') ? nuevaTarjeta() : cargarDetalle(val); }

    function nuevaTarjeta() {
        document.getElementById('form_premium').reset();
        document.getElementById('idt_actual').value = "";
        generarToken();
        updatePreview();
    }

    async function cargarDetalle(idt) {
        const sql = `SELECT * FROM \`<?php echo $idu;?>-Tarjetas\` WHERE IDT = ${idt} LIMIT 1`;
        const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB}` }).then(r => r.json());
        if(res.data && res.data[0]) {
            const d = res.data[0];
            const p = JSON.parse(d.Datos_Perfil);
            const c = JSON.parse(d.Datos_Contacto);
            const b = JSON.parse(d.Datos_Pagos);

            document.getElementById('idt_actual').value = d.IDT;
            document.getElementById('t_token').value = d.Token;
            document.getElementById('p_titular').value = d.Titular;
            document.getElementById('t_estado').value = d.Estado;
            document.getElementById('p_puesto').value = p.puesto || '';
            document.getElementById('p_slogan').value = p.slogan || '';
            document.getElementById('p_foto').value = p.foto || '';
            document.getElementById('p_efecto').value = p.efecto || 0;
            document.getElementById('p_color_bg').value = p.color_bg || '#0f172a';
            document.getElementById('p_color_1').value = p.color_1 || '#6366f1';
            document.getElementById('p_color_2').value = p.color_2 || '#a855f7';
            document.getElementById('c_wa').value = c.wa || '';
            document.getElementById('c_email').value = c.email || '';
            document.getElementById('c_web').value = c.web || '';
            document.getElementById('b_banco').value = b.banco || '';
            document.getElementById('b_titular').value = b.titular || '';
            document.getElementById('b_clabe').value = b.clabe || '';
            updatePreview();
        }
    }

    function generarToken() {
        if(document.getElementById('idt_actual').value !== "") return;
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let token = '';
        for (let i = 0; i < 11; i++) { token += chars.charAt(Math.floor(Math.random() * chars.length)); }
        document.getElementById('t_token').value = token;
    }

    function updatePreview() {
        const v = {
            n: document.getElementById('p_titular').value || 'Nombre Titular',
            p: document.getElementById('p_puesto').value || 'Profesión',
            f: document.getElementById('p_foto').value || 'https://via.placeholder.com/150',
            bg: document.getElementById('p_color_bg').value,
            c1: document.getElementById('p_color_1').value,
            c2: document.getElementById('p_color_2').value,
            b: document.getElementById('b_banco').value || 'BANCO',
            cl: document.getElementById('b_clabe').value || 'CLABE...'
        };

        const html = `<html><head><script src="https://cdn.tailwindcss.com"><\/script></head>
        <body class="flex items-center justify-center h-full m-0" style="background:${v.bg}; overflow:hidden;">
            <div class="w-10/12 text-center text-white p-8 rounded-[2.5rem] shadow-2xl relative" style="background:rgba(255,255,255,0.03); backdrop-filter:blur(20px); border:1px solid rgba(255,255,255,0.1)">
                <img src="${v.f}" class="w-24 h-24 rounded-full mx-auto -mt-20 border-4 object-cover" style="border-color:${v.c1}">
                <h2 class="text-2xl font-bold mt-5 tracking-tight">${v.n}</h2>
                <p class="text-[10px] uppercase tracking-[4px] font-black mt-1" style="color:${v.c1}">${v.p}</p>
                <button class="w-full py-4 rounded-2xl mt-8 text-xs font-bold uppercase tracking-widest" style="background:linear-gradient(135deg, ${v.c1}aa, ${v.c2}aa); border:1px solid rgba(255,255,255,0.2)">Guardar Contacto</button>
                <div class="mt-8 p-4 rounded-2xl border text-left" style="background:rgba(255,255,255,0.05); border-color:rgba(255,255,255,0.1)">
                    <p class="text-[8px] font-bold uppercase mb-1" style="color:${v.c1}">Datos Bancarios</p>
                    <p class="text-xs font-bold">${v.b}</p>
                    <p class="text-[10px] font-mono opacity-60">${v.cl}</p>
                </div>
            </div>
        </body></html>`;
        document.getElementById('frame_preview').contentWindow.document.open();
        document.getElementById('frame_preview').contentWindow.document.write(html);
        document.getElementById('frame_preview').contentWindow.document.close();

        // ACTUALIZAR QR
        const token = document.getElementById('t_token').value;
        const fullURL ="http://167.172.224.160/MS/P/TarjetP.php?id=" + IDU_USER + "&t=" + token;
        document.getElementById('url_label').innerText = "?id=" + IDU_USER + "&t=" + token;
        document.getElementById('qrcode_preview').innerHTML = "";
        qrInstancia = new QRCode(document.getElementById("qrcode_preview"), { text: fullURL, width: 140, height: 140 });
    }

    async function guardarTodo() {
        const idt = document.getElementById('idt_actual').value;
        const token = document.getElementById('t_token').value;
        const titular = document.getElementById('p_titular').value || 'Sin Nombre';
        const p = { puesto: document.getElementById('p_puesto').value, slogan: document.getElementById('p_slogan').value, foto: document.getElementById('p_foto').value, efecto: document.getElementById('p_efecto').value, color_bg: document.getElementById('p_color_bg').value, color_1: document.getElementById('p_color_1').value, color_2: document.getElementById('p_color_2').value };
        const c = { wa: document.getElementById('c_wa').value, email: document.getElementById('c_email').value, web: document.getElementById('c_web').value };
        const b = { banco: document.getElementById('b_banco').value, titular: document.getElementById('b_titular').value, clabe: document.getElementById('b_clabe').value };
        let sql = idt ? `UPDATE \`<?php echo $idu;?>-Tarjetas\` SET Token='${token}', Titular='${titular}', Datos_Perfil='${JSON.stringify(p)}', Datos_Contacto='${JSON.stringify(c)}', Datos_Pagos='${JSON.stringify(b)}' WHERE IDT=${idt}` : `INSERT INTO \`<?php echo $idu;?>-Tarjetas\` (IDU, Token, Titular, Datos_Perfil, Datos_Contacto, Datos_Pagos) VALUES ('${IDU_USER}', '${token}', '${titular}', '${JSON.stringify(p)}', '${JSON.stringify(c)}', '${JSON.stringify(b)}')`;
        const res = await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB}` }).then(r => r.json());
        if(res.status === 'OK') { alert("Identidad Digital Actualizada"); cargarLista(idt || res.last_id); }
    }

    function descargarQR() {
        const img = document.querySelector("#qrcode_preview img");
        if(!img) return;
        const a = document.createElement("a");
        a.href = img.src;
        a.download = "QR_Identidad_" + document.getElementById('t_token').value + ".png";
        a.click();
    }
</script>