<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}

ob_clean();
header('Content-Type: application/json');

if (!isset($conn) && isset($con)) {
    $conn = $con;
}

if (!isset($conn) || !is_object($conn)) {
    echo json_encode(["status" => "error", "message" => "Database Connection Failed"]);
    exit;
}

$conn->set_charset("utf8mb4");

$has_permission = false;
$permission_value = '';

if (isset($_SESSION['admin_logged_in']) && isset($_SESSION['admin_user']) && isset($_SESSION['admin_pass'])) {
    $admin_user = $_SESSION['admin_user'];
    $admin_pass = $_SESSION['admin_pass'];
    
    $sql = "SELECT users_control FROM modarator_permissions WHERE username = ? AND password = ? LIMIT 1";
    $stmt = @$conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ss", $admin_user, $admin_pass);
        if (@$stmt->execute()) {
            $res = $stmt->get_result();
            if ($res && $res->num_rows > 0) {
                $row = $res->fetch_assoc();
                $permission_value = strtolower(trim((string)$row['users_control']));
            }
        }
        $stmt->close();
    }
}

if ($permission_value === 'yes' || $permission_value === '1' || $permission_value === 'true') {
    $has_permission = true;
}

if (!$has_permission) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Permission Denied! আপনার এই পেজ ব্যবহারের পারমিশন নেই।"]);
    exit;
}

$action = $_POST['action'] ?? '';

if ($action == 'list') {
    $limit = isset($_POST['show']) ? (int)$_POST['show'] : 20;
    $page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
    $search = isset($_POST['search']) ? trim($_POST['search']) : '';
    if ($limit < 1) $limit = 1;
    if ($page < 1) $page = 1;
    $offset = ($page - 1) * $limit;
    
    $where = "";
    $params = [];
    $types = "";
    
    if (!empty($search)) {
        $term = "%" . $search . "%";
        $where = "WHERE username LIKE ? OR email LIKE ? OR number LIKE ?";
        $params = [$term, $term, $term];
        $types = "sss";
    }
    
    $count_sql = "SELECT COUNT(*) AS total FROM users $where";
    $count_stmt = $conn->prepare($count_sql);
    if (!empty($search)) {
        $count_stmt->bind_param($types, ...$params);
    }
    $count_stmt->execute();
    $count_res = $count_stmt->get_result();
    $total_row = $count_res->fetch_assoc();
    $total_users = (int)$total_row['total'];
    $count_stmt->close();
    
    $sql = "SELECT id, username, email, number, balance, winning, profile_pic, verify_badge FROM users $where ORDER BY id DESC LIMIT ? OFFSET ?";
    $stmt = $conn->prepare($sql);
    $params[] = $limit;
    $params[] = $offset;
    $types .= "ii";
    
    if (!empty($search)) {
        $stmt->bind_param($types, ...$params);
    } else {
        $stmt->bind_param("ii", $limit, $offset);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    $stmt->close();
    
    $total_pages = ($total_users > 0) ? ceil($total_users / $limit) : 1;
    echo json_encode([
        "status" => "success",
        "count" => count($data),
        "total" => $total_users,
        "current_page" => $page,
        "per_page" => $limit,
        "total_pages" => $total_pages,
        "users" => $data
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} elseif ($action == 'update') {
    $id = intval($_POST['id'] ?? 0);
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $number = $_POST['number'] ?? '';
    $balance = floatval($_POST['balance'] ?? 0);
    $winning = floatval($_POST['winning'] ?? 0);
    $verify_badge = $_POST['verify_badge'] ?? 'No';
    
    if ($id <= 0) {
        echo json_encode(["status" => "error", "message" => "Invalid ID"]);
        exit;
    }
    
    $stmt = $conn->prepare("UPDATE users SET username=?, email=?, number=?, balance=?, winning=?, verify_badge=? WHERE id=?");
    $stmt->bind_param("sssddsi", $username, $email, $number, $balance, $winning, $verify_badge, $id);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Updated successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => $stmt->error]);
    }
    $stmt->close();

} elseif ($action == 'delete') {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(["status" => "error", "message" => "Invalid ID"]);
        exit;
    }
    
    $stmt = $conn->prepare("DELETE FROM users WHERE id=?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Deleted successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => $stmt->error]);
    }
    $stmt->close();
} else {
    echo json_encode(["status" => "error", "message" => "Invalid action"]);
}
$conn->close();
?>