<?php
// --- DATABASE & ENCODING SETUP (Top of the file) ---
if(file_exists('../config.php')) require '../config.php';
else if(file_exists('config.php')) require 'config.php';

// বাংলা ফন্ট এবং ফ্যান্সি গেম নামের জন্য অত্যন্ত জরুরি
if(isset($conn)) {
    $conn->set_charset("utf8mb4");
}

// --- [API HANDLER] NAME FETCHING (UPDATED FOR NEW API) ---
if (isset($_GET['fetch_uid_name'])) {
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Pragma: no-cache");
    header("Expires: 0");
    $uid = trim($_GET['fetch_uid_name']);
    
    $url = "https://tamim1280.vercel.app/player-info?uid=" . $uid;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 8);
    $response = curl_exec($ch);
    $data = json_decode($response, true);
    curl_close($ch);

    // নতুন এপিআই এর সঠিক কি (Key) চেক
    $nickname = $data['basicInfo']['nickname'] ?? $data['basicinfo']['nickname'] ?? $data['nickname'] ?? "";
    echo $nickname;
    exit; 
}

// --- [UPDATED LOGIC] AUTO GUILD CHECK HANDLER (FIXED AUTO-BAN ISSUE) ---
if (isset($_GET['auto_guild_check'])) {
    $target_clan_id = "3066573253"; 
    $uid = trim($_GET['auto_guild_check']);
    
    $url = "https://tamim1280.vercel.app/player-info?uid=" . $uid;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    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);

    // ডাটা হ্যান্ডেলিং (নতুন এপিআই ফরম্যাট অনুযায়ী)
    $info = $data['basicInfo'] ?? $data['basicinfo'] ?? null;
    
    if ($info) {
        $current_clan_id = $info['clanId'] ?? $info['clanid'] ?? ""; 
        $current_clan_name = $info['clanName'] ?? $info['clanname'] ?? "No Guild";

        // ১. যদি প্লেয়ার আমাদের টার্গেট গিল্ডে থাকে
        if ($current_clan_id == $target_clan_id) {
            $conn->query("UPDATE members SET is_checked = 1 WHERE uid = '$uid'");
            echo "STAY|" . $current_clan_name;
        } 
        // ২. যদি এপিআই থেকে কোনো গিল্ড আইডি-ই না পাওয়া যায় (ব্যান করা যাবে না)
        elseif (empty($current_clan_id) || $current_clan_id == "0") {
            echo "NO_GUILD_DATA|" . $current_clan_name;
        }
        // ৩. যদি নিশ্চিতভাবে অন্য কোনো গিল্ড আইডিতে থাকে তবেই ব্যান হবে
        else {
            $reason = "এই প্লেয়ারটি কে গিল্ড থেকে বের করে দেওয়া হয়েছে কারণ রুলস অমান্য করেছে।";
            $safe_reason = $conn->real_escape_string($reason);
            $conn->query("UPDATE members SET is_banned = 1, ban_reason = '$safe_reason' WHERE uid = '$uid'");
            echo "BANNED|" . $current_clan_name;
        }
    } 
    else {
        echo "NOT_FOUND|N/A";
    }
    exit;
}

// --- CUSTOM SESSION PATH FIX ---
$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(); }

if(!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit(); }

$message = ""; 
$msg_type = "";

// --- [NEW FEATURE: SMART AUTO-SYNC HANDLER] ---
if (isset($_POST['mass_json_update'])) {
    $raw_input = trim($_POST['json_data']);
    if (!empty($raw_input)) {
        // ডাটা ক্লিনিং
        $raw_input = rtrim($raw_input, ',');
        if ($raw_input[0] !== '[') {
            $raw_input = '[' . $raw_input . ']';
        }
        
        $players = json_decode($raw_input, true);
        
        if ($players && is_array($players)) {
            $upd = 0; $ins = 0;
            foreach ($players as $p) {
                if (isset($p['account_id'])) {
                    $uid = $conn->real_escape_string($p['account_id']);
                    $name = $conn->real_escape_string($p['nickname'] ?? 'Unknown');
                    $total = (int)($p['guild_war_total_point'] ?? 0);
                    $weekly = (int)($p['total_activeness'] ?? 0);

                    // চেক করা হচ্ছে প্লেয়ারটি ডাটাবেসে আছে কি না
                    $check = $conn->query("SELECT id FROM members WHERE uid = '$uid'");
                    
                    if ($check->num_rows > 0) {
                        // যদি থাকে তবে ডাটা আপডেট হবে (Update Name and Points)
                        $sql = "UPDATE members SET game_name='$name', total_dogtags=$total, weekly_dogtags=$weekly, is_checked=1 WHERE uid='$uid'";
                        $conn->query($sql);
                        $upd++;
                    } else {
                        // যদি না থাকে তবে নতুন মেম্বার হিসেবে অ্যাড হবে (Insert New Member)
                        $join_date = date('Y-m-d');
                        $sql = "INSERT INTO members (uid, game_name, total_dogtags, weekly_dogtags, rank, behavior_score, join_date, is_checked) 
                                VALUES ('$uid', '$name', $total, $weekly, 'Member', 100, '$join_date', 1)";
                        $conn->query($sql);
                        $ins++;
                    }
                }
            }
            $message = "সফলভাবে $upd জন আপডেট হয়েছে এবং $ins জন নতুন মেম্বার যুক্ত হয়েছে!";
            $msg_type = "success";
        } else {
            $message = "ভুল ডাটা ফরম্যাট! দয়া করে সঠিক কোড পেস্ট করুন।";
            $msg_type = "error";
        }
    }
}

// 1. DELETE
if(isset($_GET['delete'])) { 
    $del_id = intval($_GET['delete']);
    if($del_id > 0) { $conn->query("DELETE FROM members WHERE id=$del_id"); }
    header("Location: index.php"); exit(); 
}

// 2. TOGGLE
if(isset($_GET['toggle_check'])) {
    $id = intval($_GET['toggle_check']);
    $conn->query("UPDATE members SET is_checked = IF(is_checked=1, 0, 1) WHERE id=$id");
    header("Location: index.php"); exit(); 
}

// 3. ADD MEMBER
if(isset($_POST['add_member'])) {
    $uid = $_POST['uid']; 
    $name = $conn->real_escape_string($_POST['game_name']); 
    $total_in = (int)$_POST['total_val'];
    $weekly_in = (int)$_POST['weekly_val'];
    $tourn = $_POST['tournament'] ?? 'no'; 
    $rank = $_POST['rank'] ?? 'Member';
    $join_date = (!empty($_POST['join_date'])) ? $_POST['join_date'] : date('Y-m-d');
    $behavior = (int)($_POST['behavior'] ?? 100);
    $nc_status = isset($_POST['nc_status']) ? 1 : 0;
    $raw_date = $_POST['nc_date'] ?? '';
    $nc_date = ($nc_status == 1 && !empty($raw_date)) ? str_replace('T', ' ', $raw_date) : NULL;
    if($nc_status == 1 && empty($nc_date)) $nc_date = date('Y-m-d H:i:s', strtotime('+3 days'));
    $wa = $_POST['wa_num'] ?? ''; $tg = $_POST['tg_link'] ?? '';
    try { 
        $sql = "INSERT INTO members (uid, game_name, total_dogtags, weekly_dogtags, tournament_status, rank, join_date, behavior_score, name_change_status, name_change_date, whatsapp_number, telegram_username) 
                VALUES ('$uid','$name',$total_in,$weekly_in,'$tourn', '$rank', '$join_date', $behavior, $nc_status, " . ($nc_date ? "'$nc_date'" : "NULL") . ", '$wa', '$tg')";
        $conn->query($sql); $message="Added Successfully!"; $msg_type="success"; 
    } 
    catch(Exception $e) { $message="Error: UID Already Exists!"; $msg_type="error"; }
}

// 4. EDIT MEMBER
if(isset($_POST['edit_id'])) {
    $id = (int)$_POST['edit_id'];
    $act = $_POST['action_type'];
    $rank = $_POST['edit_rank'] ?? 'Member';
    $behavior = (int)$_POST['behavior_score'] ?? 100;
    $join_date = $_POST['edit_join_date'] ?? date('Y-m-d');
    $tourn = $_POST['edit_tournament'] ?? 'no';
    $nc_status = isset($_POST['nc_status']) ? 1 : 0;
    $raw_date = $_POST['nc_date'] ?? '';
    $nc_date = ($nc_status == 1 && !empty($raw_date)) ? str_replace('T', ' ', $raw_date) : NULL;
    $wa = $_POST['wa_num'] ?? ''; $tg = $_POST['tg_link'] ?? '';
    $sql = "UPDATE members SET rank='$rank', behavior_score=$behavior, join_date='$join_date', tournament_status='$tourn', name_change_status=$nc_status, name_change_date=" . ($nc_date ? "'$nc_date'" : "NULL") . ", whatsapp_number='$wa', telegram_username='$tg' ";
    
    if($act == 'smart_update') {
        $input_total = (int)$_POST['smart_total_inp'];
        $row = $conn->query("SELECT total_dogtags, weekly_dogtags FROM members WHERE id=$id")->fetch_assoc();
        $old_total = (int)$row['total_dogtags']; $old_weekly = (int)$row['weekly_dogtags'];
        $diff = $input_total - $old_total; $new_weekly = $old_weekly + $diff;
        if($new_weekly < 0) $new_weekly = 0; 
        $sql .= ", total_dogtags = $input_total, weekly_dogtags = $new_weekly";
    }
    elseif($act == 'manual_override') {
        $m_weekly = (int)$_POST['man_weekly']; $m_total = (int)$_POST['man_total'];
        $sql .= ", weekly_dogtags = $m_weekly, total_dogtags = $m_total";
    }
    elseif($act == 'reset_weekly') { $sql .= ", weekly_dogtags = 0"; }
    elseif($act == 'ban_player') {
        $reason = $conn->real_escape_string($_POST['ban_reason']);
        $sql .= ", is_banned = 1, ban_reason = '$reason'";
    }
    elseif($act == 'unban_player') { $sql .= ", is_banned = 0, ban_reason = NULL"; }
    $sql .= " WHERE id=$id";
    if($conn->query($sql)) { $message="Updated Successfully!"; $msg_type="success"; } 
    else { $message="Failed!"; $msg_type="error"; }
}

// 5. UPDATE SETTINGS
if(isset($_POST['update_settings'])) {
    $sets_arr = ['telegram_link', 'tournament_date', 'fb_link', 'discord_link', 'yt_link', 'wa_link', 'youtube_bgm_link'];
    foreach($sets_arr as $key) {
        $val = $conn->real_escape_string($_POST[$key] ?? '');
        $chk = $conn->query("SELECT * FROM settings WHERE setting_key='$key'");
        if($chk->num_rows > 0) $conn->query("UPDATE settings SET setting_value='$val' WHERE setting_key='$key'");
        else $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('$key', '$val')");
    }
    $dir = "../uploads/";
    if(!file_exists($dir)) mkdir($dir, 0777, true);
    if(!empty($_FILES['guild_logo']['name'])) move_uploaded_file($_FILES['guild_logo']['tmp_name'], $dir."logo.png");
    if(!empty($_FILES['tourn_image']['name'])) move_uploaded_file($_FILES['tourn_image']['tmp_name'], $dir."tournament.jpg");
    $message="Saved!"; $msg_type="success";
}

// 6. TELEGRAM SETTINGS
if(isset($_POST['update_tg_bot'])) {
    $tg_keys = ['tg_bot_token', 'tg_chat_ids', 'tg_nc_msg', 'tg_weekly_msg'];
    $raw_w_date = $_POST['next_weekly_cron'] ?? '';
    if(!empty($raw_w_date)) {
        $w_date = str_replace('T', ' ', $raw_w_date);
        $chk = $conn->query("SELECT * FROM settings WHERE setting_key='next_weekly_cron'");
        if($chk->num_rows > 0) $conn->query("UPDATE settings SET setting_value='$w_date' WHERE setting_key='next_weekly_cron'");
        else $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('next_weekly_cron', '$w_date')");
    }
    foreach($tg_keys as $key) {
        $val = $conn->real_escape_string($_POST[$key] ?? '');
        $chk = $conn->query("SELECT * FROM settings WHERE setting_key='$key'");
        if($chk->num_rows > 0) $conn->query("UPDATE settings SET setting_value='$val' WHERE setting_key='$key'");
        else $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('$key', '$val')");
    }
    $message="Telegram Settings Saved!"; $msg_type="success";
}

// 7. TRIGGERS
if(isset($_POST['test_bot_conn'])) { include 'tg_logic_core.php'; $message = testBotConnection($conn); $msg_type="success"; }
if(isset($_POST['test_nc_msg'])) { include 'tg_logic_core.php'; $message = forceTestNameChange($conn); $msg_type="success"; }
if(isset($_POST['test_weekly_msg'])) { include 'tg_logic_core.php'; $message = forceTestWeekly($conn); $msg_type="success"; }
if(isset($_POST['run_weekly_check'])) { include 'tg_logic_core.php'; $res = runWeeklyReminder($conn); $message = $res; $msg_type="success"; }

// DATA LOAD
$sql_mem = "SELECT * FROM members ORDER BY is_checked DESC, weekly_dogtags DESC, total_dogtags DESC, rank='Admin' DESC";
$members = $conn->query($sql_mem);
$sets = []; $q = $conn->query("SELECT * FROM settings"); while($r=$q->fetch_assoc()) $sets[$r['setting_key']]=$r['setting_value'];

function getTenure($date) {
    if(!$date) return "<span style='color:#777; font-size:10px;'>New</span>";
    $diff = date_diff(date_create($date), date_create());
    if($diff->y >= 1) return "<b style='color:gold; font-size:10px;'>OLD ({$diff->y}Y)</b>";
    return "<span style='color:#aaa; font-size:10px;'>{$diff->m}M {$diff->d}D</span>";
}
?>

<!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>Guild Admin</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>
        body, html { margin:0; padding:0; height:100%; overflow:hidden; background: #000; color: #fff; font-family: 'Segoe UI', sans-serif; }
        .admin-wrapper { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
        header { flex-shrink: 0; background: #111; padding: 15px; border-bottom: 1px solid #222; display:flex; justify-content:space-between; align-items:center; }
        .tab-menu { flex-shrink: 0; display: flex; background: #080808; border-bottom:1px solid #333; overflow-x: auto; white-space: nowrap; -webkit-overflow-scrolling: touch; }
        .t-btn { flex: 1; padding: 12px; text-align: center; cursor: pointer; color: #777; font-weight:bold; font-size:12px; transition:0.3s; min-width: 90px; border-bottom: 2px solid transparent; }
        .t-btn.active { color: #fff; background: #111; border-bottom-color: cyan; }
        .content-area { flex-grow: 1; overflow-y: auto; padding: 15px; padding-bottom: 100px; }
        .logo { font-weight:bold; font-size:18px; color: cyan; text-decoration:none; text-transform:uppercase; letter-spacing:1px; }
        
        .serial-no { color: #555; font-size: 14px; font-weight: bold; margin-right: 12px; font-family: monospace; width: 25px; text-align: center; }

        .list-card { background: #111; margin-bottom: 8px; border-radius: 5px; padding: 12px; display: flex; align-items: center; border: 1px solid #222; position: relative; }
        .rnk-Admin { border-left: 3px solid red; } .rnk-Leader { border-left: 3px solid orange; }
        .is-banned-card { border-left: 3px solid #500 !important; opacity: 0.7; }
        .ban-badge { background: red; color: white; font-size: 8px; padding: 2px 5px; border-radius: 3px; position: absolute; top: 5px; right: 5px; font-weight: bold; }
        .check-green { color: #00ff9d; font-size:20px; padding-right:15px; cursor:pointer; }
        .check-red { color: #333; font-size:20px; padding-right:15px; cursor:pointer; }
        .info-box { flex: 1; cursor:pointer; }
        .p-name { font-size: 15px; font-weight: bold; color: #fff; display: block; margin-bottom: 3px; }
        .p-sub { font-size: 11px; color: #666; font-family: monospace; }
        .score-col { text-align: right; font-family: monospace; font-size: 11px; cursor:pointer; }
        .bg-weekly { background: #004d00; color: #00ff9d; border: 1px solid #006600; padding: 3px 6px; border-radius: 4px; font-weight: bold; }
        .bg-total { background: #002244; color: cyan; border: 1px solid #004488; padding: 3px 6px; border-radius: 4px; font-weight: bold; }
        .smart-box { background:#1a0f00; border:1px solid #ff9900; padding:15px; border-radius:6px; margin-bottom:15px; }
        .live-prev { display:none; background:#191919; border-left:2px solid #ff9900; padding:10px; margin-top:10px; }
        .hl-txt { color:#ff9900; font-weight:bold; font-size:14px; }
        .manual-box { display:none; background:#001a33; border:1px solid #0088cc; padding:10px; border-radius:6px; margin-bottom:15px; }
        .inp-grp { margin-bottom: 12px; }
        .inp-lbl { display: block; font-size: 11px; color: #777; margin-bottom: 5px; text-transform:uppercase; letter-spacing:1px; }
        input, select, textarea { width: 100%; padding: 12px; background: #050505; border: 1px solid #333; color: #fff; border-radius: 4px; box-sizing:border-box; font-size:14px; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.95); z-index: 999; justify-content: center; align-items: center; }
        .modal-body { background: #111; border: 1px solid #333; width: 90%; max-width: 400px; padding: 20px; border-radius: 8px; max-height: 85vh; overflow-y: auto; }
        .btn { width:100%; padding:14px; border:none; font-weight:bold; border-radius:4px; margin-top:15px; cursor:pointer; }
        .btn-set { background: #ff9900; color:#000; width:auto; padding:12px 25px; margin:0; }
        .btn-main { background: cyan; color: #000; border:1px solid cyan; }
        .btn-link { background:transparent; border:none; color:#0088cc; font-size:11px; text-decoration:underline; cursor:pointer; display:block; text-align:right; margin-bottom:5px;}
        .toggle-switch { display: flex; align-items: center; cursor: pointer; width: fit-content; margin-bottom:10px; }
        .toggle-switch input { display: none; }
        .slider { width: 40px; height: 20px; background: #333; border-radius: 20px; position: relative; transition: 0.3s; margin-right: 10px; }
        .toggle-switch input:checked + .slider { background: cyan; }
        .toggle-switch input:checked + .slider::before { transform: translateX(20px); }
        .slider::before { content: ""; position: absolute; width: 16px; height: 16px; background: #fff; border-radius: 50%; top: 2px; left: 2px; transition: 0.3s; }
        .date-reveal { display:none; background:#222; padding:10px; border-radius:5px; margin-top:5px; }
        .ban-ctrl-box { background: #1a0000; border: 1px solid #500; padding: 12px; border-radius: 6px; margin: 15px 0; border-left: 3px solid red; }
        .help-txt { color:#666; font-size:10px; margin-top:3px; display:block; }
        .btn-check { background: #00ff9d; color: #000; border: none; padding: 12px 15px; font-weight: bold; cursor: pointer; border-radius: 4px; white-space: nowrap; }
        
        #auto_status { font-size: 11px; color: #00ff9d; font-weight: bold; background: rgba(0, 255, 157, 0.1); padding: 5px 10px; border-radius: 50px; border: 1px solid rgba(0, 255, 157, 0.3); }
    </style>
</head>
<body>

<div class="admin-wrapper">
    <header>
        <a href="#" class="logo">Guild Admin</a>
        <div id="auto_status"><i class="fas fa-robot"></i> Monitoring Active...</div>
        <a href="logout.php" style="color:#ff3333; font-size:20px;"><i class="fas fa-power-off"></i></a>
    </header>

    <div class="tab-menu">
        <div class="t-btn active" onclick="goTab('list', this)">LIST</div>
        <div class="t-btn" onclick="goTab('json_up', this)" style="color: yellow;">1280 CODE</div>
        <div class="t-btn" onclick="goTab('banned_list', this)">BANNED</div>
        <div class="t-btn" onclick="goTab('add', this)">ADD NEW</div>
        <div class="t-btn" onclick="goTab('sets', this)">SETTINGS</div>
        <div class="t-btn" onclick="goTab('tg_sets', this)" style="color:#0088cc;"><i class="fab fa-telegram-plane"></i> BOT</div>
    </div>
    
    <?php if($message): ?>
    <div style="background:#222; border-bottom:2px solid <?php echo $msg_type=='success'?'#00ff9d':'red'; ?>; color:<?php echo $msg_type=='success'?'#00ff9d':'red'; ?>; text-align:center; padding:10px; font-size:12px;">
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <div class="content-area">
        <!-- 1. LIST -->
        <div id="list" class="page-sec">
             <input type="text" id="srcBox" onkeyup="filterList('memList')" placeholder="Search Active Players..." style="width:100%; padding:10px; border-radius:50px; text-align:center; background:#111; border:1px solid #333; color:#fff; margin-bottom:15px;">
            <div id="memList">
                <?php 
                $active_uids = []; 
                $count = 1;
                $members->data_seek(0); 
                while($row = $members->fetch_assoc()): 
                    if($row['is_banned'] == 1) continue; 
                    $active_uids[] = $row['uid'];
                    $json = htmlspecialchars(json_encode($row, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8'); 
                ?>
                <div class="list-card rnk-<?php echo str_replace(' ','',$row['rank']); ?>" data-uid="<?php echo $row['uid']; ?>">
                    <div class="serial-no"><?php echo $count++; ?>.</div>
                    <a href="?toggle_check=<?php echo $row['id']; ?>" class="<?php echo $row['is_checked']?'check-green':'check-red'; ?>"><i class="fas fa-check-circle"></i></a>
                    <div class="info-box" onclick='openMod(<?php echo $json; ?>)'>
                        <span class="p-name"><?php echo $row['game_name']; ?></span>
                        <div class="p-sub">UID: <?php echo $row['uid']; ?> | <?php echo getTenure($row['join_date']); ?></div>
                    </div>
                    <div class="score-col" onclick='openMod(<?php echo $json; ?>)'>
                        <div style="color:gold; font-size:10px; margin-bottom:2px;"><i class="fas fa-star"></i> <?php echo $row['behavior_score']; ?></div>
                        <div style="display:flex; gap:5px; justify-content:flex-end; margin-top:5px;">
                            <span class="bg-weekly">W: <?php echo $row['weekly_dogtags']; ?></span>
                            <span class="bg-total">T: <?php echo $row['total_dogtags']; ?></span>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>
        </div>

        <!-- 2. SMART JSON SYNC TAB -->
        <div id="json_up" class="page-sec" style="display:none;">
            <div style="background:#111; padding:20px; border-radius:8px; border:1px solid #333;">
                <h4 style="color:yellow; margin-top:0;"><i class="fas fa-sync"></i> Smart Auto Sync</h4>
                <p style="font-size:11px; color:#aaa;">এখানে আপনার কপআপনার লিডার থেকে নেওয়া কোডটি পেস্ট করুন। TAMIM 1280 LEADER।</p>
                <form method="post">
                    <textarea name="json_data" rows="12" placeholder='এখানে কোড পেস্ট করুন...'></textarea>
                    <button type="submit" name="mass_json_update" class="btn btn-main" style="background:yellow; color:#000; font-weight:bold; margin-top:15px; border-radius:50px;">সবগুলো অটো সিঙ্ক করুন</button>
                </form>
            </div>
        </div>

        <!-- 3. BANNED -->
        <div id="banned_list" class="page-sec" style="display:none;">
            <input type="text" id="srcBoxBan" onkeyup="filterList('banList')" placeholder="Search Banned Players..." style="width:100%; padding:10px; border-radius:50px; text-align:center; background:#111; border:1px solid #333; color:#fff; margin-bottom:15px;">
            <div id="banList">
                <?php 
                $ban_count = 1;
                $members->data_seek(0); 
                while($row = $members->fetch_assoc()): 
                    if($row['is_banned'] == 0) continue; 
                    $json = htmlspecialchars(json_encode($row, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8'); 
                ?>
                <div class="list-card is-banned-card">
                    <div class="serial-no" style="color:#700;"><?php echo $ban_count++; ?>.</div>
                    <span class="ban-badge">BANNED</span>
                    <div class="info-box" onclick='openMod(<?php echo $json; ?>)'>
                        <span class="p-name"><?php echo $row['game_name']; ?></span>
                        <div class="p-sub">UID: <?php echo $row['uid']; ?> | <span style="color:red;">Reason: <?php echo $row['ban_reason']; ?></span></div>
                    </div>
                    <div class="score-col" onclick='openMod(<?php echo $json; ?>)'>
                        <button class="btn-link" style="color:red; text-decoration:none;">EDIT/UNBAN</button>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>
        </div>

        <!-- 4. ADD NEW -->
        <div id="add" class="page-sec" style="display:none;">
            <form method="post">
                <div class="inp-grp">
                    <label class="inp-lbl">UID (Click CHECK for Auto Name)</label>
                    <div style="display:flex; gap:5px;">
                        <input type="number" name="uid" id="add_uid_inp" required placeholder="Enter UID">
                        <button type="button" onclick="fetchNameManual()" class="btn-check" id="btnCheckName"><i class="fas fa-search"></i> CHECK</button>
                    </div>
                </div>
                <div class="inp-grp"><label class="inp-lbl">Game Name (Auto or Manual)</label><input type="text" name="game_name" id="add_name_inp" required placeholder="Type name OR click check"></div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px;">
                    <div class="inp-grp"><label class="inp-lbl">This Week</label><input type="number" name="weekly_val" required></div>
                    <div class="inp-grp"><label class="inp-lbl">Total Dogtag</label><input type="number" name="total_val" required></div>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px;">
                    <div class="inp-grp"><label class="inp-lbl">Join Date</label><input type="date" name="join_date" value="<?php echo date('Y-m-d'); ?>"></div>
                    <div class="inp-grp"><label class="inp-lbl">Behavior Score</label><input type="number" name="behavior" value="100"></div>
                </div>
                <div class="inp-grp"><label class="inp-lbl">Tournament Squad</label>
                    <select name="tournament"><option value="no">No</option><option value="yes">Yes</option></select>
                </div>
                <div class="inp-grp"><label class="inp-lbl">Rank</label>
                    <select name="rank" onchange="toggleAddOff(this.value)"><option value="Member">Member</option><option value="Officer">Officer</option><option value="Active Leader">Active Leader</option><option value="Leader">Leader</option><option value="Admin">Admin</option></select>
                </div>
                <div id="add_off" style="display:none; padding:10px; border:1px solid #333; margin-bottom:10px;">
                    <div class="inp-grp"><input type="text" name="wa_num" placeholder="WhatsApp"></div>
                    <div class="inp-grp"><input type="text" name="tg_link" placeholder="Telegram"></div>
                </div>
                <div style="margin-top:15px; border-top:1px solid #333; padding-top:10px;">
                    <label class="toggle-switch"><input type="checkbox" name="nc_status" id="add_nc_cb" onchange="toggleDateBox('add')"><span class="slider"></span><span>Name Change?</span></label>
                    <div id="add_nc_box" class="date-reveal"><label class="inp-lbl">Deadline</label><input type="datetime-local" name="nc_date"></div>
                </div>
                <button type="submit" name="add_member" class="btn btn-main">Create Member</button>
            </form>
        </div>

        <!-- 5. GENERAL SETTINGS -->
        <div id="sets" class="page-sec" style="display:none;">
            <form method="post" enctype="multipart/form-data">
                <h4 style="color:cyan;">Images</h4>
                <div class="inp-grp"><label class="inp-lbl">Logo</label><input type="file" name="guild_logo"></div>
                <div class="inp-grp"><label class="inp-lbl">Banner (Tournament List)</label><input type="file" name="tourn_image"></div>
                <h4 style="color:violet;">Music & Events</h4>
                <div class="inp-grp">
                    <label class="inp-lbl" style="color:violet;"><i class="fas fa-music"></i> Background Music (YouTube Link)</label>
                    <input type="text" name="youtube_bgm_link" value="<?php echo $sets['youtube_bgm_link']??''; ?>" placeholder="https://youtu.be/...">
                </div>
                <div class="inp-grp">
                    <label class="inp-lbl" style="color:yellow;"><i class="fas fa-calendar-alt"></i> Tournament Date & Time</label>
                    <input type="datetime-local" name="tournament_date" value="<?php echo ($sets['tournament_date']??'') ? date('Y-m-d\TH:i', strtotime($sets['tournament_date'])) : ''; ?>" style="color-scheme: dark;">
                </div>
                <h4 style="color:gold;">Social Links</h4>
                <div class="inp-grp"><label class="inp-lbl">Telegram</label><input type="text" name="telegram_link" value="<?php echo $sets['telegram_link']??''; ?>"></div>
                <div class="inp-grp"><label class="inp-lbl">WhatsApp</label><input type="text" name="wa_link" value="<?php echo $sets['wa_link']??''; ?>"></div>
                <div class="inp-grp"><label class="inp-lbl">Facebook</label><input type="text" name="fb_link" value="<?php echo $sets['fb_link']??''; ?>"></div>
                <div class="inp-grp"><label class="inp-lbl">YouTube</label><input type="text" name="yt_link" value="<?php echo $sets['yt_link']??''; ?>"></div>
                <div class="inp-grp"><label class="inp-lbl">Discord</label><input type="text" name="discord_link" value="<?php echo $sets['discord_link']??''; ?>"></div>
                <button type="submit" name="update_settings" class="btn btn-main">Save Settings</button>
            </form>
        </div>

        <!-- 6. TELEGRAM BOT SETTINGS -->
        <div id="tg_sets" class="page-sec" style="display:none;">
            <form method="post">
                <div style="background:#001a33; border:1px solid #0088cc; padding:15px; border-radius:8px; margin-bottom:20px;">
                    <h4 style="color:#00f2ff; margin-top:0;"><i class="fas fa-robot"></i> Telegram Bot Config</h4>
                    <div class="inp-grp"><label class="inp-lbl">Bot Token</label><input type="text" name="tg_bot_token" value="<?php echo $sets['tg_bot_token']??''; ?>"></div>
                    <div class="inp-grp"><label class="inp-lbl">Chat IDs</label><input type="text" name="tg_chat_ids" value="<?php echo $sets['tg_chat_ids']??''; ?>"></div>
                    <div style="display:grid; grid-template-columns: 1fr; gap:10px; margin-top:10px;">
                        <button type="submit" name="test_bot_conn" class="btn" style="background:#00ff9d; color:#000; margin:0;"><i class="fas fa-plug"></i> TEST CONNECTION</button>
                    </div>
                </div>
                <div class="inp-grp">
                    <label class="inp-lbl" style="color:orange;"><i class="fas fa-clock"></i> Next Weekly Reminder</label>
                    <input type="datetime-local" name="next_weekly_cron" value="<?php echo ($sets['next_weekly_cron']??'') ? date('Y-m-d\TH:i', strtotime($sets['next_weekly_cron'])) : ''; ?>" style="color-scheme:dark;">
                </div>
                <button type="submit" name="run_weekly_check" class="btn" style="background:linear-gradient(45deg, #ff0055, #ff5500); color:#fff;">FORCE RUN WEEKLY</button>
                <div class="inp-grp">
                    <label class="inp-lbl" style="color:red;">Name Change Expiry Msg</label>
                    <textarea name="tg_nc_msg" rows="4"><?php echo $sets['tg_nc_msg']??''; ?></textarea>
                </div>
                <div class="inp-grp">
                    <label class="inp-lbl" style="color:orange;">Weekly Reminder Msg</label>
                    <textarea name="tg_weekly_msg" rows="4"><?php echo $sets['tg_weekly_msg']??''; ?></textarea>
                </div>
                <button type="submit" name="update_tg_bot" class="btn btn-main">Save Bot Settings</button>
            </form>
        </div>

    </div>
</div>

<!-- MODAL -->
<div id="modEdit" class="modal">
    <div class="modal-body">
        <div style="display:flex; justify-content:space-between; margin-bottom:15px;">
            <span id="eName" style="color:cyan; font-size:18px; font-weight:bold;">PLAYER</span>
            <span onclick="document.getElementById('modEdit').style.display='none'" style="color:red; cursor:pointer; font-size:24px;">&times;</span>
        </div>
        <form method="post" id="editForm">
            <input type="hidden" name="edit_id" id="eid">
            <input type="hidden" name="action_type" id="atype">
            <div class="smart-box">
                <label class="inp-lbl" style="color:#ff9900;"><i class="fas fa-calculator"></i> INPUT NEW TOTAL</label>
                <div style="display:flex; gap:10px;">
                    <input type="number" name="smart_total_inp" id="inpSmart" onkeyup="smartLive()" style="font-size:18px; border-color:#ff9900;">
                    <button type="button" onclick="subSmart()" class="btn btn-set">UPDATE</button>
                </div>
                <div id="smartPrev" class="live-prev"><span id="resTxt" class="hl-txt"></span></div>
            </div>
            <button type="button" class="btn-link" onclick="toggleMan()">Manual Edit</button>
            <div id="manBox" class="manual-box">
                <div class="inp-grp"><label class="inp-lbl">Weekly</label><input type="number" name="man_weekly" id="mWe"></div>
                <div class="inp-grp"><label class="inp-lbl">Total</label><input type="number" name="man_total" id="mTo"></div>
                <button type="button" onclick="subMan()" class="btn" style="background:#0088cc;">FORCE SAVE</button>
            </div>
            <hr style="border-color:#333; margin:15px 0;">
            <div class="inp-grp" style="background:#151515; padding:10px; border-radius:5px;">
                <label class="toggle-switch" style="margin:0;"><input type="checkbox" name="nc_status" id="enc_cb" onchange="toggleDateBox('edit')"><span class="slider"></span> <span>Name Change Req?</span></label>
                <div id="edit_nc_box" class="date-reveal"><label class="inp-lbl">Deadline</label><input type="datetime-local" name="nc_date" id="encdate"></div>
            </div>
            <div class="inp-grp"><label class="inp-lbl">Rank</label>
                <select name="edit_rank" id="erank" onchange="toggleEditOff()"><option value="Member">Member</option><option value="Officer">Officer</option><option value="Active Leader">Active Leader</option><option value="Leader">Leader</option><option value="Admin">Admin</option></select>
            </div>
            <div id="edit_off" style="display:none; padding:10px; border:1px solid #333; margin-bottom:10px;">
                <div class="inp-grp"><input type="text" name="wa_num" id="ewa" placeholder="WhatsApp"></div>
                <div class="inp-grp"><input type="text" name="tg_link" id="etg" placeholder="Telegram"></div>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px;">
                <div class="inp-grp"><label class="inp-lbl">Join Date</label><input type="date" name="edit_join_date" id="edate"></div>
                <div class="inp-grp"><label class="inp-lbl">Behavior Score</label><input type="number" name="behavior_score" id="ebeh"></div>
                <div class="inp-grp"><label class="inp-lbl">Tournament Squad</label><select name="edit_tournament" id="etourn"><option value="no">No</option><option value="yes">Yes</option></select></div>
            </div>
            <button type="button" onclick="subMainSave()" class="btn btn-main">SAVE CHANGES</button>
            <div class="ban-ctrl-box">
                <h4 style="color:#ff3333; font-size:12px; margin:0 0 10px 0;">BAN CONTROL</h4>
                <div id="banFields">
                    <input type="text" name="ban_reason" id="breason" placeholder="Reason...">
                    <button type="button" onclick="confirmBan()" class="btn" style="background:red;">BAN PLAYER</button>
                </div>
                <div id="unbanFields" style="display:none;">
                    <p id="currBanReason" style="color:#aaa; font-size:11px;"></p>
                    <button type="button" onclick="confirmUnban()" class="btn" style="background:#00ff9d; color:#000;">UNBAN PLAYER</button>
                </div>
            </div>
            <button type="button" class="btn" style="background:#330000; color:red; margin-top:10px;" onclick="confirmDeleteMember()">DELETE MEMBER</button>
            <input type="hidden" id="curTotal"><input type="hidden" id="curWeekly">
        </form>
    </div>
</div>

<script>
function goTab(id, btn){ document.querySelectorAll('.page-sec').forEach(x=>x.style.display='none'); document.getElementById(id).style.display='block'; document.querySelectorAll('.t-btn').forEach(x=>x.classList.remove('active')); btn.classList.add('active'); }
function act(t){ document.getElementById('atype').value=t; }
function toggleAddOff(v) { document.getElementById('add_off').style.display = (v!='Member') ? 'block':'none'; }
function toggleEditOff() { var v=document.getElementById('erank').value; document.getElementById('edit_off').style.display = (v!='Member') ? 'block':'none'; }
function toggleDateBox(m) { if(m=='add') document.getElementById('add_nc_box').style.display = document.getElementById('add_nc_cb').checked ? 'block':'none'; else document.getElementById('edit_nc_box').style.display = document.getElementById('enc_cb').checked ? 'block':'none'; }
function toggleMan() { var b=document.getElementById('manBox'); b.style.display = (b.style.display=='none') ? 'block':'none'; }
function subSmart() { act('smart_update'); document.getElementById('editForm').submit(); }
function subMan() { act('manual_override'); document.getElementById('editForm').submit(); }
function subMainSave() { act('main_save'); document.getElementById('editForm').submit(); }
function confirmBan() { if(document.getElementById('breason').value == "") { alert("Reason needed!"); return; } if(confirm("Ban?")) { act('ban_player'); document.getElementById('editForm').submit(); } }
function confirmUnban() { if(confirm("Unban?")) { act('unban_player'); document.getElementById('editForm').submit(); } }
function confirmDeleteMember() { var memberId = document.getElementById('eid').value; if(memberId && confirm('Are you sure you want to delete?')) { window.location.href = 'index.php?delete=' + memberId; } }

function openMod(d) {
    document.getElementById('modEdit').style.display='flex';
    document.getElementById('eid').value = d.id;
    document.getElementById('eName').innerText = d.game_name.toUpperCase();
    document.getElementById('curTotal').value = d.total_dogtags; 
    document.getElementById('curWeekly').value = d.weekly_dogtags; 
    document.getElementById('mWe').value = d.weekly_dogtags;
    document.getElementById('mTo').value = d.total_dogtags;
    document.getElementById('erank').value = d.rank;
    document.getElementById('edate').value = d.join_date;
    document.getElementById('ebeh').value = d.behavior_score;
    document.getElementById('etourn').value = d.tournament_status;
    document.getElementById('ewa').value = d.whatsapp_number;
    document.getElementById('etg').value = d.telegram_username;
    toggleEditOff(); 
    document.getElementById('enc_cb').checked = (d.name_change_status==1);
    toggleDateBox('edit'); 
    if(d.name_change_date) document.getElementById('encdate').value = d.name_change_date.replace(" ","T");
    if(d.is_banned == 1) {
        document.getElementById('banFields').style.display = 'none';
        document.getElementById('unbanFields').style.display = 'block';
        document.getElementById('currBanReason').innerText = "Reason: " + d.ban_reason;
    } else {
        document.getElementById('banFields').style.display = 'block';
        document.getElementById('unbanFields').style.display = 'none';
        document.getElementById('breason').value = '';
    }
}

function smartLive() {
    var newInp = parseInt(document.getElementById('inpSmart').value) || 0;
    var oldT = parseInt(document.getElementById('curTotal').value) || 0;
    var oldW = parseInt(document.getElementById('curWeekly').value) || 0;
    if(newInp !== 0) {
        var diff = newInp - oldT;
        var finalW = oldW + diff;
        if(finalW < 0) finalW = 0;
        document.getElementById('smartPrev').style.display='block';
        document.getElementById('resTxt').innerText = "New Weekly: " + finalW;
    } else { document.getElementById('smartPrev').style.display='none'; }
}

function filterList(targetId) {
    var srcId = (targetId == 'memList') ? 'srcBox' : 'srcBoxBan';
    var v = document.getElementById(srcId).value.toUpperCase();
    var list = document.getElementById(targetId).children;
    for(var i=0; i<list.length; i++) list[i].style.display = list[i].innerText.toUpperCase().includes(v) ? 'flex' : 'none';
}

function fetchNameManual() {
    let uid = document.getElementById('add_uid_inp').value;
    let nameBox = document.getElementById('add_name_inp');
    let btn = document.getElementById('btnCheckName');
    if(uid.length < 5) { alert("Invalid UID!"); return; }
    btn.innerHTML = '...';
    fetch('index.php?fetch_uid_name=' + uid).then(res => res.text()).then(data => {
        if(data.trim() !== "") nameBox.value = data.trim();
        else alert("Not Found!");
        btn.innerHTML = '<i class="fas fa-search"></i> CHECK';
    });
}

// --- [NEW] AUTO GUILD CHECKER SCRIPT ---
let activeUIDs = <?php echo json_encode($active_uids); ?>;
let currentIndex = 0;

function runAutoGuildCheck() {
    if (activeUIDs.length === 0) return;
    let uid = activeUIDs[currentIndex];
    let statusLabel = document.getElementById('auto_status');
    statusLabel.innerHTML = `<i class="fas fa-sync fa-spin"></i> Checking: ${uid}...`;

    fetch('index.php?auto_guild_check=' + uid)
    .then(res => res.text())
    .then(text => {
        let parts = text.split('|');
        let status = parts[0];
        let guildName = parts[1] || 'N/A';

        if (status === "STAY") {
            statusLabel.innerHTML = `<i class="fas fa-check-circle"></i> ${uid} | ${guildName} (Verified)`;
            let card = document.querySelector(`[data-uid="${uid}"]`);
            if(card) {
                let icon = card.querySelector('.fa-check-circle');
                icon.parentElement.className = 'check-green';
            }
        } else if (status === "BANNED") {
            statusLabel.innerHTML = `<i class="fas fa-user-slash" style="color:red;"></i> ${uid} BANNED FROM ${guildName}`;
        } else {
            statusLabel.innerHTML = `<i class="fas fa-question-circle"></i> ${uid} Not Found`;
        }
        
        currentIndex++;
        if (currentIndex >= activeUIDs.length) {
            currentIndex = 0;
            setTimeout(runAutoGuildCheck, 60000); 
        } else {
            setTimeout(runAutoGuildCheck, 4000); 
        }
    })
    .catch(err => {
        currentIndex++;
        setTimeout(runAutoGuildCheck, 4000);
    });
}
setTimeout(runAutoGuildCheck, 5000);
</script>
</body>
</html>