<?php
session_start();
include 'config.php';
if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit(); }

$user_id = $_SESSION['user_id'];
$user = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();

$selected_brand_id = $_POST['brand_id'] ?? '';
$brand_info = $selected_brand_id ? $conn->query("SELECT * FROM brands WHERE id=$selected_brand_id")->fetch_assoc() : null;
$is_iphone = ($brand_info && strtoupper($brand_info['name']) == 'IPHONE');

function getBrandLogo($name, $db_logo) {
    if (!empty($db_logo) && strlen($db_logo) > 10) return $db_logo;
    $n = strtoupper(trim($name));
    $fallbacks = [
        'IPHONE'  => 'https://www.vectorlogo.zone/logos/apple/apple-ar21.svg',
        'SAMSUNG' => 'https://www.vectorlogo.zone/logos/samsung/samsung-ar21.svg',
        'XIAOMI'  => 'https://www.vectorlogo.zone/logos/xiaomi/xiaomi-ar21.svg',
        'VIVO'    => 'https://www.vectorlogo.zone/logos/vivo/vivo-ar21.svg',
        'REALME'  => 'https://www.vectorlogo.zone/logos/realme/realme-ar21.svg',
        'OPPO'    => 'https://www.vectorlogo.zone/logos/oppo/oppo-ar21.svg',
        'INFINIX' => 'https://vignette.wikia.nocookie.net/logopedia/images/2/2b/Infinix_2022.svg',
        'TECNO'   => 'https://upload.wikimedia.org/wikipedia/commons/7/73/Tecno_Mobile_logo.svg',
        'ONEPLUS' => 'https://www.vectorlogo.zone/logos/oneplus/oneplus-ar21.svg',
    ];
    return $fallbacks[$n] ?? 'https://cdn-icons-png.flaticon.com/512/644/644458.png';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sensi AI Pro - Device Calibration 🚀</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@400;600;700&display=swap');
        
        body { 
            font-family: 'Rajdhani', sans-serif; 
            background: #020617; color: #fff;
            min-height: 100vh; overflow-x: hidden; position: relative;
        }

        .bg-stars {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: radial-gradient(circle at center, #083344 0%, #020617 100%);
            z-index: -1;
        }
        .star { position: absolute; background: white; border-radius: 50%; opacity: 0.3; animation: blink 3s infinite; }
        @keyframes blink { 0%, 100% { opacity: 0.3; } 50% { opacity: 0.8; } }

        .main-container { max-width: 900px; margin: 0 auto; padding: 20px; position: relative; z-index: 10; }

        .premium-card {
            background: rgba(15, 23, 42, 0.6); backdrop-filter: blur(15px);
            border: 1px solid rgba(6, 182, 212, 0.2); border-radius: 35px;
            padding: 2.5rem; box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
            transition: 0.4s;
            position: relative; /* গুরুত্বপূর্ণ */
        }

        .brand-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 20px; }

        .brand-item {
            background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 25px; padding: 20px; transition: all 0.4s ease; display: flex; 
            flex-direction: column; align-items: center; cursor: pointer;
        }

        .brand-img { height: 50px; width: 100%; object-fit: contain; transition: 0.4s; margin-bottom: 12px; }

        /* Hover Effect - Green Glow & Blur */
        .brand-item:hover, .brand-item.active {
            border-color: #10b981; 
            background: rgba(16, 185, 129, 0.15);
            box-shadow: 0 0 30px rgba(16, 185, 129, 0.3);
            transform: translateY(-5px);
            backdrop-filter: blur(10px);
        }
        .brand-item:hover .brand-img, .brand-item.active .brand-img { filter: drop-shadow(0 0 10px #10b981); transform: scale(1.1); }

        .centered-input {
            text-align: center; background: rgba(0, 0, 0, 0.6) !important; color: #fff !important;
            border: 2px solid rgba(16, 185, 129, 0.3) !important; padding: 18px;
            border-radius: 22px; width: 100%; outline: none; font-weight: 700; font-size: 16px;
        }
        .centered-input:focus { border-color: #10b981; box-shadow: 0 0 15px rgba(16, 185, 129, 0.3); }

        /* ড্রপডাউন ফিক্স - এখানে পরিবর্তন করা হয়েছে */
        .dropdown-container { position: relative; width: 100%; z-index: 9999; }
        .model-list {
            position: absolute; 
            top: 105%; left: 0; right: 0;
            background: #0d1117; 
            border: 2px solid #10b981;
            border-radius: 22px; 
            max-height: 250px; 
            overflow-y: auto;
            z-index: 10000 !important; /* সবার উপরে থাকার জন্য */
            display: none; 
            box-shadow: 0 30px 60px rgba(0,0,0,1);
            margin-top: 5px;
        }
        .model-item { padding: 15px; text-align: center; cursor: pointer; border-bottom: 1px solid rgba(255,255,255,0.05); font-weight: 600; }
        .model-item:hover { background: #10b981; color: #000; }

        .neon-btn {
            background: linear-gradient(90deg, #10b981, #06b6d4);
            color: #000; font-weight: 900; text-transform: uppercase;
            letter-spacing: 3px; padding: 22px; border-radius: 25px; width: 100%;
            box-shadow: 0 10px 30px rgba(16, 185, 129, 0.3); font-family: 'Orbitron', sans-serif;
        }
    </style>
</head>
<body>

    <div class="bg-stars" id="stars"></div>

    <nav class="p-6 flex justify-between items-center max-w-6xl mx-auto w-full relative z-20">
        <h1 style="font-family: 'Orbitron', sans-serif;" class="text-3xl font-black text-emerald-400">SENSI <span class="text-white">AI</span></h1>
        <div class="bg-emerald-500/10 border border-emerald-500/20 px-6 py-2 rounded-2xl text-emerald-400 font-bold">
            ৳<?php echo number_format($user['balance'], 0); ?>
        </div>
    </nav>

    <div class="main-container">
        
        <!-- Step 1: Brands -->
        <div class="premium-card mb-10" style="z-index: 10;">
            <h3 class="text-xs text-center font-bold text-gray-400 uppercase tracking-[6px] mb-10 italic">01. CHOOSE YOUR BRAND</h3>
            <form action="" method="POST" class="brand-grid">
                <?php
                $brands = $conn->query("SELECT * FROM brands");
                while($b = $brands->fetch_assoc()):
                    $active = ($b['id'] == $selected_brand_id) ? 'active' : '';
                    $logo = getBrandLogo($b['name'], $b['logo']);
                ?>
                    <button type="submit" name="brand_id" value="<?php echo $b['id']; ?>" class="brand-item <?php echo $active; ?>">
                        <img src="<?php echo $logo; ?>" class="brand-img" alt="<?php echo $b['name']; ?>">
                        <span class="text-[11px] font-bold text-gray-400 uppercase"><?php echo $b['name']; ?></span>
                    </button>
                <?php endwhile; ?>
            </form>
        </div>

        <?php if($brand_info): ?>
        <form action="buy_action.php" method="POST" class="space-y-8">
            <input type="hidden" name="brand_id" value="<?php echo $selected_brand_id; ?>">
            
            <!-- Step 2: Model - উচ্চতর Z-Index দেওয়া হয়েছে -->
            <div class="premium-card" style="z-index: 50;">
                <h3 class="text-xs text-center font-bold text-emerald-400 uppercase tracking-[6px] mb-8 italic">02. IDENTIFY DEVICE MODEL 🔍</h3>
                <div class="dropdown-container">
                    <input type="text" id="modelSearch" name="model_name" placeholder="E.G. IPHONE 15 PRO MAX" autocomplete="off" class="centered-input" required>
                    <div class="model-list" id="modelList">
                        <?php
                        $ms = $conn->query("SELECT * FROM models WHERE brand_id=$selected_brand_id");
                        while($m = $ms->fetch_assoc()):
                        ?>
                            <div class="model-item"><?php echo $m['model_name']; ?></div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>

            <!-- Step 3: Specs - নিম্নতর Z-Index দেওয়া হয়েছে -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6" style="position: relative; z-index: 10;">
                <div class="premium-card text-center">
                    <h3 class="text-[10px] font-bold text-gray-500 uppercase tracking-[5px] mb-5 italic">RAM Capacity 💾</h3>
                    <select name="ram" class="centered-input">
                        <?php 
                        $ram_opts = $is_iphone ? ['4GB', '6GB', '8GB'] : ['4GB', '6GB', '8GB', '12GB', '16GB', '24GB'];
                        foreach($ram_opts as $r) echo "<option value='$r'>$r RAM</option>"; 
                        ?>
                    </select>
                </div>
                <div class="premium-card text-center">
                    <h3 class="text-[10px] font-bold text-gray-500 uppercase tracking-[5px] mb-5 italic">Storage Space 📂</h3>
                    <select name="rom" class="centered-input">
                        <?php 
                        $rom_opts = ['64GB', '128GB', '256GB', '512GB', '1TB'];
                        foreach($rom_opts as $r) echo "<option value='$r'>$r ROM</option>"; 
                        ?>
                    </select>
                </div>
            </div>

            <!-- Step 4: Finalize -->
            <div class="premium-card text-center border-emerald-500/40 group overflow-hidden relative" style="z-index: 10;">
                <div class="absolute -right-16 -bottom-16 opacity-5 text-[150px] group-hover:rotate-12 transition-all">🚀</div>
                <h4 class="text-6xl font-black text-white mb-10 orbitron italic">৳<?php echo $brand_info['price']; ?></h4>
                <button type="submit" class="neon-btn">
                    START CALIBRATION <i class="fas fa-bolt ml-2"></i>
                </button>
            </div>
        </form>
        <?php endif; ?>

    </div>

    <script>
        // ব্যাকগ্রাউন্ড স্টার
        const starsContainer = document.getElementById('stars');
        for (let i = 0; i < 40; i++) {
            const star = document.createElement('div');
            star.className = 'star';
            star.style.left = Math.random() * 100 + '%';
            star.style.top = Math.random() * 100 + '%';
            star.style.width = Math.random() * 3 + 'px';
            star.style.height = star.style.width;
            star.style.animationDelay = Math.random() * 5 + 's';
            starsContainer.appendChild(star);
        }

        // ড্রপডাউন লজিক
        const searchInput = document.getElementById('modelSearch');
        const list = document.getElementById('modelList');
        const items = document.querySelectorAll('.model-item');

        if(searchInput) {
            searchInput.addEventListener('focus', () => {
                list.style.display = 'block';
            });
            
            searchInput.addEventListener('input', (e) => {
                const val = e.target.value.toLowerCase();
                items.forEach(item => {
                    item.style.display = item.innerText.toLowerCase().includes(val) ? 'block' : 'none';
                });
            });

            items.forEach(item => {
                item.addEventListener('click', () => {
                    searchInput.value = item.innerText;
                    list.style.display = 'none';
                });
            });

            document.addEventListener('click', (e) => {
                if(!e.target.closest('.dropdown-container')) {
                    list.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>