<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$message = '';
$message_type = '';

// Handle user status toggle (keep this for activation/deactivation)
if (isset($_GET['toggle_status'])) {
    $user_id = intval($_GET['user_id']);
    $new_status = intval($_GET['status']);
    
    $stmt = mysqli_prepare($conn, "UPDATE users SET status = ? WHERE user_id = ?");
    mysqli_stmt_bind_param($stmt, "ii", $new_status, $user_id);
    
    if (mysqli_stmt_execute($stmt)) {
        $_SESSION['flash_message'] = "User status updated successfully!";
        $_SESSION['flash_type'] = "success";
    } else {
        $_SESSION['flash_message'] = "Error updating user status: " . mysqli_error($conn);
        $_SESSION['flash_type'] = "danger";
    }
    mysqli_stmt_close($stmt);
    
    header("Location: users.php");
    exit();
}

// REMOVED: User deletion functionality (as requested)

// Handle user edit form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] === 'edit_user') {
        $user_id = intval($_POST['user_id']);
        
        // Fetch current user data for comparison
        $current_query = mysqli_query($conn, "SELECT * FROM users WHERE user_id = $user_id");
        $current_user = mysqli_fetch_assoc($current_query);
        
        if (!$current_user) {
            $_SESSION['flash_message'] = "User not found!";
            $_SESSION['flash_type'] = "danger";
            header("Location: users.php");
            exit();
        }
        
        $name = sanitize($conn, $_POST['name']);
        $password = $_POST['password']; // Plain text as requested
        $mobile = sanitize($conn, $_POST['mobile']);
        $email = sanitize($conn, $_POST['email']);
        $dob = !empty($_POST['dob']) ? $_POST['dob'] : null;
        $gender = intval($_POST['gender']);
        $address = sanitize($conn, $_POST['address']);
        $panno = strtoupper(sanitize($conn, $_POST['panno']));
        $aadharno = sanitize($conn, $_POST['aadharno']);
        $sponsor_id = !empty($_POST['sponsor_id']) ? intval($_POST['sponsor_id']) : null;
        $package_id = intval($_POST['package_id']);
        $wallet = floatval($_POST['wallet']);
        $withdrawl_inc = floatval($_POST['withdrawl_inc']);
        $spill_income = floatval($_POST['spill_income']);
        $left_count = intval($_POST['left_count']);
        $right_count = intval($_POST['right_count']);
        $left_count_temp = intval($_POST['left_count_temp']);
        $right_count_temp = intval($_POST['right_count_temp']);
        $total_pairs = intval($_POST['total_pairs']);
        $paid_pairs = intval($_POST['paid_pairs']);
        $unpaid_pairs = intval($_POST['unpaid_pairs']);
        $status = intval($_POST['status']);
        $rank = sanitize($conn, $_POST['rank']);
        $rank_level = intval($_POST['rank_level']);
        $position = intval($_POST['position']);
        $placement_id = !empty($_POST['placement_id']) ? intval($_POST['placement_id']) : 0;
        $left_side = !empty($_POST['left_side']) ? intval($_POST['left_side']) : 0;
        $right_side = !empty($_POST['right_side']) ? intval($_POST['right_side']) : 0;
        $left_1_id = !empty($_POST['left_1_id']) ? intval($_POST['left_1_id']) : 0;
        $left_2_id = !empty($_POST['left_2_id']) ? intval($_POST['left_2_id']) : 0;
        $right_1_id = !empty($_POST['right_1_id']) ? intval($_POST['right_1_id']) : 0;
        $right_2_id = !empty($_POST['right_2_id']) ? intval($_POST['right_2_id']) : 0;
        $pin_used = sanitize($conn, $_POST['pin_used']);
        $registered_by = !empty($_POST['registered_by']) ? intval($_POST['registered_by']) : 0;
        
        // Handle image upload
        $image_name = $current_user['image']; // Keep current image by default
        
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/webp'];
            $max_size = 5 * 1024 * 1024; // 5MB
            
            if (!in_array($_FILES['image']['type'], $allowed_types)) {
                $_SESSION['flash_message'] = "Invalid image type. Only JPG, PNG, GIF and WEBP are allowed!";
                $_SESSION['flash_type'] = "danger";
                header("Location: users.php?edit=$user_id");
                exit();
            }
            
            if ($_FILES['image']['size'] > $max_size) {
                $_SESSION['flash_message'] = "Image size too large. Maximum 5MB allowed!";
                $_SESSION['flash_type'] = "danger";
                header("Location: users.php?edit=$user_id");
                exit();
            }
            
            // Create upload directory if not exists
            $upload_dir = "../profile-img/";
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Generate unique filename
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $image_name = "profile_" . $user_id . "_" . date('Ymd_His') . "." . $ext;
            $target_file = $upload_dir . $image_name;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                // Delete old image if exists and not default
                if ($current_user['image'] && $current_user['image'] != 'noprofil.jpg' && file_exists($upload_dir . $current_user['image'])) {
                    unlink($upload_dir . $current_user['image']);
                }
            } else {
                $_SESSION['flash_message'] = "Failed to upload image!";
                $_SESSION['flash_type'] = "danger";
                header("Location: users.php?edit=$user_id");
                exit();
            }
        }
        
        // Build update query dynamically
        $update_fields = [];
        $params = [];
        $types = "";
        
        $fields = [
            'name' => [$name, 's'],
            'mobile' => [$mobile, 's'],
            'email' => [$email, 's'],
            'dob' => [$dob, 's'],
            'gender' => [$gender, 'i'],
            'address' => [$address, 's'],
            'panno' => [$panno, 's'],
            'aadharno' => [$aadharno, 's'],
            'sponsor_id' => [$sponsor_id, 'i'],
            'package_id' => [$package_id, 'i'],
            'wallet' => [$wallet, 'd'],
            'withdrawl_inc' => [$withdrawl_inc, 'd'],
            'spill_income' => [$spill_income, 'd'],
            'left_count' => [$left_count, 'i'],
            'right_count' => [$right_count, 'i'],
            'left_count_temp' => [$left_count_temp, 'i'],
            'right_count_temp' => [$right_count_temp, 'i'],
            'total_pairs' => [$total_pairs, 'i'],
            'paid_pairs' => [$paid_pairs, 'i'],
            'unpaid_pairs' => [$unpaid_pairs, 'i'],
            'status' => [$status, 'i'],
            'rank' => [$rank, 's'],
            'rank_level' => [$rank_level, 'i'],
            'position' => [$position, 'i'],
            'placement_id' => [$placement_id, 'i'],
            'left_side' => [$left_side, 'i'],
            'right_side' => [$right_side, 'i'],
            'left_1_id' => [$left_1_id, 'i'],
            'left_2_id' => [$left_2_id, 'i'],
            'right_1_id' => [$right_1_id, 'i'],
            'right_2_id' => [$right_2_id, 'i'],
            'pin_used' => [$pin_used, 's'],
            'registered_by' => [$registered_by, 'i'],
            'image' => [$image_name, 's']
        ];
        
        // Add password only if provided
        if (!empty($password)) {
            $fields['password'] = [$password, 's'];
        }
        
        foreach ($fields as $field => $field_data) {
            $update_fields[] = "$field = ?";
            $params[] = $field_data[0];
            $types .= $field_data[1];
        }
        
        $params[] = $user_id;
        $types .= "i";
        
        $query = "UPDATE users SET " . implode(", ", $update_fields) . " WHERE user_id = ?";
        
        $stmt = mysqli_prepare($conn, $query);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, $types, ...$params);
            
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['flash_message'] = "User updated successfully!";
                $_SESSION['flash_type'] = "success";
            } else {
                $_SESSION['flash_message'] = "Error updating user: " . mysqli_error($conn);
                $_SESSION['flash_type'] = "danger";
            }
            mysqli_stmt_close($stmt);
        } else {
            $_SESSION['flash_message'] = "Database error: " . mysqli_error($conn);
            $_SESSION['flash_type'] = "danger";
        }
        
        header("Location: users.php");
        exit();
    }
    
    elseif ($_POST['action'] === 'bulk_action') {
        $action_type = $_POST['bulk_action_type'];
        $selected_users = isset($_POST['selected_users']) ? $_POST['selected_users'] : [];
        
        if (empty($selected_users)) {
            $_SESSION['flash_message'] = "No users selected!";
            $_SESSION['flash_type'] = "warning";
            header("Location: users.php");
            exit();
        }
        
        $user_ids = implode(',', array_map('intval', $selected_users));
        
        switch ($action_type) {
            case 'activate':
                $result = mysqli_query($conn, "UPDATE users SET status = 1 WHERE user_id IN ($user_ids)");
                if ($result) {
                    $_SESSION['flash_message'] = "Selected users activated successfully!";
                    $_SESSION['flash_type'] = "success";
                } else {
                    $_SESSION['flash_message'] = "Error activating users: " . mysqli_error($conn);
                    $_SESSION['flash_type'] = "danger";
                }
                break;
                
            case 'deactivate':
                $result = mysqli_query($conn, "UPDATE users SET status = 0 WHERE user_id IN ($user_ids)");
                if ($result) {
                    $_SESSION['flash_message'] = "Selected users deactivated successfully!";
                    $_SESSION['flash_type'] = "success";
                } else {
                    $_SESSION['flash_message'] = "Error deactivating users: " . mysqli_error($conn);
                    $_SESSION['flash_type'] = "danger";
                }
                break;
        }
        
        header("Location: users.php");
        exit();
    }
}

// Check for flash messages
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $message_type = $_SESSION['flash_type'];
    unset($_SESSION['flash_message']);
    unset($_SESSION['flash_type']);
}

// Search and filter functionality
$search = isset($_GET['search']) ? sanitize($conn, $_GET['search']) : '';
$status_filter = isset($_GET['status']) ? intval($_GET['status']) : -1;
$package_filter = isset($_GET['package']) ? intval($_GET['package']) : 0;
$rank_filter = isset($_GET['rank']) ? sanitize($conn, $_GET['rank']) : '';

$where = [];
if ($search) {
    $where[] = "(user_id LIKE '%$search%' OR name LIKE '%$search%' OR mobile LIKE '%$search%' OR email LIKE '%$search%' OR panno LIKE '%$search%')";
}
if ($status_filter >= 0) {
    $where[] = "status = $status_filter";
}
if ($package_filter > 0) {
    $where[] = "package_id = $package_filter";
}
if ($rank_filter) {
    $where[] = "rank = '$rank_filter'";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// Get distinct ranks for filter
$ranks = mysqli_query($conn, "SELECT DISTINCT rank FROM users WHERE rank != '' AND rank IS NOT NULL ORDER BY rank");

// Get users with pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$total_result = mysqli_query($conn, "SELECT COUNT(*) as total FROM users $where_clause");
$total = mysqli_fetch_assoc($total_result)['total'];
$total_pages = ceil($total / $limit);

$users = mysqli_query($conn, "SELECT * FROM users $where_clause ORDER BY id DESC LIMIT $offset, $limit");

// Get user for editing if edit mode
$edit_user = null;
if (isset($_GET['edit']) && $_GET['edit'] !== 'new') {
    $edit_id = intval($_GET['edit']);
    $edit_result = mysqli_query($conn, "SELECT * FROM users WHERE user_id = $edit_id");
    $edit_user = mysqli_fetch_assoc($edit_result);
}

// Get statistics
$stats = [];
$result = mysqli_query($conn, "SELECT status, COUNT(*) as count FROM users GROUP BY status");
while ($row = mysqli_fetch_assoc($result)) {
    $stats[$row['status']] = $row['count'];
}
$stats[0] = $stats[0] ?? 0;
$stats[1] = $stats[1] ?? 0;

// Get package stats
$package_stats = [];
$result = mysqli_query($conn, "SELECT package_id, COUNT(*) as count FROM users WHERE package_id IN (2500, 3500) GROUP BY package_id");
while ($row = mysqli_fetch_assoc($result)) {
    $package_stats[$row['package_id']] = $row['count'];
}

// Get total wallet balance
$wallet_result = mysqli_query($conn, "SELECT SUM(wallet) as total_wallet FROM users");
$total_wallet = mysqli_fetch_assoc($wallet_result)['total_wallet'] ?? 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>User Management - MLM System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
    
    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <!-- Toastr for notifications -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <style>
        * {
            font-family: 'Inter', sans-serif;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(180deg, #4154f1, #6f42c1);
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.05);
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        .stat-icon.primary { background: rgba(65, 84, 241, 0.1); color: #4154f1; }
        .stat-icon.success { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .stat-icon.warning { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        .stat-icon.info { background: rgba(23, 162, 184, 0.1); color: #17a2b8; }
        .stat-icon.purple { background: rgba(111, 66, 193, 0.1); color: #6f42c1; }
        
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 5px;
            color: #1a1a1a;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 14px;
            font-weight: 500;
        }
        
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .table-container {
            background: white;
            border-radius: 16px;
            padding: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 40px;
            object-fit: cover;
            border: 2px solid #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .badge-package {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 500;
            font-size: 12px;
        }
        
        .badge-package.basic {
            background: rgba(255, 193, 7, 0.15);
            color: #856404;
        }
        
        .badge-package.premium {
            background: rgba(111, 66, 193, 0.15);
            color: #563d7c;
        }
        
        .badge-status {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 500;
            font-size: 12px;
        }
        
        .badge-status.active {
            background: rgba(40, 167, 69, 0.15);
            color: #28a745;
        }
        
        .badge-status.inactive {
            background: rgba(220, 53, 69, 0.15);
            color: #dc3545;
        }
        
        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin: 0 3px;
            transition: all 0.2s;
            border: none;
            background: transparent;
            color: #6c757d;
        }
        
        .action-btn:hover {
            background: #f8f9fa;
            color: #4154f1;
            transform: scale(1.1);
        }
        
        .action-btn.edit:hover { background: rgba(65, 84, 241, 0.1); color: #4154f1; }
        .action-btn.view:hover { background: rgba(23, 162, 184, 0.1); color: #17a2b8; }
        .action-btn.activate:hover { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .action-btn.deactivate:hover { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        
        .pagination .page-link {
            border: none;
            padding: 8px 16px;
            margin: 0 5px;
            border-radius: 8px;
            color: #6c757d;
            font-weight: 500;
        }
        
        .pagination .page-item.active .page-link {
            background: #4154f1;
            color: white;
        }
        
        .pagination .page-item.disabled .page-link {
            background: #f8f9fa;
            color: #adb5bd;
        }
        
        .modal-content {
            border-radius: 20px;
            border: none;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #4154f1 0%, #6f42c1 100%);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 20px 30px;
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-body {
            padding: 30px;
        }
        
        .nav-tabs .nav-link {
            color: #6c757d;
            font-weight: 500;
            border: none;
            padding: 12px 20px;
        }
        
        .nav-tabs .nav-link.active {
            color: #4154f1;
            background: transparent;
            border-bottom: 2px solid #4154f1;
        }
        
        .form-label {
            font-weight: 500;
            color: #495057;
            margin-bottom: 8px;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            border: 1.5px solid #e9ecef;
            padding: 10px 15px;
            transition: all 0.2s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #4154f1;
            box-shadow: 0 0 0 3px rgba(65, 84, 241, 0.1);
        }
        
        .image-preview {
            width: 150px;
            height: 150px;
            border-radius: 16px;
            border: 3px solid #fff;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            object-fit: cover;
            margin-bottom: 15px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #4154f1 0%, #6f42c1 100%);
            border: none;
            border-radius: 10px;
            padding: 10px 25px;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #2f3eb0 0%, #563d7c 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(65, 84, 241, 0.3);
        }
        
        .btn-secondary {
            border-radius: 10px;
            padding: 10px 25px;
            font-weight: 500;
        }
        
        .select2-container--bootstrap-5 .select2-selection {
            border-radius: 10px;
            border: 1.5px solid #e9ecef;
            min-height: 42px;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        
        .empty-state i {
            font-size: 60px;
            color: #dee2e6;
            margin-bottom: 20px;
        }
        
        .empty-state h5 {
            color: #495057;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #6c757d;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>User Management</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Users</li>
                </ol>
            </nav>
        </div>

        <section class="section">
            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon primary">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-value"><?php echo number_format($total); ?></div>
                    <div class="stat-label">Total Users</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon success">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div class="stat-value"><?php echo number_format($stats[1]); ?></div>
                    <div class="stat-label">Active Users</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon warning">
                        <i class="fas fa-user-clock"></i>
                    </div>
                    <div class="stat-value"><?php echo number_format($stats[0]); ?></div>
                    <div class="stat-label">Inactive Users</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon info">
                        <i class="fas fa-wallet"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($total_wallet, 2); ?></div>
                    <div class="stat-label">Total Wallet</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon purple">
                        <i class="fas fa-crown"></i>
                    </div>
                    <div class="stat-value"><?php echo number_format(($package_stats[2500] ?? 0) + ($package_stats[3500] ?? 0)); ?></div>
                    <div class="stat-label">Package Holders</div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-lg-12">
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                            <i class="fas fa-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-circle'; ?> me-2"></i>
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Filter Card -->
                    <div class="filter-card">
                        <h5 class="mb-4"><i class="fas fa-filter me-2"></i>Filter Users</h5>
                        
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <input type="text" class="form-control" name="search" 
                                       placeholder="Search by ID, Name, Mobile, Email or PAN" 
                                       value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            
                            <div class="col-md-2">
                                <select name="status" class="form-select">
                                    <option value="-1">All Status</option>
                                    <option value="1" <?php echo $status_filter == 1 ? 'selected' : ''; ?>>Active</option>
                                    <option value="0" <?php echo $status_filter == 0 ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <select name="package" class="form-select">
                                    <option value="0">All Packages</option>
                                    <option value="2500" <?php echo $package_filter == 2500 ? 'selected' : ''; ?>>₹2500 Basic</option>
                                    <option value="3500" <?php echo $package_filter == 3500 ? 'selected' : ''; ?>>₹3500 Premium</option>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <select name="rank" class="form-select">
                                    <option value="">All Ranks</option>
                                    <?php if ($ranks && mysqli_num_rows($ranks) > 0): ?>
                                        <?php while ($rank = mysqli_fetch_assoc($ranks)): ?>
                                            <option value="<?php echo $rank['rank']; ?>" <?php echo $rank_filter == $rank['rank'] ? 'selected' : ''; ?>>
                                                <?php echo $rank['rank']; ?>
                                            </option>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search me-2"></i>Apply
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Bulk Actions -->
                    <form method="POST" id="bulkActionForm" onsubmit="return confirm('Perform bulk action on selected users?')">
                        <input type="hidden" name="action" value="bulk_action">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="d-flex gap-2">
                                <select name="bulk_action_type" class="form-select" style="width: 200px;" required>
                                    <option value="">Bulk Actions</option>
                                    <option value="activate">Activate Selected</option>
                                    <option value="deactivate">Deactivate Selected</option>
                                </select>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-check-double me-2"></i>Apply
                                </button>
                            </div>
                            
                            <button type="button" class="btn btn-success" onclick="window.location.href='?edit=new'">
                                <i class="fas fa-user-plus me-2"></i>Add New User
                            </button>
                        </div>
                    
                    <!-- Users Table -->
                    <div class="table-container">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle">
                                <thead>
                                    <tr>
                                        <th width="40">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="selectAll">
                                            </div>
                                        </th>
                                        <th>User</th>
                                        <th>Contact</th>
                                        <th>Sponsor</th>
                                        <th>Package</th>
                                        <th>Wallet</th>
                                        <th>Rank</th>
                                        <th>Status</th>
                                        <th>Joined</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($users && mysqli_num_rows($users) > 0): ?>
                                        <?php while ($user = mysqli_fetch_assoc($users)): ?>
                                        <tr>
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input user-checkbox" type="checkbox" name="selected_users[]" value="<?php echo $user['user_id']; ?>">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <img src="<?php echo (!empty($user['image']) && $user['image'] != 'noprofil.jpg' && file_exists('../profile-img/' . $user['image'])) ? '../profile-img/' . $user['image'] : '..\uploads\profiles/noprofil.jpg'; ?>" 
                                                         class="user-avatar me-3" 
                                                         alt="Avatar"
                                                         onerror="this.src='..\uploads\profiles/noprofil.jpg'">
                                                    <div>
                                                        <div class="fw-bold"><?php echo htmlspecialchars($user['name']); ?></div>
                                                        <small class="text-muted">ID: <?php echo $user['user_id']; ?></small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div><?php echo $user['mobile']; ?></div>
                                                <small class="text-muted"><?php echo $user['email'] ?: 'No email'; ?></small>
                                            </td>
                                            <td>
                                                <?php if ($user['sponsor_id']): ?>
                                                    <span class="badge bg-light text-dark"><?php echo $user['sponsor_id']; ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($user['package_id'] == 2500): ?>
                                                    <span class="badge-package basic">₹2500 Basic</span>
                                                <?php elseif ($user['package_id'] == 3500): ?>
                                                    <span class="badge-package premium">₹3500 Premium</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">No Package</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="fw-bold">₹<?php echo number_format($user['wallet'], 2); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($user['rank'] && $user['rank'] != 'NO Rank'): ?>
                                                    <span class="badge bg-info text-dark"><?php echo $user['rank']; ?></span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($user['status'] == 1): ?>
                                                    <span class="badge-status active">Active</span>
                                                <?php else: ?>
                                                    <span class="badge-status inactive">Inactive</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div><?php echo date('d M Y', strtotime($user['joining_date'] ?: $user['created_at'])); ?></div>
                                                <small class="text-muted"><?php echo date('h:i A', strtotime($user['joining_date'] ?: $user['created_at'])); ?></small>
                                            </td>
                                            <td>
                                                <button type="button" class="action-btn view" title="Quick View" onclick="quickView(<?php echo $user['user_id']; ?>)">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                
                                                <a href="?edit=<?php echo $user['user_id']; ?>" class="action-btn edit" title="Edit User">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                
                                                <?php if ($user['status'] == 1): ?>
                                                    <a href="?toggle_status=1&user_id=<?php echo $user['user_id']; ?>&status=0" 
                                                       class="action-btn deactivate" 
                                                       title="Deactivate"
                                                       onclick="return confirm('Deactivate this user?')">
                                                        <i class="fas fa-ban"></i>
                                                    </a>
                                                <?php else: ?>
                                                    <a href="?toggle_status=1&user_id=<?php echo $user['user_id']; ?>&status=1" 
                                                       class="action-btn activate" 
                                                       title="Activate"
                                                       onclick="return confirm('Activate this user?')">
                                                        <i class="fas fa-check-circle"></i>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="10">
                                                <div class="empty-state">
                                                    <i class="fas fa-users-slash"></i>
                                                    <h5>No Users Found</h5>
                                                    <p>Try adjusting your search or filter criteria</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <nav class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>&package=<?php echo $package_filter; ?>&rank=<?php echo urlencode($rank_filter); ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                                
                                <?php 
                                $start = max(1, $page - 2);
                                $end = min($total_pages, $page + 2);
                                for ($i = $start; $i <= $end; $i++): 
                                ?>
                                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>&package=<?php echo $package_filter; ?>&rank=<?php echo urlencode($rank_filter); ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>&package=<?php echo $package_filter; ?>&rank=<?php echo urlencode($rank_filter); ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                    </form>
                </div>
            </div>
        </section>
    </main>
    
    <!-- Edit User Modal -->
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-edit me-2"></i>
                        <span id="modalUserTitle">Edit User</span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data" id="editUserForm">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_id" id="edit_user_id" value="<?php echo isset($edit_user['user_id']) ? $edit_user['user_id'] : ''; ?>">
                    <input type="hidden" name="current_image" id="current_image" value="<?php echo isset($edit_user['image']) ? $edit_user['image'] : 'noprofil.jpg'; ?>">
                    
                    <div class="modal-body">
                        <ul class="nav nav-tabs" id="editUserTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="basic-tab" data-bs-toggle="tab" data-bs-target="#basic" type="button" role="tab">
                                    <i class="fas fa-user me-2"></i>Basic Info
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="financial-tab" data-bs-toggle="tab" data-bs-target="#financial" type="button" role="tab">
                                    <i class="fas fa-coins me-2"></i>Financial
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="binary-tab" data-bs-toggle="tab" data-bs-target="#binary" type="button" role="tab">
                                    <i class="fas fa-code-branch me-2"></i>Binary Tree
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="placement-tab" data-bs-toggle="tab" data-bs-target="#placement" type="button" role="tab">
                                    <i class="fas fa-sitemap me-2"></i>Placement
                                </button>
                            </li>
                        </ul>
                        
                        <div class="tab-content p-4" id="editUserTabContent">
                            <!-- Basic Info Tab -->
                            <div class="tab-pane fade show active" id="basic" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-3 text-center">
                                        <div class="mb-4">
                                            <?php 
                                            $preview_src = '..\uploads\profiles/noprofil.jpg';
                                            if (isset($edit_user['image']) && $edit_user['image'] && $edit_user['image'] != 'noprofil.jpg') {
                                                if (file_exists('../profile-img/' . $edit_user['image'])) {
                                                    $preview_src = '../profile-img/' . $edit_user['image'];
                                                }
                                            }
                                            ?>
                                            <img src="<?php echo $preview_src; ?>" 
                                                 id="imagePreview" 
                                                 class="image-preview" 
                                                 alt="Profile Preview"
                                                 onerror="this.src='..\uploads\profiles/noprofil.jpg'">
                                                 
                                            <label for="profileImage" class="btn btn-outline-primary btn-sm">
                                                <i class="fas fa-camera me-2"></i>Change Photo
                                            </label>
                                            <input type="file" class="d-none" name="image" id="profileImage" accept="image/*">
                                            <small class="text-muted d-block mt-2">Max 5MB (JPG, PNG, GIF)</small>
                                        </div>
                                    </div>
                                    <div class="col-md-9">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label">User ID</label>
                                                <input type="text" class="form-control" value="<?php echo isset($edit_user['user_id']) ? $edit_user['user_id'] : ''; ?>" readonly>
                                                <small class="text-muted">User ID cannot be changed</small>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Full Name *</label>
                                                <input type="text" class="form-control" name="name" value="<?php echo isset($edit_user['name']) ? htmlspecialchars($edit_user['name']) : ''; ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Password</label>
                                                <input type="text" class="form-control" name="password" placeholder="Leave blank to keep current">
                                                <small class="text-muted">Plain text - will be stored as-is</small>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Mobile *</label>
                                                <input type="text" class="form-control" name="mobile" value="<?php echo isset($edit_user['mobile']) ? $edit_user['mobile'] : ''; ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Email</label>
                                                <input type="email" class="form-control" name="email" value="<?php echo isset($edit_user['email']) ? htmlspecialchars($edit_user['email']) : ''; ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Date of Birth</label>
                                                <input type="date" class="form-control" name="dob" value="<?php echo isset($edit_user['dob']) ? $edit_user['dob'] : ''; ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Gender</label>
                                                <select class="form-select" name="gender">
                                                    <option value="0" <?php echo (isset($edit_user['gender']) && $edit_user['gender'] == 0) ? 'selected' : ''; ?>>Male</option>
                                                    <option value="1" <?php echo (isset($edit_user['gender']) && $edit_user['gender'] == 1) ? 'selected' : ''; ?>>Female</option>
                                                    <option value="2" <?php echo (isset($edit_user['gender']) && $edit_user['gender'] == 2) ? 'selected' : ''; ?>>Other</option>
                                                </select>
                                            </div>
                                            <div class="col-md-12">
                                                <label class="form-label">Address</label>
                                                <textarea class="form-control" name="address" rows="2"><?php echo isset($edit_user['address']) ? htmlspecialchars($edit_user['address']) : ''; ?></textarea>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">PAN Number</label>
                                                <input type="text" class="form-control" name="panno" value="<?php echo isset($edit_user['panno']) ? $edit_user['panno'] : ''; ?>" style="text-transform:uppercase">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Aadhar Number</label>
                                                <input type="text" class="form-control" name="aadharno" value="<?php echo isset($edit_user['aadharno']) ? $edit_user['aadharno'] : ''; ?>">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Financial Tab -->
                            <div class="tab-pane fade" id="financial" role="tabpanel">
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Sponsor ID</label>
                                        <input type="number" class="form-control" name="sponsor_id" value="<?php echo isset($edit_user['sponsor_id']) ? $edit_user['sponsor_id'] : ''; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Package</label>
                                        <select class="form-select" name="package_id">
                                            <option value="0">No Package</option>
                                            <option value="2500" <?php echo (isset($edit_user['package_id']) && $edit_user['package_id'] == 2500) ? 'selected' : ''; ?>>₹2500 - Basic</option>
                                            <option value="3500" <?php echo (isset($edit_user['package_id']) && $edit_user['package_id'] == 3500) ? 'selected' : ''; ?>>₹3500 - Premium</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Wallet Balance</label>
                                        <div class="input-group">
                                            <span class="input-group-text">₹</span>
                                            <input type="number" step="0.01" class="form-control" name="wallet" value="<?php echo isset($edit_user['wallet']) ? $edit_user['wallet'] : 0; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Withdrawal Income</label>
                                        <div class="input-group">
                                            <span class="input-group-text">₹</span>
                                            <input type="number" step="0.01" class="form-control" name="withdrawl_inc" value="<?php echo isset($edit_user['withdrawl_inc']) ? $edit_user['withdrawl_inc'] : 0; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Spill Income</label>
                                        <div class="input-group">
                                            <span class="input-group-text">₹</span>
                                            <input type="number" step="0.01" class="form-control" name="spill_income" value="<?php echo isset($edit_user['spill_income']) ? $edit_user['spill_income'] : 0; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Rank</label>
                                        <input type="text" class="form-control" name="rank" value="<?php echo isset($edit_user['rank']) ? htmlspecialchars($edit_user['rank']) : ''; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Rank Level</label>
                                        <input type="number" class="form-control" name="rank_level" value="<?php echo isset($edit_user['rank_level']) ? $edit_user['rank_level'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Status</label>
                                        <select class="form-select" name="status">
                                            <option value="1" <?php echo (isset($edit_user['status']) && $edit_user['status'] == 1) ? 'selected' : ''; ?>>Active</option>
                                            <option value="0" <?php echo (isset($edit_user['status']) && $edit_user['status'] == 0) ? 'selected' : ''; ?>>Inactive</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Binary Tree Tab -->
                            <div class="tab-pane fade" id="binary" role="tabpanel">
                                <div class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">Position</label>
                                        <select class="form-select" name="position">
                                            <option value="0" <?php echo (isset($edit_user['position']) && $edit_user['position'] == 0) ? 'selected' : ''; ?>>Left</option>
                                            <option value="1" <?php echo (isset($edit_user['position']) && $edit_user['position'] == 1) ? 'selected' : ''; ?>>Right</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Left Count</label>
                                        <input type="number" class="form-control" name="left_count" value="<?php echo isset($edit_user['left_count']) ? $edit_user['left_count'] : 0; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Right Count</label>
                                        <input type="number" class="form-control" name="right_count" value="<?php echo isset($edit_user['right_count']) ? $edit_user['right_count'] : 0; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Left Count Temp</label>
                                        <input type="number" class="form-control" name="left_count_temp" value="<?php echo isset($edit_user['left_count_temp']) ? $edit_user['left_count_temp'] : 0; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Right Count Temp</label>
                                        <input type="number" class="form-control" name="right_count_temp" value="<?php echo isset($edit_user['right_count_temp']) ? $edit_user['right_count_temp'] : 0; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Total Pairs</label>
                                        <input type="number" class="form-control" name="total_pairs" value="<?php echo isset($edit_user['total_pairs']) ? $edit_user['total_pairs'] : 0; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Paid Pairs</label>
                                        <input type="number" class="form-control" name="paid_pairs" value="<?php echo isset($edit_user['paid_pairs']) ? $edit_user['paid_pairs'] : 0; ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Unpaid Pairs</label>
                                        <input type="number" class="form-control" name="unpaid_pairs" value="<?php echo isset($edit_user['unpaid_pairs']) ? $edit_user['unpaid_pairs'] : 0; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Placement Tab -->
                            <div class="tab-pane fade" id="placement" role="tabpanel">
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Placement ID</label>
                                        <input type="number" class="form-control" name="placement_id" value="<?php echo isset($edit_user['placement_id']) ? $edit_user['placement_id'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Left Side User ID</label>
                                        <input type="number" class="form-control" name="left_side" value="<?php echo isset($edit_user['left_side']) ? $edit_user['left_side'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Right Side User ID</label>
                                        <input type="number" class="form-control" name="right_side" value="<?php echo isset($edit_user['right_side']) ? $edit_user['right_side'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Left 1 ID</label>
                                        <input type="number" class="form-control" name="left_1_id" value="<?php echo isset($edit_user['left_1_id']) ? $edit_user['left_1_id'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Left 2 ID</label>
                                        <input type="number" class="form-control" name="left_2_id" value="<?php echo isset($edit_user['left_2_id']) ? $edit_user['left_2_id'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Right 1 ID</label>
                                        <input type="number" class="form-control" name="right_1_id" value="<?php echo isset($edit_user['right_1_id']) ? $edit_user['right_1_id'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Right 2 ID</label>
                                        <input type="number" class="form-control" name="right_2_id" value="<?php echo isset($edit_user['right_2_id']) ? $edit_user['right_2_id'] : 0; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">PIN Used</label>
                                        <input type="text" class="form-control" name="pin_used" value="<?php echo isset($edit_user['pin_used']) ? $edit_user['pin_used'] : ''; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Registered By</label>
                                        <input type="number" class="form-control" name="registered_by" value="<?php echo isset($edit_user['registered_by']) ? $edit_user['registered_by'] : 0; ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times me-2"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-primary" onclick="return confirm('Save changes to this user?')">
                            <i class="fas fa-save me-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Quick View Modal -->
    <div class="modal fade" id="quickViewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-eye me-2"></i>
                        User Quick View
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="quickViewContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading user details...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'includes/footer.php'; ?>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
    <script src="assets/js/main.js"></script>
    
    <!-- jQuery and Plugins -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    
    <script>
    // Toastr configuration
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "3000"
    };
    
    // Initialize Select2
    $(document).ready(function() {
        $('.form-select').select2({
            theme: 'bootstrap-5',
            width: '100%',
            dropdownParent: $(document.body)
        });
    });
    
    // Select All checkbox
    document.getElementById('selectAll')?.addEventListener('change', function() {
        var checkboxes = document.getElementsByClassName('user-checkbox');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].checked = this.checked;
        }
    });
    
    // Image preview
    document.getElementById('profileImage')?.addEventListener('change', function(e) {
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('imagePreview').src = e.target.result;
        }
        if (e.target.files[0]) {
            reader.readAsDataURL(e.target.files[0]);
        }
    });
    
    // Quick view function
    function quickView(userId) {
        var modal = new bootstrap.Modal(document.getElementById('quickViewModal'));
        var contentDiv = document.getElementById('quickViewContent');
        contentDiv.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-2 text-muted">Loading user details...</p></div>';
        modal.show();
        
        fetch('ajax/get_user_details.php?user_id=' + userId)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    var user = data.user;
                    var html = '<div class="row">';
                    
                    // Avatar
                    html += '<div class="col-md-4 text-center mb-3">';
                    var avatar = (user.image && user.image != 'noprofil.jpg') ? '../profile-img/' + user.image : '..\uploads\profiles/noprofil.jpg';
                    html += '<img src="' + avatar + '" class="img-fluid rounded-circle mb-3" style="width: 150px; height: 150px; object-fit: cover; border: 3px solid #fff; box-shadow: 0 4px 20px rgba(0,0,0,0.1);" onerror="this.src=\'..\uploads\profiles/noprofil.jpg\'">';
                    html += '<h5>' + user.name + '</h5>';
                    html += '<p class="text-muted mb-2">ID: ' + user.user_id + '</p>';
                    if (user.status == 1) {
                        html += '<span class="badge bg-success px-3 py-2">Active</span>';
                    } else {
                        html += '<span class="badge bg-warning px-3 py-2">Inactive</span>';
                    }
                    html += '</div>';
                    
                    // Details
                    html += '<div class="col-md-8">';
                    html += '<div class="row g-3">';
                    
                    var details = [
                        { label: 'Mobile', value: user.mobile },
                        { label: 'Email', value: user.email || 'N/A' },
                        { label: 'Sponsor ID', value: user.sponsor_id || 'N/A' },
                        { label: 'Package', value: user.package_id == 2500 ? '₹2500 Basic' : (user.package_id == 3500 ? '₹3500 Premium' : 'No Package') },
                        { label: 'Wallet', value: '₹' + parseFloat(user.wallet).toFixed(2) },
                        { label: 'Rank', value: user.rank || 'No Rank' },
                        { label: 'Left/Right Count', value: user.left_count + ' / ' + user.right_count },
                        { label: 'Joined', value: new Date(user.joining_date || user.created_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' }) }
                    ];
                    
                    details.forEach(detail => {
                        html += '<div class="col-md-6">';
                        html += '<div class="border rounded p-3 bg-light">';
                        html += '<small class="text-muted d-block">' + detail.label + '</small>';
                        html += '<strong>' + detail.value + '</strong>';
                        html += '</div>';
                        html += '</div>';
                    });
                    
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                    
                    contentDiv.innerHTML = html;
                } else {
                    contentDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i>User not found!</div>';
                }
            })
            .catch(error => {
                contentDiv.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i>Error loading user details!</div>';
                console.error('Error:', error);
            });
    }
    
    // Show edit modal if edit parameter exists
    <?php if (isset($_GET['edit']) && $_GET['edit'] !== 'new' && $edit_user): ?>
    document.addEventListener('DOMContentLoaded', function() {
        var editModal = new bootstrap.Modal(document.getElementById('editUserModal'));
        document.getElementById('modalUserTitle').innerText = 'Edit User - <?php echo $edit_user['user_id']; ?>';
        editModal.show();
    });
    <?php endif; ?>
    
    // Show success/error messages via toastr
    <?php if ($message): ?>
    toastr["<?php echo $message_type; ?>"]("<?php echo addslashes($message); ?>");
    <?php endif; ?>
    
    // Handle form submission
    document.getElementById('editUserForm')?.addEventListener('submit', function(e) {
        if (!confirm('Save changes to this user?')) {
            e.preventDefault();
        }
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>