<?php
session_start();
require_once '../config.php';

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

$db = getDB();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['user_id'])) {
    $userId = (int)$_POST['user_id'];
    if ($_POST['action'] === 'block') {
        $reason = $_POST['block_reason'] ?? 'No reason provided';
        $db->prepare("UPDATE users SET status = 'blocked', block_reason = ? WHERE id = ?")->execute([$reason, $userId]);
    } elseif ($_POST['action'] === 'activate') {
        $db->prepare("UPDATE users SET status = 'active', block_reason = NULL WHERE id = ?")->execute([$userId]);
    } elseif ($_POST['action'] === 'delete') {
        $db->prepare("DELETE FROM users WHERE id = ?")->execute([$userId]);
    }
    header('Location: users.php');
    exit;
}

// Get filters
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Build query
$query = "SELECT * FROM users WHERE 1=1";
$countQuery = "SELECT COUNT(*) as total FROM users WHERE 1=1";
$params = [];

if ($search) {
    $condition = " AND (email LIKE ? OR username LIKE ? OR machine_id LIKE ? OR computer_name LIKE ? OR windows_user LIKE ?)";
    $query .= $condition;
    $countQuery .= $condition;
    $searchTerm = "%$search%";
    $params = [$searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm];
}

if ($status) {
    $query .= " AND status = ?";
    $countQuery .= " AND status = ?";
    $params[] = $status;
}

// Get total count
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalUsers = $stmt->fetch()['total'];
$totalPages = ceil($totalUsers / $perPage);

// Get users
$query .= " ORDER BY registered_at DESC LIMIT $perPage OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$users = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Users - RSecurity Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <div class="flex h-screen">
        <?php include 'sidebar.php'; ?>
        
        <div class="flex-1 overflow-auto">
            <header class="bg-white shadow-sm">
                <div class="px-8 py-4">
                    <h2 class="text-2xl font-bold text-gray-800">Users Management</h2>
                    <span class="text-sm text-gray-600"><?= $totalUsers ?> Total Users</span>
                </div>
            </header>
            <main class="p-8">
                <!-- Filters -->
                <div class="bg-white rounded-lg shadow p-6 mb-6">
                    <form method="GET" class="flex flex-wrap gap-4">
                        <input type="text" name="search" placeholder="Search by email, username, machine ID..." 
                            value="<?= htmlspecialchars($search) ?>"
                            class="flex-1 min-w-[300px] px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
                        
                        <select name="status" class="px-4 py-2 border rounded-lg">
                            <option value="">All Status</option>
                            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
                            <option value="blocked" <?= $status === 'blocked' ? 'selected' : '' ?>>Blocked</option>
                            <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                        </select>
                        
                        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg">
                            Filter
                        </button>
                        <a href="users.php" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">
                            Reset
                        </a>
                    </form>
                </div>

                <!-- Users Table -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">User Info</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Machine Details</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">System Info</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Dates</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($users as $user): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 text-sm font-mono text-gray-500">#<?= $user['id'] ?></td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($user['username']) ?></div>
                                        <div class="text-sm text-gray-500"><?= htmlspecialchars($user['email']) ?></div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-900">💻 <?= htmlspecialchars($user['computer_name']) ?></div>
                                        <div class="text-sm text-gray-500">👤 <?= htmlspecialchars($user['windows_user']) ?></div>
                                        <div class="text-xs text-gray-400 font-mono mt-1">🔑 <?= htmlspecialchars(substr($user['machine_id'], 0, 25)) ?>...</div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm text-gray-900"><?= htmlspecialchars($user['os']) ?></div>
                                        <div class="text-xs text-gray-500"><?= htmlspecialchars($user['os_version']) ?></div>
                                        <div class="text-xs text-gray-400 mt-1">App v<?= htmlspecialchars($user['app_version']) ?></div>
                                    </td>
                                    <td class="px-6 py-4 text-sm">
                                        <div class="text-gray-900">📅 <?= date('M d, Y', strtotime($user['registered_at'])) ?></div>
                                        <div class="text-gray-500 text-xs">🕐 <?= date('H:i', strtotime($user['registered_at'])) ?></div>
                                        <?php if ($user['last_active']): ?>
                                        <div class="text-gray-400 text-xs mt-1">Last: <?= date('M d', strtotime($user['last_active'])) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <?php
                                        $statusColors = [
                                            'active' => 'bg-green-100 text-green-800',
                                            'blocked' => 'bg-red-100 text-red-800',
                                            'pending' => 'bg-yellow-100 text-yellow-800'
                                        ];
                                        $color = $statusColors[$user['status']] ?? 'bg-gray-100 text-gray-800';
                                        ?>
                                        <span class="px-3 py-1 text-xs font-semibold rounded-full <?= $color ?>">
                                            <?= ucfirst($user['status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="flex gap-2">
                                            <a href="view_user.php?id=<?= $user['id'] ?>" class="px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 text-xs font-medium">View</a>
                                            
                                            <?php if ($user['status'] === 'active'): ?>
                                            <button onclick="showBlockDialog(<?= $user['id'] ?>, '<?= htmlspecialchars($user['username']) ?>')" class="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 text-xs font-medium">Block</button>
                                            <?php else: ?>
                                            <form method="POST" class="inline">
                                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                                <input type="hidden" name="action" value="activate">
                                                <button class="px-3 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 text-xs font-medium">Activate</button>
                                            </form>
                                            <?php endif; ?>
                                            
                                            <form method="POST" class="inline" onsubmit="return confirm('Delete this user permanently?')">
                                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                                <input type="hidden" name="action" value="delete">
                                                <button class="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 text-xs font-medium">Delete</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                
                                <?php if (empty($users)): ?>
                                <tr>
                                    <td colspan="7" class="px-6 py-12 text-center">
                                        <div class="text-gray-400 text-lg">No users found</div>
                                        <div class="text-gray-500 text-sm mt-2">Try adjusting your search filters</div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <div class="bg-gray-50 px-6 py-4 flex justify-between items-center border-t">
                        <div class="text-sm text-gray-600">
                            Page <?= $page ?> of <?= $totalPages ?>
                        </div>
                        <div class="flex gap-2">
                            <?php if ($page > 1): ?>
                            <a href="?page=<?= $page - 1 ?><?= $search ? '&search=' . urlencode($search) : '' ?><?= $status ? '&status=' . $status : '' ?>" 
                               class="px-4 py-2 bg-white border rounded-lg hover:bg-gray-50">Previous</a>
                            <?php endif; ?>
                            
                            <?php if ($page < $totalPages): ?>
                            <a href="?page=<?= $page + 1 ?><?= $search ? '&search=' . urlencode($search) : '' ?><?= $status ? '&status=' . $status : '' ?>" 
                               class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Next</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </main>
        </div>
    </div>

    <!-- Block User Dialog -->
    <div id="blockDialog" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4">
            <h3 class="text-xl font-bold mb-4">Block User</h3>
            <p class="text-gray-600 mb-4">Block <span id="blockUsername" class="font-semibold"></span>?</p>
            <form method="POST" id="blockForm">
                <input type="hidden" name="user_id" id="blockUserId">
                <input type="hidden" name="action" value="block">
                <label class="block text-sm font-medium mb-2">Reason for blocking:</label>
                <select id="reasonSelect" class="w-full px-3 py-2 border rounded-lg mb-3" onchange="toggleCustomReason()">
                    <option value="Violation of terms of service">Violation of terms of service</option>
                    <option value="Suspicious activity detected">Suspicious activity detected</option>
                    <option value="Payment issues">Payment issues</option>
                    <option value="Security concerns">Security concerns</option>
                    <option value="Abuse or harassment">Abuse or harassment</option>
                    <option value="custom">Custom reason...</option>
                </select>
                <textarea id="customReason" name="block_reason" class="hidden w-full px-3 py-2 border rounded-lg mb-3" rows="3" placeholder="Enter custom reason..."></textarea>
                <div class="flex gap-3 justify-end">
                    <button type="button" onclick="closeBlockDialog()" class="px-4 py-2 bg-gray-500 hover:bg-gray-600 text-white rounded-lg">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">Block User</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showBlockDialog(userId, username) {
            document.getElementById('blockUserId').value = userId;
            document.getElementById('blockUsername').textContent = username;
            document.getElementById('blockDialog').classList.remove('hidden');
        }

        function closeBlockDialog() {
            document.getElementById('blockDialog').classList.add('hidden');
            document.getElementById('reasonSelect').value = 'Violation of terms of service';
            document.getElementById('customReason').classList.add('hidden');
        }

        function toggleCustomReason() {
            const select = document.getElementById('reasonSelect');
            const custom = document.getElementById('customReason');
            if (select.value === 'custom') {
                custom.classList.remove('hidden');
                custom.name = 'block_reason';
                custom.required = true;
            } else {
                custom.classList.add('hidden');
                custom.name = '';
                custom.required = false;
            }
        }

        document.getElementById('blockForm').addEventListener('submit', function(e) {
            const select = document.getElementById('reasonSelect');
            const custom = document.getElementById('customReason');
            if (select.value !== 'custom') {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'block_reason';
                hiddenInput.value = select.value;
                this.appendChild(hiddenInput);
            }
        });
    </script>
</body>
</html>
