<?php
$page_title = "Users Management";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Filters
$status = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';
$sort = $_GET['sort'] ?? 'newest';

// Build query
$where = [];
$params = [];

if ($status) {
    $where[] = "account_status = ?";
    $params[] = $status;
}

if ($search) {
    $where[] = "(username LIKE ? OR email LIKE ? OR full_name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

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

// Sorting
$order_by = "ORDER BY ";
switch ($sort) {
    case 'oldest': $order_by .= "created_at ASC"; break;
    case 'balance_high': $order_by .= "balance DESC"; break;
    case 'balance_low': $order_by .= "balance ASC"; break;
    default: $order_by .= "created_at DESC"; break;
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM users $where_clause";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_users = $count_stmt->fetch()['total'];
$total_pages = ceil($total_users / $limit);

// Get users
$sql = "SELECT * FROM users $where_clause $order_by LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN account_status = 'active' THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN account_status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN account_status = 'suspended' THEN 1 ELSE 0 END) as suspended,
    SUM(balance) as total_balance,
    SUM(total_deposit) as total_deposited
    FROM users";
$stats_stmt = $db->prepare($stats_sql);
$stats_stmt->execute();
$stats = $stats_stmt->fetch();
?>

<!-- Content -->
<div class="container-fluid">
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Users</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format((int)($stats['total'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-users text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Users</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format((int)($stats['active'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-user-check text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Pending Users</p>
                    <h3 class="text-2xl font-bold text-yellow-600"><?php echo number_format((int)($stats['pending'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-user-clock text-yellow-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Suspended Users</p>
                    <h3 class="text-2xl font-bold text-red-600"><?php echo number_format((int)($stats['suspended'] ?? 0)); ?></h3>
                </div>
                <i class="fas fa-user-slash text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Balance</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format((float)($stats['total_balance'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-wallet text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Deposited</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format((float)($stats['total_deposited'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave text-green-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Filters and Actions -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <!-- Search -->
            <div class="flex-1">
                <form method="GET" action="">
                    <div class="flex">
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
                               class="flex-1 px-4 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-purple-500"
                               placeholder="Search by username, email, or name">
                        <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-r-lg hover:bg-purple-700">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Filters -->
            <div class="flex flex-wrap gap-2">
                <a href="?status=active" class="px-3 py-2 rounded-lg <?php echo $status == 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                    Active
                </a>
                <a href="?status=pending" class="px-3 py-2 rounded-lg <?php echo $status == 'pending' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800'; ?>">
                    Pending
                </a>
                <a href="?status=suspended" class="px-3 py-2 rounded-lg <?php echo $status == 'suspended' ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800'; ?>">
                    Suspended
                </a>
                <a href="?" class="px-3 py-2 rounded-lg bg-gray-800 text-white">
                    All Users
                </a>
            </div>
            
            <!-- Actions -->
            <div class="flex gap-2">
                <a href="user-create.php" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                    <i class="fas fa-user-plus mr-2"></i>Create User
                </a>
                <button onclick="exportUsers()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-download mr-2"></i>Export
                </button>
            </div>
        </div>
        
        <!-- Sort Options -->
        <div class="mt-4 flex flex-wrap gap-2">
            <span class="text-gray-600">Sort by:</span>
            <a href="?sort=newest<?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
               class="px-3 py-1 rounded <?php echo $sort == 'newest' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                Newest First
            </a>
            <a href="?sort=oldest<?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
               class="px-3 py-1 rounded <?php echo $sort == 'oldest' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                Oldest First
            </a>
            <a href="?sort=balance_high<?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
               class="px-3 py-1 rounded <?php echo $sort == 'balance_high' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                Balance (High to Low)
            </a>
            <a href="?sort=balance_low<?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
               class="px-3 py-1 rounded <?php echo $sort == 'balance_low' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                Balance (Low to High)
            </a>
        </div>
    </div>

    <!-- Users Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Contact</th>
                        <th class="p-4 text-left">Balance</th>
                        <th class="p-4 text-left">Investments</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Joined</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($users) > 0): ?>
                        <?php foreach ($users as $user): 
                            // Get investment stats for this user
                            $inv_stmt = $db->prepare("SELECT COUNT(*) as count, SUM(amount) as total FROM investments WHERE user_id = ?");
                            $inv_stmt->execute([$user['id']]);
                            $investment = $inv_stmt->fetch();
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- User Info -->
                            <td class="p-4">
                                <div class="flex items-center space-x-3">
                                    <div class="w-10 h-10 bg-gradient-to-r from-purple-500 to-blue-500 rounded-full flex items-center justify-center text-white font-bold">
                                        <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                                    </div>
                                    <div>
                                        <p class="font-semibold"><?php echo htmlspecialchars($user['username']); ?></p>
                                        <p class="text-sm text-gray-500">ID: <?php echo $user['id']; ?></p>
                                        <?php if ($user['referred_by']): ?>
                                        <p class="text-xs text-blue-600">Referred by: <?php echo $user['referred_by']; ?></p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Contact -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($user['email']); ?></p>
                                <?php if ($user['phone']): ?>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($user['phone']); ?></p>
                                <?php endif; ?>
                                <?php if ($user['country']): ?>
                                <p class="text-xs text-gray-500"><?php echo htmlspecialchars($user['country']); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Balance -->
                            <td class="p-4">
                                <p class="font-bold text-green-600">$<?php echo number_format($user['balance'], 2); ?></p>
                                <div class="text-xs text-gray-500 space-y-1">
                                    <p>Deposited: $<?php echo number_format($user['total_deposit'], 2); ?></p>
                                    <p>Withdrawn: $<?php echo number_format($user['total_withdrawal'], 2); ?></p>
                                </div>
                            </td>
                            
                            <!-- Investments -->
                            <td class="p-4">
                                <p class="font-medium">$<?php echo number_format($investment['total'] ?? 0, 2); ?></p>
                                <p class="text-sm text-gray-500"><?php echo $investment['count'] ?? 0; ?> investments</p>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo $user['account_status'] == 'active' ? 'bg-green-100 text-green-800' :
                                        ($user['account_status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                        'bg-red-100 text-red-800');
                                ?>">
                                    <?php echo ucfirst($user['account_status']); ?>
                                </span>
                                <?php if (!$user['email_verified']): ?>
                                <span class="ml-1 px-2 py-1 bg-red-100 text-red-800 text-xs rounded">Email Not Verified</span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Joined -->
                            <td class="p-4">
                                <p><?php echo date('M d, Y', strtotime($user['created_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo time_ago($user['created_at']); ?></p>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <a href="user-edit.php?id=<?php echo $user['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-edit mr-1"></i> Edit
                                    </a>
                                    <a href="../user/dashboard.php?admin_view=<?php echo $user['id']; ?>" 
                                       target="_blank" class="text-green-600 hover:text-green-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View as User
                                    </a>
                                    <?php if ($user['account_status'] == 'active'): ?>
                                    <a href="?action=suspend&id=<?php echo $user['id']; ?>" 
                                       onclick="return confirm('Suspend this user?')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-ban mr-1"></i> Suspend
                                    </a>
                                    <?php else: ?>
                                    <a href="?action=activate&id=<?php echo $user['id']; ?>" 
                                       onclick="return confirm('Activate this user?')"
                                       class="text-green-600 hover:text-green-800 text-sm font-medium">
                                        <i class="fas fa-check mr-1"></i> Activate
                                    </a>
                                    <?php endif; ?>
                                    <a href="transactions.php?user_id=<?php echo $user['id']; ?>" 
                                       class="text-purple-600 hover:text-purple-800 text-sm font-medium">
                                        <i class="fas fa-history mr-1"></i> Transactions
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="p-8 text-center text-gray-500">
                                <i class="fas fa-users text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No users found</p>
                                <?php if ($status || $search): ?>
                                <p class="text-sm mt-2">Try changing your search filters</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_users); ?> of <?php echo number_format($total_users); ?> users
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?><?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?><?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?><?php echo $status ? "&status=$status" : ''; ?><?php echo $search ? "&search=$search" : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function exportUsers() {
    if (confirm('Export user list to CSV?')) {
        window.location.href = '../api/export-users.php?<?php echo $_SERVER['QUERY_STRING']; ?>';
    }
}

// Handle actions via AJAX
function updateUserStatus(userId, action) {
    if (confirm('Are you sure you want to ' + action + ' this user?')) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: action + '_user',
                user_id: userId
            },
            success: function(response) {
                const result = JSON.parse(response);
                if (result.success) {
                    showNotification(result.message, 'success');
                    location.reload();
                } else {
                    showNotification('Error: ' + result.message, 'error');
                }
            }
        });
    }
}

// Quick status update
document.querySelectorAll('.quick-status').forEach(button => {
    button.addEventListener('click', function() {
        const userId = this.dataset.userId;
        const action = this.dataset.action;
        updateUserStatus(userId, action);
    });
});
</script>

<?php require_once 'footer.php'; ?>