<?php 
include 'header.php'; 

// ডাটাবেজ থেকে ইমোটগুলো নিয়ে আসা
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$query = "SELECT * FROM items";
if ($search != '') {
    $query .= " WHERE title LIKE '%$search%' OR tags LIKE '%$search%' OR code LIKE '%$search%' 
                ORDER BY (CASE WHEN title LIKE '$search%' THEN 1 ELSE 2 END), sort_order ASC, id DESC";
} else { 
    $query .= " ORDER BY sort_order ASC, id DESC"; 
}
$result = $conn->query($query);
?>

<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 md:py-12">
    
    <!-- STEP 1: CONFIGURATION (App-like Centered Card) -->
    <div id="step1" class="step-active flex items-center justify-center min-h-[60vh] md:min-h-[70vh]">
        <div class="bg-[#0d1117] p-6 md:p-10 rounded-[32px] border border-gray-800 w-full max-w-[400px] shadow-2xl transition-all">
            <div class="text-center mb-8">
                <div class="inline-block p-3 bg-cyan-500/10 rounded-2xl mb-4">
                    <i class="fas fa-sliders-h text-cyan-500 text-xl"></i>
                </div>
                <h2 class="text-xl font-bold uppercase tracking-[2px] text-white">Config Data</h2>
                <p class="text-[10px] text-gray-500 mt-1 uppercase">Setup team and UID details</p>
            </div>

            <div class="space-y-5">
                <!-- Player Selector -->
                <div class="relative">
                    <select id="playerCount" onchange="generateUIDFields()" class="input-box appearance-none cursor-pointer">
                        <option value="1">1 Player (Solo)</option>
                        <option value="2">2 Players (Duo)</option>
                        <option value="3">3 Players (Trio)</option>
                        <option value="4">4 Players (Squad)</option>
                    </select>
                    <i class="fas fa-chevron-down absolute right-4 top-4 text-gray-500 pointer-events-none text-xs"></i>
                </div>

                <!-- UID Container -->
                <div id="uidContainer" class="space-y-4">
                    <div class="relative group">
                        <input type="number" id="uid_1" placeholder="Enter Player 1 UID" class="uid-input input-box pr-12 focus:border-cyan-500 transition-all">
                        <button onclick="pasteToField('uid_1')" class="absolute right-0 top-0 h-full w-12 flex items-center justify-center text-cyan-500 hover:text-cyan-300 transition-colors border-l border-gray-800 group-focus-within:border-cyan-500">
                            <i class="fas fa-paste"></i>
                        </button>
                    </div>
                </div>

                <!-- Team Code -->
                <div class="relative group">
                    <input type="number" id="teamCode" placeholder="Enter Team Code" class="input-box pr-12 focus:border-cyan-500 transition-all">
                    <button onclick="pasteToField('teamCode')" class="absolute right-0 top-0 h-full w-12 flex items-center justify-center text-cyan-500 hover:text-cyan-300 transition-colors border-l border-gray-800 group-focus-within:border-cyan-500">
                        <i class="fas fa-paste"></i>
                    </button>
                </div>

                <!-- Confirm Button -->
                <button onclick="generateEmoteList()" class="w-full bg-[#00d2ff] text-black font-black py-4 rounded-2xl uppercase tracking-wider hover:scale-[1.02] active:scale-95 transition-all shadow-lg shadow-cyan-500/20 text-sm mt-4">
                    Confirm & Proceed <i class="fas fa-bolt ml-1"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- STEP 2: EMOTE LIST (Perfect Responsive Grid) -->
    <div id="step2" class="step-hidden">
        <!-- Search Bar -->
        <div class="mb-10 max-w-xl mx-auto px-2">
            <div class="relative group">
                <input type="text" id="searchInput" onkeyup="filterItems()" placeholder="Search your emote..." class="w-full bg-[#0d1117] border border-gray-800 rounded-2xl py-4 px-6 outline-none focus:border-cyan-500 text-sm transition-all shadow-xl">
                <i class="fas fa-search absolute right-6 top-4.5 text-gray-600 group-focus-within:text-cyan-500 transition-colors"></i>
            </div>
        </div>

        <!-- Grid -->
        <div class="emote-grid">
            <?php while($row = $result->fetch_assoc()): ?>
            <div class="neon-border rounded-[28px] overflow-hidden flex flex-col emote-item group transition-all duration-300 hover:border-cyan-500/40 hover:-translate-y-1 shadow-lg" data-title="<?php echo strtolower($row['title']); ?>">
                <input type="hidden" class="base-emote-code" value="<?php echo $row['code']; ?>">
                
                <!-- Click Image to Copy -->
                <div class="relative cursor-pointer aspect-square overflow-hidden" onclick="copyDynamic(this.closest('.emote-item'))">
                    <img src="<?php echo $row['image_path']; ?>" class="w-full h-full object-cover opacity-85 group-hover:opacity-100 group-hover:scale-105 transition-all duration-500">
                    <div class="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                        <span class="bg-white/90 backdrop-blur-md text-black text-[10px] font-black px-5 py-2 rounded-full uppercase italic tracking-tighter">Copy Code</span>
                    </div>
                </div>

                <div class="p-5 text-center flex-grow flex flex-col justify-between">
                    <div>
                        <h3 class="text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2 truncate"><?php echo htmlspecialchars($row['title']); ?></h3>
                        <div onclick="copyDynamic(this.closest('.emote-item'))" class="cursor-pointer active:scale-95 transition-transform mb-3 inline-block w-full">
                            <span class="display-code font-mono font-black text-xs md:text-sm break-all leading-relaxed" style="color: <?php echo $settings['code_color']; ?>;">
                                <?php echo $row['code']; ?>
                            </span>
                        </div>
                    </div>
                    <p class="text-[9px] leading-tight opacity-50 font-medium" style="color: <?php echo $settings['desc_color']; ?>;">
                        <?php echo htmlspecialchars($row['description']); ?>
                    </p>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
    </div>
</main>

<script>
    // ১. ডাইনামিক ফিল্ড জেনারেটর
    function generateUIDFields() {
        const count = document.getElementById('playerCount').value;
        const container = document.getElementById('uidContainer');
        container.innerHTML = '';
        for (let i = 1; i <= count; i++) { 
            const fieldId = `uid_${i}`;
            container.innerHTML += `
                <div class="relative group">
                    <input type="number" id="${fieldId}" placeholder="Enter Player ${i} UID" class="uid-input input-box pr-12 focus:border-cyan-500 transition-all">
                    <button onclick="pasteToField('${fieldId}')" class="absolute right-0 top-0 h-full w-12 flex items-center justify-center text-cyan-500 hover:text-cyan-300 transition-colors border-l border-gray-800 group-focus-within:border-cyan-500">
                        <i class="fas fa-paste"></i>
                    </button>
                </div>`; 
        }
    }

    // ২. পেস্ট ফাংশন (Browser Prompt is mandatory for security)
    async function pasteToField(targetId) {
        try {
            const text = await navigator.clipboard.readText();
            const input = document.getElementById(targetId);
            if (text) {
                input.value = text;
                input.style.borderColor = "#00d2ff";
                setTimeout(() => input.style.borderColor = "", 500);
            }
        } catch (err) {
            // যদি ব্রাউজার পারমিশন না দেয়
            console.log("Clipboard access denied");
        }
    }

    // ৩. কোড জেনারেশন লজিক
    function generateEmoteList() {
        const uids = Array.from(document.querySelectorAll('.uid-input')).map(i => i.value.trim()).filter(v => v !== "");
        const team = document.getElementById('teamCode').value.trim();
        
        if (uids.length === 0 || team === "") { 
            alert("Please provide UIDs and Team Code!"); 
            return; 
        }

        const uidPart = uids.join(' ');
        document.querySelectorAll('.emote-item').forEach(item => {
            const base = item.querySelector('.base-emote-code').value; 
            let p = base.split(" "); 
            let cmd = p[0]; 
            let num = p.length > 1 ? p[1] : "";
            
            const finalFormatted = `${cmd} ${uidPart} ${team} ${num}`.replace(/\s+/g, ' ').trim();
            item.querySelector('.display-code').innerText = finalFormatted;
        });

        // স্টেপ চেঞ্জ
        document.getElementById('step1').classList.replace('step-active', 'step-hidden');
        document.getElementById('step2').classList.replace('step-hidden', 'step-active');
        document.getElementById('backBtn').classList.replace('step-hidden', 'step-active');
        window.scrollTo({top: 0, behavior: 'smooth'});
    }

    // ৪. আধুনিক কপি লজিক
    async function copyDynamic(card) {
        const codeElement = card.querySelector('.display-code');
        if (!codeElement) return;
        const textToCopy = codeElement.innerText;

        try {
            if (navigator.clipboard && window.isSecureContext) {
                await navigator.clipboard.writeText(textToCopy);
                showToast();
            } else {
                throw new Error();
            }
        } catch (err) {
            const area = document.createElement("textarea");
            area.value = textToCopy;
            area.style.position = "fixed";
            area.style.left = "-9999px";
            document.body.appendChild(area);
            area.select();
            document.execCommand('copy');
            document.body.removeChild(area);
            showToast();
        }
    }

    function showToast() {
        const x = document.getElementById("toast");
        x.className = "show";
        setTimeout(() => { x.className = x.className.replace("show", ""); }, 2000);
    }

    function filterItems() {
        const input = document.getElementById('searchInput').value.toLowerCase();
        document.querySelectorAll('.emote-item').forEach(item => {
            const title = item.getAttribute('data-title');
            item.style.display = title.includes(input) ? "flex" : "none";
        });
    }
</script>
</body>
</html>