<?php 
// --- CLICK HANDLER (DB CHECK + API FALLBACK) ---
if(isset($_POST['check_uid_click'])) {
    include 'config.php'; // ডাটাবেস কানেকশন

    // ব্রাউজার ক্যাশ ক্লিয়ার রাখা
    header('Content-Type: application/json');
    header("Cache-Control: no-cache, no-store, must-revalidate");

    $uid = trim($_POST['check_uid_click']);
    
    // ১. প্রথমে ডাটাবেস চেক (গিল্ডে আছে কি না)
    $chk = $conn->query("SELECT id FROM members WHERE uid='$uid'");
    
    if($chk->num_rows > 0) {
        // গিল্ডে আছে -> সাকসেস
        echo json_encode(['status' => 'found']);
    } else {
        // ২. গিল্ডে নেই -> নতুন API থেকে নাম আনবো
        if(strlen($uid) >= 8) {
            // আপনার নতুন এপিআই লিঙ্ক
            $url = "https://tamim1280.vercel.app/player-info?uid=" . $uid . "&server=bd";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 
            curl_setopt($ch, CURLOPT_ENCODING, ''); 
            curl_setopt($ch, CURLOPT_TCP_NODELAY, true);
            
            $headers = [
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36',
                'Referer: https://google.com'
            ];
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10); // টাইমআউট কিছুটা বাড়ানো হলো

            $response = curl_exec($ch);
            $data = json_decode($response, true);
            curl_close($ch);

            // আপনার নতুন API রেসপন্স অনুযায়ী নাম বের করা (basicInfo এর ভেতরে nickname)
            $nickname = "Unknown Player";
            if (isset($data['basicInfo']['nickname'])) {
                $nickname = $data['basicInfo']['nickname'];
            } elseif (isset($data['nickname'])) {
                $nickname = $data['nickname'];
            }
            
            // গিল্ডে নেই, কিন্তু নাম পাওয়া গেছে
            echo json_encode(['status' => 'not_in_guild', 'name' => $nickname]);
        } else {
            // ভুল UID
            echo json_encode(['status' => 'invalid']);
        }
    }
    exit; // প্রসেস শেষ
}

// --- CUSTOM SESSION PATH FIX START ---
$sessionPath = __DIR__ . '/sessions';
if (!file_exists($sessionPath)) { 
    @mkdir($sessionPath, 0755, true); 
}
if (is_writable($sessionPath)) {
    ini_set('session.save_path', $sessionPath);
}
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// --- CUSTOM SESSION PATH FIX END ---

// Auto Logout
if(isset($_SESSION['guild_member_uid'])) {
    unset($_SESSION['guild_member_uid']);
}

include 'config.php'; 

// Settings Load
$sets = []; 
$q = $conn->query("SELECT * FROM settings"); 
while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>TAMIM 1280 Guild</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="style.css?v=<?php echo time(); ?>">
    <style>
        /* === LOGO WRAPPER === */
        .logo-box {
            position: relative;
            width: 200px;
            height: 200px;
            margin: 0 auto 20px auto;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #mainLogo {
            position: relative;
            width: 110px;
            height: 110px;
            border-radius: 50%;
            object-fit: cover;
            background: #000;
            z-index: 5;
            border: 3px solid #444;
            box-shadow: 0 0 15px rgba(0,0,0,0.5);
            transition: 0.3s;
        }

        /* === LIGHTNING CANVAS === */
        #shockCanvas {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 1;
            display: none;
        }

        .active-logo-glow {
            border-color: #fff !important;
            box-shadow: 0 0 20px #00f2ff, inset 0 0 10px #00f2ff !important;
            animation: vibrate 0.1s infinite;
        }

        @keyframes vibrate {
            0% { transform: translate(0, 0); }
            25% { transform: translate(1px, -1px); }
            50% { transform: translate(-1px, 2px); }
            75% { transform: translate(-2px, 1px); }
            100% { transform: translate(1px, 1px); }
        }

        /* --- UI Styles --- */
        .btn-grid {
            display: grid; grid-template-columns: 1fr 1fr; gap: 15px;
            margin-top: 30px; padding-top: 25px; border-top: 1px solid rgba(255,255,255,0.1);
        }
        .btn-opt {
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            padding: 20px 10px; border-radius: 12px; text-decoration: none;
            transition: 0.3s; position: relative; overflow: hidden;
            background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.1);
        }
        .btn-opt i { font-size: 28px; margin-bottom: 8px; transition: 0.3s; }
        .btn-opt span { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 1px; color: #aaa; }
        
        .btn-lb:hover { background: rgba(255, 165, 0, 0.1); border-color: orange; box-shadow: 0 0 20px rgba(255, 165, 0, 0.2); }
        .btn-lb:hover i, .btn-lb:hover span { color: orange; transform: scale(1.1); }
        .btn-off:hover { background: rgba(0, 255, 255, 0.1); border-color: cyan; box-shadow: 0 0 20px rgba(0, 255, 255, 0.2); }
        .btn-off:hover i, .btn-off:hover span { color: cyan; transform: scale(1.1); }
        .search-area { margin-bottom: 20px; }

        /* RESULT MESSAGE STYLE (NOT IN GUILD) */
        #statusResult {
            text-align: center;
            margin-top: 15px;
            font-size: 14px;
            font-weight: bold;
            display: none; /* ডিফল্টভাবে লুকানো */
            padding: 10px;
            border-radius: 8px;
            border: 1px solid transparent;
        }
        .not-found-box {
            background: rgba(255, 0, 0, 0.1);
            border-color: #ff3333 !important;
            color: #ff5555;
        }
        .player-name-hl {
            color: #fff;
            font-size: 16px;
            display: block;
            margin-bottom: 5px;
            text-transform: uppercase;
        }
    </style>
</head>
<body>

<?php include 'header.php'; ?>

<div class="main-wrapper">
    <div class="container">
        
        <!-- LOGO SECTION -->
        <div class="logo-box">
            <canvas id="shockCanvas"></canvas>
            <img id="mainLogo" 
                 src="uploads/logo.png?v=<?php echo time(); ?>" 
                 onerror="this.src='https://cdn-icons-png.flaticon.com/512/2922/2922510.png'">
        </div>
        
        <div style="text-align:center; margin-bottom:30px;">
            <h1 style="margin:0; color:#fff; font-size: 26px; letter-spacing:1px;">Ƭᴇᴀᴍs┊1280모</h1>
            <p style="color:#aaa; font-size:12px; margin-top:5px; text-transform:uppercase;">Official Guild Portal</p>
        </div>

        <div class="search-box-area">
            
            <!-- FORM: JavaScript Handle করবে -->
            <form onsubmit="handleCheck(event)" class="search-area">
                <div class="input-group">
                    <label style="color:#00f2ff; font-size:11px; margin-bottom:8px; display:block; letter-spacing:1px; font-weight:bold;">SEARCH PLAYER IDENTITY</label>
                    <input type="number" id="uidInput" name="uid" placeholder="Enter UID here..." required autocomplete="off" 
                           style="padding:15px; border-radius:8px; background:#0a0a0a; border:1px solid #333; color:white; width:100%; box-sizing:border-box; font-size:16px; text-align:center; font-weight:bold; letter-spacing:1px;">
                </div>
                
                <button type="submit" id="checkBtn" class="btn" style="width:100%; margin-top:15px; padding:14px; background:linear-gradient(90deg, #00f2ff, #0088ff); border:none; font-weight:bold; cursor:pointer; font-size:14px; border-radius:8px; box-shadow: 0 5px 20px rgba(0, 242, 255, 0.2); color:#000;">
                    CHECK STATUS <i class="fas fa-arrow-right"></i>
                </button>
            </form>

            <!-- রেজাল্ট দেখানোর জায়গা (যদি গিল্ডে না থাকে) -->
            <div id="statusResult"></div>

            <div style="text-align:center; color:#444; font-size:10px; margin-top:30px; letter-spacing:2px;">— GUILD EXPLORER —</div>
            
            <div class="btn-grid">
                <a href="leaderboard.php?tab=weekly" class="btn-opt btn-lb">
                    <i class="fas fa-trophy"></i>
                    <span>Leaderboard</span>
                </a>
                <a href="leaderboard.php?tab=officers" class="btn-opt btn-off">
                    <i class="fas fa-user-shield"></i>
                    <span>Management</span>
                </a>
            </div>

        </div>
    </div>
</div>

<footer>
    <div class="social-icons">
        <?php if(!empty($sets['fb_link'])) echo '<a href="'.$sets['fb_link'].'" target="_blank"><i class="fab fa-facebook-f"></i></a>'; ?>
        <?php if(!empty($sets['wa_link'])) echo '<a href="'.$sets['wa_link'].'" target="_blank"><i class="fab fa-whatsapp"></i></a>'; ?>
        <?php if(!empty($sets['discord_link'])) echo '<a href="'.$sets['discord_link'].'" target="_blank"><i class="fab fa-discord"></i></a>'; ?>
        <?php if(!empty($sets['yt_link'])) echo '<a href="'.$sets['yt_link'].'" target="_blank"><i class="fab fa-youtube"></i></a>'; ?>
    </div>
    <p class="copyright">&copy; 2026 TAMIM 1280. All Rights Reserved.</p>
</footer>

<!-- ⚡ JAVASCRIPT ⚡ -->
<script>
    // --- BUTTON CLICK LOGIC ---
    function handleCheck(e) {
        e.preventDefault(); // ফর্ম সাবমিট বন্ধ করা
        
        let uid = document.getElementById('uidInput').value;
        let btn = document.getElementById('checkBtn');
        let resBox = document.getElementById('statusResult');

        if(uid.length < 8) {
            alert("Please enter a valid UID!");
            return;
        }

        // লোডিং শুরু
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
        btn.style.opacity = "0.7";
        resBox.style.display = "none"; // আগের রেজাল্ট লুকানো

        let formData = new FormData();
        formData.append('check_uid_click', uid);

        fetch('index.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            // বাটন রিসেট
            btn.innerHTML = 'CHECK STATUS <i class="fas fa-arrow-right"></i>';
            btn.style.opacity = "1";

            if(data.status === 'found') {
                // ১. গিল্ডে পাওয়া গেছে -> Result Page এ নিয়ে যাও
                window.location.href = "result.php?uid=" + uid;
            } 
            else if(data.status === 'not_in_guild') {
                // ২. গিল্ডে নেই -> নাম দেখাবে এবং এরর মেসেজ
                resBox.innerHTML = `
                    <span class="player-name-hl">${data.name}</span>
                    <i class="fas fa-times-circle"></i> Not in Guild Member!
                `;
                resBox.className = "not-found-box";
                resBox.style.display = "block";
            }
            else {
                // ৩. ইনভ্যালিড UID
                resBox.innerHTML = "Invalid UID / Player Not Found";
                resBox.className = "not-found-box";
                resBox.style.display = "block";
            }
        })
        .catch(err => {
            btn.innerHTML = 'CHECK STATUS <i class="fas fa-arrow-right"></i>';
            btn.style.opacity = "1";
            alert("Connection Error!");
        });
    }

    // --- LIGHTNING EFFECT LOGIC (UNCHANGED) ---
    const canvas = document.getElementById('shockCanvas');
    const ctx = canvas.getContext('2d');
    const logoImg = document.getElementById('mainLogo');
    let isRunning = false;

    function resizeCanvas() { canvas.width = 200; canvas.height = 200; }
    resizeCanvas();
    function random(min, max) { return Math.random() * (max - min) + min; }
    function drawLightning(x, y) {
        const angle = random(0, Math.PI * 2);
        let sx = x + Math.cos(angle) * 55;
        let sy = y + Math.sin(angle) * 55;
        let ex = x + Math.cos(angle) * random(80, 100);
        let ey = y + Math.sin(angle) * random(80, 100);
        ctx.beginPath(); ctx.moveTo(sx, sy);
        let steps = random(3, 6); let currentX = sx; let currentY = sy;
        for (let i = 0; i < steps; i++) {
            let midX = currentX + (ex - currentX) / steps;
            let midY = currentY + (ey - currentY) / steps;
            midX += random(-10, 10); midY += random(-10, 10);
            ctx.lineTo(midX, midY); currentX = midX; currentY = midY;
        }
        ctx.lineTo(ex, ey); 
        ctx.strokeStyle = '#fff'; ctx.lineWidth = random(1, 3);
        ctx.shadowBlur = 15; ctx.shadowColor = '#00f2ff';
        ctx.stroke();
    }
    function animateShock() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        const bolts = Math.floor(random(2, 5));
        for (let i = 0; i < bolts; i++) { drawLightning(100, 100); }
    }
    function loop() {
        if (!isRunning) { ctx.clearRect(0, 0, canvas.width, canvas.height); return; }
        animateShock();
        setTimeout(() => { requestAnimationFrame(loop); }, 50);
    }
    setInterval(() => {
        if(typeof player !== 'undefined' && typeof player.getPlayerState === 'function') {
            var state = player.getPlayerState();
            if(state === 1) {
                if (!isRunning) { isRunning = true; canvas.style.display = "block"; logoImg.classList.add('active-logo-glow'); loop(); }
            } else {
                isRunning = false; canvas.style.display = "none"; logoImg.classList.remove('active-logo-glow');
            }
        }
    }, 1000);
</script>

</body>
</html>