<?php
require_once "config.php";

if (!isset($conn) || !($conn instanceof mysqli)) {
    die(json_encode(["status" => "error", "message" => "Database connection error"]));
}
$conn->set_charset("utf8mb4");

if (isset($_POST['type']) && in_array($_POST['type'], ['list', 'check', 'change'])) {
    $type = $_POST['type'];
    
    if ($type === "change") {
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) {
            echo "ID Missing";
            exit;
        }
        $stmt = $conn->prepare("UPDATE device_ban SET ban_status = 0 WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute() && $stmt->affected_rows > 0) {
            echo "Device Unbanned Successfully";
        } else {
            echo "Invalid ID or Already Unbanned";
        }
        $stmt->close();
        exit;
    }

    if ($type === "list") {
        $result = $conn->query("SELECT device_id, id, ban_status, created_at FROM device_ban WHERE ban_status = 1 ORDER BY id DESC");
        $banned_devices = [];
        while ($row = $result->fetch_assoc()) {
            $banned_devices[] = [
                "device_id" => $row['device_id'],
                "id" => $row['id'],
                "ban_status" => (int)$row['ban_status'],
                "date" => $row['created_at']
            ];
        }
        echo json_encode($banned_devices);
        exit;
    }
    
    if ($type === "check") {
        $device_id = $_POST['device_id'] ?? null;
        if (!$device_id) {
            echo "Device ID Missing";
            exit;
        }
        $stmt = $conn->prepare("SELECT ban_status FROM device_ban WHERE device_id = ?");
        $stmt->bind_param("s", $device_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            echo ((int)$row['ban_status'] === 1) ? "Your device is banned" : "Device allowed";
        } else {
            echo "Device not found, allowed";
        }
        $stmt->close();
        exit;
    }
}

session_set_cookie_params(0);
session_start();
date_default_timezone_set("Asia/Dhaka");

function session_alive(): bool {
    return !empty($_SESSION['auth_logged_in']);
}

if (!session_alive()) {
    if (isset($_GET['api'])) die(json_encode(["status" => "unauthorized"]));
    header("Location: admin_login.php");
    exit;
}

$role = $_SESSION['auth_role'] ?? '';
$sess_username = $_SESSION['auth_username'] ?? '';
$sess_password = $_SESSION['auth_password'] ?? '';

$canRead = false;
$canEdit = false;
$canDelete = false;

if ($role === 'admin') {
    $canRead = true;
    $canEdit = true;
    $canDelete = true;
} elseif ($role === 'permission') {
    $stmt = $conn->prepare("SELECT members_read, members_edit, members_delete FROM `Zabbar_Admin_Permission` WHERE username = ? AND password = ? LIMIT 1");
    $stmt->bind_param("ss", $sess_username, $sess_password);
    $stmt->execute();
    if ($row = $stmt->get_result()->fetch_assoc()) {
        $canRead = ($row['members_read'] === 'Yes' || $row['members_read'] == 1);
        $canEdit = ($row['members_edit'] === 'Yes' || $row['members_edit'] == 1);
        $canDelete = ($row['members_delete'] === 'Yes' || $row['members_delete'] == 1);
    }
    $stmt->close();
}

function fcm_base64url_encode($data) { 
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

function fcm_get_access_token($jsonFilePath) {
    if (!file_exists($jsonFilePath)) return false;
    $credentials = json_decode(file_get_contents($jsonFilePath), true);
    if (!$credentials || !isset($credentials['private_key'])) return false;

    $clientEmail = $credentials['client_email'];
    $privateKey  = $credentials['private_key'];

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $now = time();
    $payload = json_encode([
        'iss'   => $clientEmail,
        'scope' => 'https://www.googleapis.com/auth/cloud-platform',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now
    ]);

    $unsignedJwt = fcm_base64url_encode($header) . "." . fcm_base64url_encode($payload);
    $signature = '';
    openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $jwt = $unsignedJwt . "." . fcm_base64url_encode($signature);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);
    return $responseData['access_token'] ?? false;
}

function sendFcmDataMessage($projectId, $accessToken, $topic, $dataPayload) {
    $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";
    
    $message = [
        "message" => [
            "topic" => $topic,
            "data" => $dataPayload
        ]
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken, 
        'Content-Type: application/json; UTF-8'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return $httpCode === 200;
}

if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    if (!$canRead) {
        echo json_encode(["status" => "error", "message" => "Permission denied."]);
        exit;
    }

    $action = $_GET['api'];
    $page = max(1, (int)($_GET['page'] ?? 1));
    $tab = $_GET['tab'] ?? 'all';
    $search = trim($_GET['search'] ?? '');
    $limit = 100;
    $offset = ($page - 1) * $limit;

    if ($action === 'fetch') {
        if ($tab === 'moderator' && $role === 'admin') {
            $where = "1=1"; $params = []; $types = "";
            if ($search !== '') {
                $where .= " AND username LIKE ?";
                $params[] = "%$search%";
                $types .= "s";
            }
            $cStmt = $conn->prepare("SELECT COUNT(*) as total FROM `Zabbar_Admin_Permission` WHERE $where");
            if (!empty($types)) $cStmt->bind_param($types, ...$params);
            $cStmt->execute();
            $totalUsers = $cStmt->get_result()->fetch_assoc()['total'] ?? 0;
            $totalPages = ceil($totalUsers / $limit);
            $cStmt->close();

            $sql = "SELECT username, password FROM `Zabbar_Admin_Permission` WHERE $where ORDER BY username ASC LIMIT ? OFFSET ?";
            $params[] = $limit; $params[] = $offset; $types .= "ii";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            echo json_encode(["status" => "success", "data" => $data, "page" => $page, "totalPages" => $totalPages, "total" => $totalUsers]);
            exit;
        }

        if ($tab === 'device') {
            $where = "1=1"; $params = []; $types = "";
            if ($search !== '') {
                $where .= " AND device_id LIKE ?";
                $params[] = "%$search%";
                $types .= "s";
            }
            $cStmt = $conn->prepare("SELECT COUNT(*) as total FROM device_ban WHERE $where");
            if (!empty($types)) $cStmt->bind_param($types, ...$params);
            $cStmt->execute();
            $totalDevices = $cStmt->get_result()->fetch_assoc()['total'] ?? 0;
            $totalPages = ceil($totalDevices / $limit);
            $cStmt->close();

            $sql = "SELECT id, device_id, ban_status, created_at FROM device_ban WHERE $where ORDER BY id DESC LIMIT ? OFFSET ?";
            $params[] = $limit; $params[] = $offset; $types .= "ii";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();

            echo json_encode(["status" => "success", "data" => $data, "page" => $page, "totalPages" => $totalPages, "total" => $totalDevices]);
            exit;
        }

        $where = "1=1"; $params = []; $types = "";
        if ($search !== '') {
            $search_param = "{$search}%";
            $exact_device = $search;
            $where .= " AND (username LIKE ? OR email LIKE ? OR device_id = ?)";
            array_push($params, $search_param, $search_param, $exact_device);
            $types .= "sss";
        }

        $cStmt = $conn->prepare("SELECT COUNT(id) as total FROM users WHERE $where");
        if (!empty($types)) $cStmt->bind_param($types, ...$params);
        $cStmt->execute();
        $totalUsers = $cStmt->get_result()->fetch_assoc()['total'];
        $totalPages = ceil($totalUsers / $limit);
        $cStmt->close();

        if ($search !== '') {
            $sql = "SELECT * FROM users WHERE $where ORDER BY (username = ?) DESC, (device_id = ?) DESC, (username LIKE ? OR email LIKE ?) DESC, username ASC LIMIT ? OFFSET ?";
            $params_order = $params;
            $types_order = $types;
            array_push($params_order, $search, $exact_device, $search_param, $search_param, $limit, $offset);
            $types_order .= "ssssii";
        } else {
            $sql = "SELECT * FROM users WHERE $where ORDER BY id DESC LIMIT ? OFFSET ?";
            $params_order = $params;
            $types_order = $types;
            array_push($params_order, $limit, $offset);
            $types_order .= "ii";
        }
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types_order, ...$params_order);
        $stmt->execute();
        $data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        echo json_encode(["status" => "success", "data" => $data, "page" => $page, "totalPages" => $totalPages, "total" => $totalUsers]);
        exit;
    }

    if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) { echo json_encode(["status" => "error", "message" => "Denied"]); exit; }
        
        $id = (int)$_POST['id'];
        $status = $_POST['status'] ?? 'unban';
        $username = $_POST['username'] ?? '';
        $target_device = $_POST['device_id'] ?? '';
        $banReason = $_POST['ban_reason'] ?? 'Banned by admin';
        $banDeviceAlso = isset($_POST['ban_device_also']) && $_POST['ban_device_also'] == '1';
        
        if ($status === 'ban') {
            $serviceAccountFile = 'noti.json';
            $accessToken = fcm_get_access_token($serviceAccountFile);
            
            if ($accessToken) {
                $credentials = json_decode(file_get_contents($serviceAccountFile), true);
                $projectId = $credentials['project_id'];
                
                $dataPayload = [
                    "title" => $username . " কে ব্যান করা হইছে",
                    "body" => $banReason,
                    "image" => "",
                    "extra" => ""
                ];
                
                sendFcmDataMessage($projectId, $accessToken, "ttt", $dataPayload);
            }

            if ($banDeviceAlso && !empty($target_device)) {
                $dStmt = $conn->prepare("INSERT INTO device_ban (device_id, ban_status, created_at) VALUES (?, 1, NOW()) ON DUPLICATE KEY UPDATE ban_status = 1");
                $dStmt->bind_param("s", $target_device);
                $dStmt->execute();
                $dStmt->close();
            }
        } elseif ($status === 'unban') {
            if (!empty($target_device)) {
                $dStmt = $conn->prepare("UPDATE device_ban SET ban_status = 0 WHERE device_id = ?");
                $dStmt->bind_param("s", $target_device);
                $dStmt->execute();
                $dStmt->close();
            }
        }

        $fields = ['username', 'email', 'number', 'password', 'balance', 'first_deposit_done', 'winning', 'total_paid', 'total_win', 'refer_earn', 'total_refer', 'fcm_key', 'device_id', 'total_play', 'total_kill', 'status', 'reg_date', 'referred_by', 'token', 'profile_pic', 'verify_badge', 'withdraw_block', 'withdraw_block_time', 'wd_limit', 'last_wd_date', 'ban_reason', 'device_name', 'uid'];
        $set = []; $types = ""; $params = [];
        
        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                $set[] = "$field = ?"; $types .= "s"; $params[] = $_POST[$field];
            }
        }
        if (empty($set)) { echo json_encode(["status" => "error", "message" => "No data"]); exit; }
        
        $types .= "i"; $params[] = $id;
        $stmt = $conn->prepare("UPDATE users SET " . implode(", ", $set) . " WHERE id = ?");
        $stmt->bind_param($types, ...$params);
        $success = $stmt->execute();
        echo json_encode(["status" => $success ? "success" : "error", "message" => $stmt->error]);
        $stmt->close();
        exit;
    }

    if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canDelete) { echo json_encode(["status" => "error", "message" => "Denied"]); exit; }
        $id = (int)$_POST['id'];
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        $success = $stmt->execute();
        echo json_encode(["status" => $success ? "success" : "error", "message" => $stmt->error]);
        $stmt->close();
        exit;
    }

    if ($action === 'delete_moderator' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if ($role !== 'admin') { echo json_encode(["status" => "error", "message" => "Only admin can delete moderators"]); exit; }
        $mod_username = $_POST['username'] ?? '';
        $mod_password = $_POST['password'] ?? '';
        if (empty($mod_username) || empty($mod_password)) {
            echo json_encode(["status" => "error", "message" => "Missing credentials"]);
            exit;
        }
        $stmt = $conn->prepare("DELETE FROM `Zabbar_Admin_Permission` WHERE username = ? AND password = ?");
        $stmt->bind_param("ss", $mod_username, $mod_password);
        $success = $stmt->execute();
        if ($success && $stmt->affected_rows > 0) {
            echo json_encode(["status" => "success"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Moderator not found or delete failed"]);
        }
        $stmt->close();
        exit;
    }

    if ($action === 'unban_device' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) { echo json_encode(["status" => "error", "message" => "Denied"]); exit; }
        $device_id = $_POST['device_id'] ?? '';
        if (empty($device_id)) { echo json_encode(["status" => "error", "message" => "Device ID missing"]); exit; }
        $stmt = $conn->prepare("UPDATE device_ban SET ban_status = 0 WHERE device_id = ?");
        $stmt->bind_param("s", $device_id);
        $success = $stmt->execute();
        echo json_encode(["status" => $success ? "success" : "error", "message" => $stmt->error]);
        $stmt->close();
        exit;
    }

    if ($action === 'ban_device' && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!$canEdit) { echo json_encode(["status" => "error", "message" => "Denied"]); exit; }
        $device_id = $_POST['device_id'] ?? '';
        if (empty($device_id)) { echo json_encode(["status" => "error", "message" => "Device ID missing"]); exit; }
        $stmt = $conn->prepare("INSERT INTO device_ban (device_id, ban_status, created_at) VALUES (?, 1, NOW()) ON DUPLICATE KEY UPDATE ban_status = 1");
        $stmt->bind_param("s", $device_id);
        $success = $stmt->execute();
        echo json_encode(["status" => $success ? "success" : "error", "message" => $stmt->error]);
        $stmt->close();
        exit;
    }

    exit;
}

if (!$canRead) {
    die("<!DOCTYPE html><html><body style='font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0;background:#f8fafc;'><div style='text-align:center;padding:40px;background:#fff;border-radius:16px;box-shadow:0 10px 15px -3px rgba(0,0,0,0.1);'><h2 style='color:#be123c;'>Access Denied</h2></div></body></html>");
}

require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { --bg-body: #f4f7fe; --bg-card: #ffffff; --text-main: #2b3674; --text-muted: #a3aed1; --primary: #4318ff; --primary-light: #e9e3ff; --accent: #00b5ff; --success: #01b574; --danger: #ee5d50; --border: #e0e5f2; --radius-md: 12px; --radius-lg: 20px; --shadow: 0px 18px 40px rgba(112, 144, 176, 0.12); }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Plus Jakarta Sans', sans-serif; }
        body { background-color: var(--bg-body); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        .sidebar { width: 280px; background: var(--bg-card); border-right: 1px solid var(--border); display: flex; flex-direction: column; }
        .sidebar-brand { padding: 32px 24px; display: flex; align-items: center; gap: 14px; }
        .brand-logo { width: 44px; height: 44px; background: linear-gradient(135deg, var(--primary), var(--accent)); border-radius: var(--radius-md); display: flex; align-items: center; justify-content: center; color: #fff; font-size: 22px; font-weight: 800; }
        .brand-text h2 { font-size: 18px; font-weight: 800; letter-spacing: -0.5px; }
        .sidebar-menu { padding: 0 16px 24px; flex-grow: 1; display: flex; flex-direction: column; gap: 6px; }
        .menu-item { display: flex; align-items: center; gap: 14px; padding: 14px 18px; color: var(--text-muted); text-decoration: none; font-weight: 600; font-size: 15px; border-radius: var(--radius-md); transition: 0.3s; }
        .menu-item.active, .menu-item:hover { background: var(--bg-body); color: var(--primary); transform: translateX(4px); }
        .menu-item svg { width: 22px; height: 22px; }
        .main-content { flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; }
        .topbar { padding: 24px 40px; background: rgba(255, 255, 255, 0.7); backdrop-filter: blur(16px); border-bottom: 1px solid rgba(255, 255, 255, 0.5); display: flex; justify-content: space-between; align-items: center; z-index: 10; flex-wrap: wrap; gap: 16px; }
        .tabs-container { display: flex; gap: 12px; background: var(--bg-card); padding: 6px; border-radius: 50px; box-shadow: 0 2px 10px rgba(0,0,0,0.03); border: 1px solid var(--border); }
        .tab-btn { padding: 10px 24px; border-radius: 50px; border: none; background: transparent; font-weight: 700; font-size: 14px; color: var(--text-muted); cursor: pointer; transition: 0.3s; }
        .tab-btn.active { background: var(--primary); color: #fff; box-shadow: 0 4px 12px rgba(67, 24, 255, 0.2); }
        .search-box { display: flex; align-items: center; background: var(--bg-card); padding: 10px 20px; border-radius: 50px; border: 1px solid var(--border); box-shadow: 0 2px 10px rgba(0,0,0,0.03); width: 300px; gap: 10px; }
        .search-box input { border: none; background: transparent; outline: none; width: 100%; color: var(--text-main); font-weight: 600; font-size: 14px; }
        .search-box svg { color: var(--text-muted); width: 18px; }
        .content-body { padding: 40px; overflow-y: auto; flex-grow: 1; }
        .user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 24px; }
        .user-card { background: var(--bg-card); border: 1px solid transparent; border-radius: var(--radius-lg); padding: 24px; box-shadow: var(--shadow); display: flex; align-items: center; justify-content: space-between; transition: 0.3s; cursor: pointer; animation: slideUp 0.4s ease backwards; position: relative; }
        .user-card:hover { border-color: var(--primary-light); transform: translateY(-4px); }
        .user-info { display: flex; align-items: center; gap: 16px; flex-grow: 1; overflow: hidden; }
        .user-avatar { width: 54px; height: 54px; border-radius: 50%; object-fit: cover; background: var(--bg-body); padding: 2px; border: 2px solid var(--primary-light); flex-shrink: 0; }
        .user-details h4 { font-size: 16px; font-weight: 800; display: flex; align-items: center; gap: 6px; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .verify-badge { color: var(--primary); width: 18px; height: 18px; flex-shrink: 0; }
        .user-details p { font-size: 13px; color: var(--text-muted); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .card-actions-right { display: flex; flex-direction: column; align-items: flex-end; gap: 10px; flex-shrink: 0; }
        .win-badge { padding: 6px 14px; background: var(--primary-light); color: var(--primary); border-radius: 50px; font-size: 13px; font-weight: 800; }
        .device-badge { padding: 6px 14px; border-radius: 50px; font-size: 12px; font-weight: 700; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .user-action-btns { display: flex; gap: 8px; }
        .u-btn { width: 34px; height: 34px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #fff; text-decoration: none; transition: 0.3s; }
        .u-money { background: linear-gradient(135deg, var(--success), #00d284); box-shadow: 0 4px 10px rgba(1, 181, 116, 0.2); }
        .u-noti { background: linear-gradient(135deg, var(--accent), #00c6ff); box-shadow: 0 4px 10px rgba(0, 181, 255, 0.2); }
        .u-btn:hover { transform: translateY(-2px) scale(1.05); }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .pagination { display: flex; align-items: center; justify-content: space-between; padding: 20px; background: var(--bg-card); border-radius: var(--radius-lg); box-shadow: var(--shadow); margin-top: 32px; }
        .page-btn { padding: 10px 24px; border: none; background: var(--bg-body); border-radius: 50px; font-weight: 700; cursor: pointer; color: var(--text-main); transition: 0.3s; }
        .page-btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .page-btn:not(:disabled):hover { background: var(--primary); color: #fff; }
        .page-info { font-size: 15px; font-weight: 700; color: var(--text-main); }
        .modal-overlay { position: fixed; inset: 0; background: rgba(11, 20, 55, 0.7); display: none; place-items: center; z-index: 100; backdrop-filter: blur(8px); padding: 20px; overflow-y: auto; }
        .modal { background: var(--bg-card); width: 100%; max-width: 800px; border-radius: var(--radius-lg); box-shadow: var(--shadow); position: relative; margin: auto; }
        .modal-header { padding: 24px 32px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { font-size: 20px; font-weight: 800; color: var(--text-main); }
        .close-btn { background: var(--bg-body); border: none; width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; cursor: pointer; color: var(--text-main); transition: 0.3s; }
        .close-btn:hover { background: var(--danger); color: #fff; }
        .close-btn svg { width: 20px; height: 20px; }
        .modal-body { padding: 32px; max-height: 65vh; overflow-y: auto; }
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
        .form-group { display: flex; flex-direction: column; gap: 8px; }
        .form-group label { font-size: 14px; font-weight: 700; color: var(--text-main); }
        .form-control { padding: 14px 18px; border: 1px solid var(--border); border-radius: 12px; font-size: 14px; font-weight: 500; outline: none; transition: 0.3s; background: var(--bg-body); color: var(--text-main); }
        .form-control:focus { border-color: var(--primary); background: #fff; box-shadow: 0 0 0 4px var(--primary-light); }
        select.form-control { appearance: none; background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%232b3674' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); background-repeat: no-repeat; background-position: right 16px center; background-size: 16px; padding-right: 48px; }
        .modal-footer { padding: 24px 32px; border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: var(--bg-body); border-radius: 0 0 var(--radius-lg) var(--radius-lg); }
        .btn { padding: 12px 28px; border-radius: 50px; font-weight: 700; cursor: pointer; border: none; transition: 0.3s; font-size: 14px; }
        .btn-primary { background: var(--primary); color: #fff; box-shadow: 0 4px 12px rgba(67, 24, 255, 0.2); }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(67, 24, 255, 0.3); }
        .btn-danger { background: var(--danger); color: #fff; box-shadow: 0 4px 12px rgba(238, 93, 80, 0.2); }
        .btn-danger:hover { transform: translateY(-2px); }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
        @media (max-width: 1024px) { .sidebar { width: 80px; } .brand-text, .menu-item span { display: none; } }
        @media (max-width: 768px) { body { flex-direction: column; } .sidebar { width: 100%; height: auto; border-right: none; border-bottom: 1px solid var(--border); flex-direction: row; align-items: center; padding: 0 20px; } .sidebar-menu { display: flex; flex-direction: row; padding: 10px 0; overflow-x: auto; margin-bottom: 0; } .topbar { flex-direction: column; align-items: stretch; padding: 20px; } .search-box { width: 100%; } .content-body { padding: 20px; } .form-grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>

<div class="main-content">
    <div class="topbar">
        <div class="tabs-container">
            <button class="tab-btn active" data-tab="all" onclick="setTab('all')">All Users</button>
            <?php if ($role === 'admin'): ?>
            <button class="tab-btn" data-tab="moderator" onclick="setTab('moderator')">Moderator</button>
            <?php endif; ?>
            <button class="tab-btn" data-tab="device" onclick="setTab('device')">Devices</button>
        </div>
        <div class="search-box">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" /></svg>
            <input type="text" id="searchInput" placeholder="Search..." oninput="debounceSearch()">
        </div>
    </div>
    <div class="content-body">
        <div class="user-grid" id="userGrid"></div>
        <div class="pagination">
            <button class="page-btn" id="prevBtn" onclick="changePage(-1)">Previous</button>
            <div class="page-info" id="pageInfo">Page 1</div>
            <button class="page-btn" id="nextBtn" onclick="changePage(1)">Next</button>
        </div>
    </div>
</div>

<div class="modal-overlay" id="editModal">
    <div class="modal">
        <div class="modal-header">
            <h3>Edit Profile</h3>
            <button class="close-btn" onclick="closeModal()"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg></button>
        </div>
        <div class="modal-body">
            <form id="editForm">
                <input type="hidden" id="e_id" name="id">
                <div class="form-grid">
                    <div class="form-group"><label>Username</label><input type="text" class="form-control" name="username" id="e_username"></div>
                    <div class="form-group"><label>Password</label><input type="text" class="form-control" name="password" id="e_password"></div>
                    <div class="form-group"><label>Email</label><input type="text" class="form-control" name="email" id="e_email"></div>
                    <div class="form-group"><label>Number</label><input type="text" class="form-control" name="number" id="e_number"></div>
                    <div class="form-group"><label>Balance</label><input type="number" class="form-control" name="balance" id="e_balance" step="0.01"></div>
                    <div class="form-group"><label>Winning</label><input type="number" class="form-control" name="winning" id="e_winning" step="0.01"></div>
                    <div class="form-group"><label>Verify Badge</label><select class="form-control" name="verify_badge" id="e_verify_badge"><option value="1">Verified</option><option value="0">Unverified</option></select></div>
                    <div class="form-group"><label>Total Refer</label><input type="number" class="form-control" name="total_refer" id="e_total_refer"></div>
                    <div class="form-group"><label>Profile Picture URL</label><input type="text" class="form-control" name="profile_pic" id="e_profile_pic"></div>
                    <div class="form-group"><label>Withdraw Block</label><select class="form-control" name="withdraw_block" id="e_withdraw_block"><option value="0">No</option><option value="1">Yes</option></select></div>
                    <div class="form-group">
                        <label>Status</label>
                        <select class="form-control" name="status" id="e_status" onchange="handleStatusChange(this)">
                            <option value="unban">Unban</option>
                            <option value="ban">Ban</option>
                        </select>
                    </div>
                    <div class="form-group"><label>Device ID</label><input type="text" class="form-control" name="device_id" id="e_device_id" readonly style="background:var(--border); color:var(--text-muted);"></div>
                    <div class="form-group" id="ban_reason_group" style="display:none; grid-column: span 2;">
                        <label>Ban Reason</label>
                        <input type="text" class="form-control" name="ban_reason" id="e_ban_reason" placeholder="Write reason if banned">
                    </div>
                    <div class="form-group" id="ban_device_group" style="display:none; flex-direction:row; align-items:center; gap:10px; grid-column: span 2;">
                        <input type="checkbox" name="ban_device_also" id="ban_device_also" value="1" style="width:18px;height:18px;cursor:pointer;">
                        <label for="ban_device_also" style="color:var(--danger); cursor:pointer;">Ban this Device Also</label>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <div><?php if ($canDelete): ?><button type="button" class="btn btn-danger" onclick="deleteUser()">Delete User</button><?php endif; ?></div>
            <div style="display:flex; gap:12px;"><button type="button" class="btn" onclick="closeModal()" style="background:var(--border); color:var(--text-main);">Cancel</button><?php if ($canEdit): ?><button type="button" class="btn btn-primary" onclick="saveUser()">Save Changes</button><?php endif; ?></div>
        </div>
    </div>
</div>
<script>
    let currentPage = 1, currentTab = 'all', usersData = [], searchTimeout;
    const canEdit = <?= $canEdit ? 'true' : 'false' ?>;
    const isAdmin = <?= $role === 'admin' ? 'true' : 'false' ?>;

    function debounceSearch() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => { currentPage = 1; loadUsers(1); }, 400);
    }

    function setTab(tab) {
        currentTab = tab;
        document.querySelectorAll('.tab-btn').forEach(t => t.classList.remove('active'));
        let tBtn = document.querySelector(`.tab-btn[data-tab="${tab}"]`);
        if(tBtn) tBtn.classList.add('active');
        currentPage = 1; loadUsers(1);
    }

    function handleStatusChange(sel) {
        let reasonGroup = document.getElementById('ban_reason_group');
        let deviceGroup = document.getElementById('ban_device_group');
        let reasonInput = document.getElementById('e_ban_reason');
        let deviceCheck = document.getElementById('ban_device_also');

        if(sel.value === 'ban') {
            reasonGroup.style.display = 'flex';
            deviceGroup.style.display = 'flex';
            let reason = prompt("কি কারণে Ban করছেন তা লিখুন:");
            if(reason && reason.trim() !== "") {
                reasonInput.value = reason;
            } else {
                sel.value = 'unban';
                reasonInput.value = '';
                reasonGroup.style.display = 'none';
                deviceGroup.style.display = 'none';
                deviceCheck.checked = false;
            }
        } else {
            reasonInput.value = '';
            reasonGroup.style.display = 'none';
            deviceGroup.style.display = 'none';
            deviceCheck.checked = false;
        }
    }

    function loadUsers(page) {
        let search = document.getElementById('searchInput').value;
        fetch(`UserInfo.php?api=fetch&page=${page}&tab=${currentTab}&search=${encodeURIComponent(search)}`)
            .then(res => res.json()).then(res => {
                if (res.status === 'success') {
                    usersData = res.data; currentPage = res.page; renderGrid(usersData);
                    document.getElementById('pageInfo').innerText = `Page ${currentPage} of ${res.totalPages} (${res.total} total)`;
                    document.getElementById('prevBtn').disabled = currentPage <= 1;
                    document.getElementById('nextBtn').disabled = currentPage >= res.totalPages;
                }
            });
    }

    function unbanDevice(device_id, event) {
        event.stopPropagation();
        if (!confirm('Are you sure you want to unban this device?')) return;
        const formData = new FormData(); 
        formData.append('device_id', device_id);
        fetch('UserInfo.php?api=unban_device', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => { 
                if (res.status === 'success') loadUsers(currentPage); 
                else alert(res.message || "Failed to unban device"); 
            });
    }
    
    function banDeviceFromList(device_id, event) {
        event.stopPropagation();
        if (!confirm('Are you sure you want to ban this device?')) return;
        const formData = new FormData(); 
        formData.append('device_id', device_id);
        fetch('UserInfo.php?api=ban_device', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => { 
                if (res.status === 'success') loadUsers(currentPage); 
                else alert(res.message || "Failed to ban device"); 
            });
    }

    function banManualDevice() {
        let did = document.getElementById('manualDeviceId').value.trim();
        if (!did) { alert('Please enter a Device ID'); return; }
        if (!confirm(`Ban device: ${did}?`)) return;
        const formData = new FormData();
        formData.append('device_id', did);
        fetch('UserInfo.php?api=ban_device', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => { 
                if (res.status === 'success') { document.getElementById('manualDeviceId').value = ''; loadUsers(currentPage); }
                else alert(res.message); 
            });
    }

    function deleteModerator(idx) {
        let u = usersData[idx];
        if (!confirm(`Delete moderator ${u.username}?`)) return;
        const formData = new FormData();
        formData.append('username', u.username);
        formData.append('password', u.password || '');
        fetch('UserInfo.php?api=delete_moderator', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    loadUsers(currentPage);
                } else {
                    alert(res.message || 'Failed to delete moderator');
                }
            });
    }

    function renderGrid(users) {
        const grid = document.getElementById('userGrid');
        grid.innerHTML = '';
        
        if (currentTab === 'moderator' && isAdmin) {
            let addCard = document.createElement('div');
            addCard.className = 'user-card';
            addCard.style.justifyContent = 'center';
            addCard.style.alignItems = 'center';
            addCard.style.padding = '24px';
            addCard.style.gridColumn = '1 / -1';
            addCard.innerHTML = `<a href="Add_Admin.php" style="width:100%; max-width:400px; background:var(--success); color:#fff; padding:12px; border-radius:8px; text-decoration:none; font-size:15px; font-weight:700; text-align:center; display:block;">+ Add Moderator</a>`;
            grid.appendChild(addCard);
        }
        
        if (currentTab === 'device' && canEdit) {
            let addCard = document.createElement('div');
            addCard.className = 'user-card';
            addCard.style.gridColumn = '1 / -1'; 
            addCard.style.display = 'flex';
            addCard.style.gap = '10px';
            addCard.style.flexDirection = 'row';
            addCard.innerHTML = `
                <input type="text" id="manualDeviceId" placeholder="Enter Device ID to Ban" class="form-control" style="flex-grow:1;">
                <button class="btn btn-danger" style="border-radius:12px;" onclick="banManualDevice()">Ban Device</button>
            `;
            grid.appendChild(addCard);
        }

        if (users.length === 0) {
            let emptyCard = document.createElement('div');
            emptyCard.className = 'user-card';
            emptyCard.style.gridColumn = '1 / -1';
            emptyCard.style.justifyContent = 'center';
            emptyCard.innerHTML = '<p style="color:var(--text-muted); font-weight:600;">No data found</p>';
            grid.appendChild(emptyCard);
            return;
        }

        users.forEach((u, idx) => {
            let card = document.createElement('div');
            
            if (currentTab === 'moderator') {
                let encUser = encodeURIComponent(u.username);
                let encPass = encodeURIComponent(u.password || '');
                card.className = 'user-card'; 
                card.style.animationDelay = `${idx * 0.05}s`;
                card.style.flexDirection = 'row';
                card.style.alignItems = 'center';
                card.setAttribute('data-moderator-index', idx);
                
                card.innerHTML = `
                    <div class="user-info">
                        <div class="user-avatar" style="background:var(--primary-light); color:var(--primary); display:grid; place-items:center; font-weight:800; font-size:20px;">M</div>
                        <div class="user-details">
                            <h4>${u.username}</h4>
                            <p>Pass: ${u.password}</p>
                        </div>
                    </div>
                    <div class="card-actions-right">
                        <div style="display:flex; gap:8px;">
                            <a href="Add_Admin.php?username=${encUser}&password=${encPass}" style="background:var(--primary); color:#fff; padding:8px 16px; border-radius:8px; text-decoration:none; font-size:13px; font-weight:700;">Edit</a>
                            <button onclick="deleteModerator(${idx}); event.stopPropagation();" class="btn btn-danger" style="padding:6px 14px; font-size:12px; border-radius:8px;">Delete</button>
                        </div>
                    </div>
                `;
            } else if (currentTab === 'device') {
                let isBanned = parseInt(u.ban_status) === 1;
                let bgStyle = isBanned ? '#fff5f5' : '#f0fdf4';
                let colStyle = isBanned ? 'var(--danger)' : 'var(--success)';
                let txtStat = isBanned ? 'Banned' : 'Active';
                
                let btn = '';
                if (canEdit) {
                    if (isBanned) {
                        btn = `<button class="btn btn-primary" style="padding:6px 14px; font-size:12px; border-radius:8px;" onclick="unbanDevice('${u.device_id}', event)">Unban</button>`;
                    } else {
                        btn = `<button class="btn btn-danger" style="padding:6px 14px; font-size:12px; border-radius:8px;" onclick="banDeviceFromList('${u.device_id}', event)">Ban</button>`;
                    }
                }

                card.className = 'user-card'; 
                card.style.animationDelay = `${idx * 0.05}s`;
                card.innerHTML = `
                    <div class="user-info">
                        <div class="user-avatar" style="background:${bgStyle}; color:${colStyle}; display:grid; place-items:center;">
                            <svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path></svg>
                        </div>
                        <div class="user-details">
                            <h4>Device ID</h4>
                            <p>ID: ${u.device_id}</p>
                            <p style="font-size:11px; margin-top:4px;">Date: ${u.created_at || 'Unknown'}</p>
                        </div>
                    </div>
                    <div class="card-actions-right">
                        <div class="device-badge" style="background:${bgStyle}; color:${colStyle};">${txtStat}</div>
                        ${btn}
                    </div>
                `;
            } else {
                let encUser = encodeURIComponent(u.username);
                card.className = 'user-card'; 
                card.style.animationDelay = `${idx * 0.05}s`;
                if (canEdit) card.onclick = () => openModal(idx);
                let badge = (u.verify_badge == 1 || u.verify_badge == 'Yes') ? `<svg class="verify-badge" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path fill-rule="evenodd" d="M8.603 3.799A4.49 4.49 0 0 1 12 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 0 1 3.498 1.307 4.491 4.491 0 0 1 1.307 3.497A4.49 4.49 0 0 1 21.75 12a4.49 4.49 0 0 1-1.549 3.397 4.491 4.491 0 0 1-1.307 3.497 4.491 4.491 0 0 1-3.497 1.307A4.49 4.49 0 0 1 12 21.75a4.49 4.49 0 0 1-3.397-1.549 4.49 4.49 0 0 1-3.498-1.306 4.491 4.491 0 0 1-1.307-3.498A4.49 4.49 0 0 1 2.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 0 1 1.307-3.497 4.49 4.49 0 0 1 3.497-1.307Zm7.007 6.387a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z" clip-rule="evenodd" /></svg>` : '';
                let pic = u.profile_pic ? u.profile_pic : 'data:image/svg+xml;charset=UTF-8,%3csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23cbd5e1"%3e%3cpath fill-rule="evenodd" d="M18.685 19.097A9.723 9.723 0 0 0 21.75 12c0-5.385-4.365-9.75-9.75-9.75S2.25 6.615 2.25 12a9.723 9.723 0 0 0 3.065 7.097A9.716 9.716 0 0 0 12 21.75a9.716 9.716 0 0 0 6.685-2.653Zm-12.54-1.285A7.486 7.486 0 0 1 12 15a7.486 7.486 0 0 1 5.855 2.812A8.224 8.224 0 0 1 12 20.25a8.224 8.224 0 0 1-5.855-2.438ZM15.75 9a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z" clip-rule="evenodd"/%3e%3c/svg%3e';
                let subText = u.number || u.email || 'No contact';
                let actionBtns = `<div class="user-action-btns"><a href="Usersmoneyhistory.php?username=${encUser}" class="u-btn u-money" onclick="event.stopPropagation()"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg></a><a href="zabbarnotification.php?username=${encUser}" class="u-btn u-noti" onclick="event.stopPropagation()"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" /></svg></a></div>`;
                card.innerHTML = `<div class="user-info"><img src="${pic}" class="user-avatar" onerror="this.src='data:image/svg+xml;charset=UTF-8,%3csvg xmlns=\\'http://www.w3.org/2000/svg\\' viewBox=\\'0 0 24 24\\' fill=\\'%23cbd5e1\\'%3e%3cpath fill-rule=\\'evenodd\\' d=\\'M18.685 19.097A9.723 9.723 0 0 0 21.75 12c0-5.385-4.365-9.75-9.75-9.75S2.25 6.615 2.25 12a9.723 9.723 0 0 0 3.065 7.097A9.716 9.716 0 0 0 12 21.75a9.716 9.716 0 0 0 6.685-2.653Zm-12.54-1.285A7.486 7.486 0 0 1 12 15a7.486 7.486 0 0 1 5.855 2.812A8.224 8.224 0 0 1 12 20.25a8.224 8.224 0 0 1-5.855-2.438ZM15.75 9a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z\\' clip-rule=\\'evenodd\\'/\\%3e%3c/svg%3e'"><div class="user-details"><h4>${u.username} ${badge}</h4><p>${subText}</p></div></div><div class="card-actions-right"><div class="win-badge">৳ ${u.winning || '0'}</div>${actionBtns}</div>`;
            }
            grid.appendChild(card);
        });
    }

    function changePage(dir) { loadUsers(currentPage + dir); }
    
    function openModal(idx) {
        const u = usersData[idx];
        document.getElementById('e_id').value = u.id; 
        document.getElementById('e_username').value = u.username || '';
        document.getElementById('e_password').value = u.password || ''; 
        document.getElementById('e_email').value = u.email || '';
        document.getElementById('e_number').value = u.number || ''; 
        document.getElementById('e_balance').value = u.balance || '';
        document.getElementById('e_winning').value = u.winning || ''; 
        document.getElementById('e_verify_badge').value = (u.verify_badge == 1 || u.verify_badge == 'Yes') ? '1' : '0';
        document.getElementById('e_total_refer').value = u.total_refer || ''; 
        document.getElementById('e_profile_pic').value = u.profile_pic || ''; 
        document.getElementById('e_withdraw_block').value = (u.withdraw_block == 1 || u.withdraw_block == 'Yes') ? '1' : '0';
        document.getElementById('e_device_id').value = u.device_id || '';
        
        let stat = u.status === 'ban' ? 'ban' : 'unban';
        document.getElementById('e_status').value = stat;
        document.getElementById('e_ban_reason').value = u.ban_reason || '';
        
        document.getElementById('ban_reason_group').style.display = 'none';
        document.getElementById('ban_device_group').style.display = 'none';
        document.getElementById('ban_device_also').checked = false;

        document.getElementById('editModal').style.display = 'flex';
    }

    function closeModal() { 
        document.getElementById('editModal').style.display = 'none'; 
        document.getElementById('editForm').reset(); 
    }
    
    function saveUser() {
        const formData = new FormData(document.getElementById('editForm'));
        fetch('UserInfo.php?api=update', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => { 
            if (res.status === 'success') { 
                closeModal(); 
                loadUsers(currentPage); 
            } else {
                alert(res.message); 
            }
        });
    }
    
    function deleteUser() {
        if (!confirm('Are you sure?')) return;
        const formData = new FormData(); formData.append('id', document.getElementById('e_id').value);
        fetch('UserInfo.php?api=delete', { method: 'POST', body: formData }).then(res => res.json()).then(res => { if (res.status === 'success') { closeModal(); loadUsers(currentPage); } else alert(res.message); });
    }
    
    window.onload = () => loadUsers(1);
</script>
</body>
</html>