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

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

$db = getDB();

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

$stats = $db->query("SELECT COUNT(*) as total, SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active, SUM(CASE WHEN status = 'blocked' THEN 1 ELSE 0 END) as blocked, SUM(CASE WHEN DATE(registered_at) = CURDATE() THEN 1 ELSE 0 END) as today FROM users")->fetch();

$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$query = "SELECT * FROM users WHERE 1=1";
$params = [];

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

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

$query .= " ORDER BY registered_at DESC";
$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>Dashboard - 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">Dashboard</h2>
                </div>
            </header>
            <main class="p-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow p-6">
                <p class="text-gray-500 text-sm">Total Users</p>
                <p class="text-3xl font-bold text-gray-800"><?= $stats['total'] ?></p>
            </div>
            <div class="bg-white rounded-lg shadow p-6">
                <p class="text-gray-500 text-sm">Active Users</p>
                <p class="text-3xl font-bold text-green-600"><?= $stats['active'] ?></p>
            </div>
            <div class="bg-white rounded-lg shadow p-6">
                <p class="text-gray-500 text-sm">Blocked Users</p>
                <p class="text-3xl font-bold text-red-600"><?= $stats['blocked'] ?></p>
            </div>
            <div class="bg-white rounded-lg shadow p-6">
                <p class="text-gray-500 text-sm">Today's Registrations</p>
                <p class="text-3xl font-bold text-purple-600"><?= $stats['today'] ?></p>
            </div>
        </div>
        <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..." 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>
                </select>
                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg">Filter</button>
                <a href="dashboard.php" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">Reset</a>
            </form>
        </div>
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <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">User</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Machine Info</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">System</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Registered</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">
                            <div class="text-sm font-medium"><?= 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"><?= htmlspecialchars($user['computer_name']) ?></div>
                            <div class="text-sm text-gray-500"><?= htmlspecialchars($user['windows_user']) ?></div>
                        </td>
                        <td class="px-6 py-4 text-sm"><?= htmlspecialchars($user['os']) ?></td>
                        <td class="px-6 py-4 text-sm"><?= date('M d, Y', strtotime($user['registered_at'])) ?></td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 text-xs font-semibold rounded-full <?= $user['status'] === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                <?= ucfirst($user['status']) ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <?php if ($user['status'] === 'active'): ?>
                            <form method="POST" class="inline">
                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                <input type="hidden" name="action" value="block">
                                <button class="text-red-600 hover:text-red-900">Block</button>
                            </form>
                            <?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="text-green-600 hover:text-green-900">Activate</button>
                            </form>
                            <?php endif; ?>
                            <form method="POST" class="inline ml-2" onsubmit="return confirm('Delete?')">
                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                <input type="hidden" name="action" value="delete">
                                <button class="text-red-600 hover:text-red-900">Delete</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($users)): ?>
                    <tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">No users found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
            </main>
        </div>
    </div>
</body>
</html>
