<?php
session_start();
require_once "../librerias/Conexion.php";

// 1. CONFIGURACIÓN DE CONEXIÓN
$db_name = "MS_Datos";
$db = new Conexion($db_name);
 

// 2. CAPTURA DE VARIABLES (Identificación por ID de Usuario y Token)
$id_user = $_GET['id'] ?? ''; // El IDU del dueño
$token   = $_GET['t']  ?? ''; // El Token de la tarjeta
$prefix = $id_user;

if (empty($id_user) || empty($token)) {
    die("Acceso denegado: Parámetros incompletos.");
}

// 3. CONSULTA SEGURA
// Validamos que el Token pertenezca específicamente al IDU proporcionado
$sql = "SELECT * FROM `{$prefix}-Tarjetas` 
        WHERE IDU = '$id_user' 
        AND Token = '$token' 
        AND Estado = 'Activa' 
        LIMIT 1";
//print_r($sql);
$res = $db->obtenerDatos($sql);
$data = $res['data'][0] ?? null;

if (!$data) {
    die("Identidad no encontrada o inactiva.");
}

// 4. DECODIFICACIÓN DE BLOQUES JSON
$perfil   = json_decode($data['Datos_Perfil'], true)   ?? [];
$contacto = json_decode($data['Datos_Contacto'], true) ?? [];
$pagos    = json_decode($data['Datos_Pagos'], true)    ?? [];

// Variables de Diseño y Contenido
$titular  = $data['Titular'];
$puesto   = $perfil['puesto'] ?? '';
$slogan   = $perfil['slogan'] ?? '';
$foto     = $perfil['foto']   ?? '';
$efecto   = $perfil['efecto'] ?? 0;
$c_bg     = $perfil['color_bg'] ?? '#0f172a';
$c_1      = $perfil['color_1']  ?? '#6366f1';
$c_2      = $perfil['color_2']  ?? '#a855f7';
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $titular; ?> | Digital ID</title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">

    <style>
        :root {
            --bg-main: <?php echo $c_bg; ?>;
            --accent: <?php echo $c_1; ?>;
            --accent-2: <?php echo $c_2; ?>;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-main);
            overflow: hidden; margin: 0; height: 100vh;
            display: flex; align-items: center; justify-content: center;
        }

        #particles-js { position: absolute; width: 100%; height: 100%; z-index: 1; }

        .glass-card {
            background: rgba(255, 255, 255, 0.03);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.15);
            border-radius: 24px;
            z-index: 10;
            box-shadow: 0 30px 60px -15px rgba(0, 0, 0, 0.6);
        }

        .btn-action {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .btn-action:hover {
            background: rgba(255, 255, 255, 0.15);
            transform: translateY(-4px);
        }

        .btn-whatsapp {
            background: rgba(37, 211, 102, 0.15);
            border: 1px solid rgba(37, 211, 102, 0.3);
            color: #4ade80;
        }

        .btn-save-contact {
            background: linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%);
            border: 1px solid rgba(255, 255, 255, 0.2);
            font-weight: 600;
        }

        .modal {
            display: none; position: fixed; inset: 0;
            background: rgba(0,0,0,0.85); backdrop-filter: blur(5px);
            z-index: 50; align-items: center; justify-content: center;
        }
    </style>
</head>
<body>

    <div id="particles-js"></div>

    <div class="glass-card p-6 sm:p-8 w-full max-w-md text-white text-center m-4 relative">
        <div class="absolute top-0 inset-x-0 h-px bg-gradient-to-r from-transparent via-white/30 to-transparent"></div>
        
        <div class="relative w-24 h-24 mx-auto mb-4 group">
             <div class="absolute inset-0 rounded-full blur-xl opacity-40 animate-pulse" style="background: var(--accent)"></div>
            <img src="<?php echo $foto; ?>" class="relative rounded-full border-[3px] border-white/30 object-cover w-full h-full shadow-xl z-10">
        </div>

        <h1 class="text-3xl font-bold mb-1 tracking-tight"><?php echo $titular; ?></h1>
        <p class="font-medium mb-6 tracking-wider uppercase text-xs" style="color: var(--accent)"><?php echo $puesto; ?></p>

        <div class="grid grid-cols-3 gap-3 mb-6">
            <a href="https://wa.me/<?php echo $contacto['wa']; ?>" target="_blank" class="btn-action btn-whatsapp p-4 rounded-2xl flex flex-col items-center justify-center">
                <i class="fa-brands fa-whatsapp text-2xl"></i>
                <span class="text-[10px] font-bold uppercase mt-1">Chat</span>
            </a>
            <button onclick="showQR()" class="btn-action p-4 rounded-2xl flex flex-col items-center justify-center">
                <i class="fa-solid fa-qrcode text-xl opacity-80"></i>
                <span class="text-[10px] font-bold uppercase mt-1">QR</span>
            </button>
            <button onclick="showBank()" class="btn-action p-4 rounded-2xl flex flex-col items-center justify-center">
                <i class="fa-solid fa-building-columns text-xl opacity-80"></i>
                <span class="text-[10px] font-bold uppercase mt-1">Banco</span>
            </button>
            <a href="tel:<?php echo $contacto['wa']; ?>" class="btn-action p-4 rounded-2xl flex flex-col items-center justify-center">
                <i class="fa-solid fa-phone text-xl opacity-80"></i>
                <span class="text-[10px] font-bold uppercase mt-1">Llamar</span>
            </a>
            <a href="mailto:<?php echo $contacto['email']; ?>" class="btn-action p-4 rounded-2xl flex flex-col items-center justify-center">
                <i class="fa-solid fa-envelope text-xl opacity-80"></i>
                <span class="text-[10px] font-bold uppercase mt-1">Email</span>
            </a>
            <a href="<?php echo $contacto['web']; ?>" target="_blank" class="btn-action p-4 rounded-2xl flex flex-col items-center justify-center">
                <i class="fa-solid fa-globe text-xl opacity-80"></i>
                <span class="text-[10px] font-bold uppercase mt-1">Web</span>
            </a>
        </div>

        <button onclick="downloadVCard()" class="btn-action btn-save-contact w-full py-4 rounded-2xl mb-4 flex items-center justify-center gap-3">
            <i class="fa-solid fa-user-plus text-lg"></i>
            <span>Guardar en Contactos</span>
        </button>

        <p class="text-gray-400 text-[10px] uppercase tracking-widest opacity-50 font-bold">"<?php echo $slogan; ?>"</p>
    </div>

    <div id="modal-qr" class="modal" onclick="closeModals()">
        <div class="glass-card p-8 text-center max-w-xs w-full mx-4" onclick="event.stopPropagation()">
            <h3 class="text-white mb-4 font-semibold">Compartir Contacto</h3>
            <div id="qrcode" class="flex justify-center"></div>
            <button onclick="closeModals()" class="mt-6 py-2 px-6 bg-white/10 rounded-full text-xs">Cerrar</button>
        </div>
    </div>

    <div id="modal-bank" class="modal" onclick="closeModals()">
        <div class="glass-card p-8 text-white max-w-sm w-full mx-4 text-left" onclick="event.stopPropagation()">
            <div class="flex items-center mb-6" style="color: var(--accent)">
                <i class="fa-solid fa-vault text-2xl mr-3"></i>
                <h3 class="font-bold text-lg">Datos Bancarios</h3>
            </div>
            <div class="space-y-4 bg-white/5 p-4 rounded-xl border border-white/10 font-mono text-sm">
                <div><p class="text-[10px] opacity-50">BANCO</p><p><?php echo $pagos['banco']; ?></p></div>
                <div><p class="text-[10px] opacity-50">CLABE</p><p class="select-all"><?php echo $pagos['clabe']; ?></p></div>
                <div><p class="text-[10px] opacity-50">TITULAR</p><p><?php echo $pagos['titular'] ?? $titular; ?></p></div>
            </div>
            <button onclick="closeModals()" class="mt-6 w-full py-3 bg-white/10 rounded-xl text-xs font-bold">Cerrar</button>
        </div>
    </div>

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

    <script>
        // --- TUS FÍSICAS ORIGINALES ---
        const configClassic = {"particles":{"number":{"value":80,"density":{"enable":true,"value_area":800}},"color":{"value":"#ffffff"},"shape":{"type":"circle"},"opacity":{"value":0.5,"random":false},"size":{"value":3,"random":true},"line_linked":{"enable":true,"distance":150,"color":"#ffffff","opacity":0.25,"width":1},"move":{"enable":true,"speed":2,"direction":"none","random":false,"straight":false,"out_mode":"out"}},"interactivity":{"detect_on":"canvas","events":{"onhover":{"enable":true,"mode":"grab"},"onclick":{"enable":true,"mode":"push"}}}};
        const configSnow = {"particles":{"number":{"value":100,"density":{"enable":true,"value_area":800}},"color":{"value":"#a5b4fc"},"shape":{"type":"circle"},"opacity":{"value":0.6,"random":true},"size":{"value":4,"random":true},"line_linked":{"enable":false},"move":{"enable":true,"speed":1,"direction":"bottom","random":true,"straight":false,"out_mode":"out"}},"interactivity":{"detect_on":"canvas","events":{"onhover":{"enable":true,"mode":"bubble"},"onclick":{"enable":true,"mode":"repulse"}},"modes":{"bubble":{"distance":200,"size":6,"duration":2,"opacity":0.8},"repulse":{"distance":200}}}};
        const configPolygons = {"particles":{"number":{"value":50},"color":{"value":"#60a5fa"},"shape":{"type":"polygon","polygon":{"nb_sides":6}},"opacity":{"value":0.5},"size":{"value":5,"random":true},"line_linked":{"enable":true,"distance":180,"color":"#60a5fa","opacity":0.3,"width":1},"move":{"enable":true,"speed":4,"direction":"none","random":true,"out_mode":"bounce"}},"interactivity":{"detect_on":"canvas","events":{"onhover":{"enable":true,"mode":"repulse"},"onclick":{"enable":true,"mode":"push"}}}};
        const configBokeh = {"particles":{"number":{"value":30,"density":{"enable":true,"value_area":800}},"color":{"value":["#ec4899", "#8b5cf6", "#3b82f6"]},"shape":{"type":"circle"},"opacity":{"value":0.3,"random":true},"size":{"value":15,"random":true},"line_linked":{"enable":false},"move":{"enable":true,"speed":0.8,"direction":"top","random":true,"straight":false,"out_mode":"out"}},"interactivity":{"detect_on":"canvas","events":{"onhover":{"enable":true,"mode":"bubble"},"onclick":{"enable":true,"mode":"repulse"}},"modes":{"bubble":{"distance":250,"size":20,"duration":2,"opacity":0.6}}}};
        const configVoid = {"particles":{"number":{"value":40},"color":{"value":"#ffffff"},"shape":{"type":"edge"},"opacity":{"value":0.8},"size":{"value":2},"line_linked":{"enable":true,"distance":120,"color":"#ffffff","opacity":0.1,"width":1},"move":{"enable":true,"speed":1,"direction":"none","random":true,"out_mode":"out"}},"interactivity":{"detect_on":"canvas","events":{"onhover":{"enable":true,"mode":"repulse"},"onclick":{"enable":true,"mode":"push"}},"modes":{"repulse":{"distance":150,"duration":0.4}}}};

        const configs = [configClassic, configSnow, configPolygons, configBokeh, configVoid];
        particlesJS('particles-js', configs[<?php echo (int)$efecto; ?>]);

        function downloadVCard() {
            const name = "<?php echo addslashes($titular); ?>";
            const job = "<?php echo addslashes($puesto); ?>";
            const phone = "<?php echo addslashes($contacto['wa']); ?>";
            const email = "<?php echo addslashes($contacto['email']); ?>";
            const web = "<?php echo addslashes($contacto['web']); ?>";
            const note = "<?php echo addslashes($slogan); ?>";

            const vCardData = [
                "BEGIN:VCARD",
                "VERSION:3.0",
                "FN:" + name,
                "N:;" + name + ";;;",
                "TITLE:" + job,
                "TEL;TYPE=CELL;TYPE=VOICE;TYPE=pref:" + phone,
                "EMAIL;TYPE=WORK;INTERNET:" + email,
                "URL:" + web,
                "NOTE:" + note,
                "REV:" + new Date().toISOString(),
                "END:VCARD"
            ].join("\n");

            const blob = new Blob([vCardData], { type: "text/vcard;charset=utf-8" });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = name.replace(/\s+/g, '_') + ".vcf";
            document.body.appendChild(a);
            a.click();
            setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 100);
        }

        // GENERACIÓN DE QR CON ID Y TOKEN
        const fullURL = window.location.origin + window.location.pathname + "?id=<?php echo $id_user; ?>&t=<?php echo $token; ?>";
        new QRCode(document.getElementById("qrcode"), { text: fullURL, width: 160, height: 160 });

        function showQR() { document.getElementById('modal-qr').style.display = 'flex'; }
        function showBank() { document.getElementById('modal-bank').style.display = 'flex'; }
        function closeModals() { document.querySelectorAll('.modal').forEach(m => m.style.display = 'none'); }
    </script>
</body>
</html>