<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is admin
adminOnly();

$user = getUserContext();
$pdo = getDB();

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    $action = $_POST['bulk_action'];
    $user_ids = $_POST['user_ids'] ?? [];

    if (!empty($user_ids) && is_array($user_ids)) {
        try {
            $pdo->beginTransaction();

            switch ($action) {
                case 'activate':
                    $stmt = $pdo->prepare("UPDATE users SET email_verified = TRUE WHERE id IN (" . str_repeat('?,', count($user_ids) - 1) . "?)");
                    $stmt->execute($user_ids);
                    break;

                case 'deactivate':
                    $stmt = $pdo->prepare("UPDATE users SET email_verified = FALSE WHERE id IN (" . str_repeat('?,', count($user_ids) - 1) . "?)");
                    $stmt->execute($user_ids);
                    break;

                case 'change_role':
                    $new_role = $_POST['new_role'] ?? '';
                    if (in_array($new_role, getAllRoles())) {
                        $stmt = $pdo->prepare("UPDATE users SET role = ? WHERE id IN (" . str_repeat('?,', count($user_ids) - 1) . "?)");
                        $stmt->execute(array_merge([$new_role], $user_ids));
                    }
                    break;

                case 'delete':
                    // Prevent deleting own account or admin accounts
                    $current_user_id = $_SESSION['user_id'];
                    $filtered_ids = array_filter($user_ids, function($id) use ($current_user_id) {
                        return $id != $current_user_id;
                    });

                    if (!empty($filtered_ids)) {
                        // Delete user profiles first
                        $stmt = $pdo->prepare("DELETE FROM user_profiles WHERE user_id IN (" . str_repeat('?,', count($filtered_ids) - 1) . "?)");
                        $stmt->execute($filtered_ids);

                        // Delete user activities
                        $stmt = $pdo->prepare("DELETE FROM user_activities WHERE user_id IN (" . str_repeat('?,', count($filtered_ids) - 1) . "?)");
                        $stmt->execute($filtered_ids);

                        // Delete achievements
                        $stmt = $pdo->prepare("DELETE FROM user_achievements WHERE user_id IN (" . str_repeat('?,', count($filtered_ids) - 1) . "?)");
                        $stmt->execute($filtered_ids);

                        // Finally delete users
                        $stmt = $pdo->prepare("DELETE FROM users WHERE id IN (" . str_repeat('?,', count($filtered_ids) - 1) . "?)");
                        $stmt->execute($filtered_ids);
                    }
                    break;
            }

            $pdo->commit();
            $success_message = "Bulk action completed successfully.";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = "Error performing bulk action: " . $e->getMessage();
        }
    }
}

// Handle export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="users_export_' . date('Y-m-d') . '.csv"');

    $output = fopen('php://output', 'w');
    fputcsv($output, ['ID', 'Username', 'Email', 'Role', 'Email Verified', 'Last Login', 'Created At']);

    $stmt = $pdo->query("SELECT id, username, email, role, email_verified, last_login, created_at FROM users ORDER BY created_at DESC");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit;
}

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

// Build query with filters
$where_conditions = [];
$params = [];

$search = trim($_GET['search'] ?? '');
if ($search) {
    $where_conditions[] = "(username LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$role_filter = $_GET['role'] ?? '';
if ($role_filter && in_array($role_filter, getAllRoles())) {
    $where_conditions[] = "role = ?";
    $params[] = $role_filter;
}

$status_filter = $_GET['status'] ?? '';
if ($status_filter) {
    if ($status_filter === 'verified') {
        $where_conditions[] = "email_verified = TRUE";
    } elseif ($status_filter === 'unverified') {
        $where_conditions[] = "email_verified = FALSE";
    }
}

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

// Get total count
$count_sql = "SELECT COUNT(*) FROM users $where_clause";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_users = $count_stmt->fetchColumn();
$total_pages = ceil($total_users / $per_page);

// Get users
$sql = "SELECT u.*, up.first_name, up.last_name,
               (SELECT COUNT(*) FROM user_activities ua WHERE ua.user_id = u.id) as activity_count,
               (SELECT COUNT(*) FROM user_achievements ua2 WHERE ua2.user_id = u.id) as achievement_count
        FROM users u
        LEFT JOIN user_profiles up ON u.id = up.user_id
        $where_clause
        ORDER BY u.created_at DESC
        LIMIT ? OFFSET ?";

$stmt = $pdo->prepare($sql);

// Bind existing parameters
foreach ($params as $index => $param) {
    $stmt->bindValue($index + 1, $param);
}

// Bind LIMIT and OFFSET as integers
$stmt->bindValue(count($params) + 1, $per_page, PDO::PARAM_INT);
$stmt->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);

$stmt->execute();
$users = $stmt->fetchAll();

$page_title = 'User Management';
include 'includes/admin_header.php';
?>

<?php if (isset($success_message)): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success_message); ?>
    </div>
<?php endif; ?>

<?php if (isset($error_message)): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error_message); ?>
    </div>
<?php endif; ?>

<div class="users-management">
    <div class="management-header">
        <div class="header-info">
            <h2><i class="fas fa-users"></i> User Management</h2>
            <p>Manage all users across the platform</p>
        </div>
        <div class="header-actions">
            <a href="?export=csv" class="btn btn-secondary">
                <i class="fas fa-download"></i> Export CSV
            </a>
            <a href="user_create.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add User
            </a>
        </div>
    </div>

    <!-- Filters and Search -->
    <div class="filters-section">
        <form method="GET" class="filters-form">
            <div class="filter-row">
                <div class="filter-group">
                    <input type="text" name="search" placeholder="Search by username or email..."
                           value="<?php echo htmlspecialchars($search); ?>" class="search-input">
                </div>

                <div class="filter-group">
                    <select name="role" class="filter-select">
                        <option value="">All Roles</option>
                        <?php foreach (getAllRoles() as $role): ?>
                            <option value="<?php echo $role; ?>" <?php echo $role_filter === $role ? 'selected' : ''; ?>>
                                <?php echo getRoleDisplayName($role); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-group">
                    <select name="status" class="filter-select">
                        <option value="">All Status</option>
                        <option value="verified" <?php echo $status_filter === 'verified' ? 'selected' : ''; ?>>Verified</option>
                        <option value="unverified" <?php echo $status_filter === 'unverified' ? 'selected' : ''; ?>>Unverified</option>
                    </select>
                </div>

                <div class="filter-actions">
                    <button type="submit" class="btn btn-sm">Filter</button>
                    <a href="users.php" class="btn btn-sm btn-secondary">Clear</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Bulk Actions Form -->
    <form method="POST" id="bulk-form">
        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

        <div class="bulk-actions">
            <div class="bulk-select">
                <label>
                    <input type="checkbox" id="select-all">
                    Select All
                </label>
            </div>

            <div class="bulk-controls">
                <select name="bulk_action" id="bulk-action" required>
                    <option value="">Choose Action</option>
                    <option value="activate">Activate Users</option>
                    <option value="deactivate">Deactivate Users</option>
                    <option value="change_role">Change Role</option>
                    <option value="delete">Delete Users</option>
                </select>

                <select name="new_role" id="role-select" style="display: none;">
                    <?php foreach (getAllRoles() as $role): ?>
                        <option value="<?php echo $role; ?>"><?php echo getRoleDisplayName($role); ?></option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to perform this action?')">
                    Apply
                </button>
            </div>
        </div>

        <!-- Users Table -->
        <div class="users-table-container">
            <table class="users-table">
                <thead>
                    <tr>
                        <th width="40"></th>
                        <th>User</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Activity</th>
                        <th>Last Login</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user_data): ?>
                        <tr>
                            <td>
                                <input type="checkbox" name="user_ids[]" value="<?php echo $user_data['id']; ?>"
                                       class="user-checkbox">
                            </td>
                            <td>
                                <div class="user-info">
                                    <div class="user-name">
                                        <?php echo htmlspecialchars($user_data['username']); ?>
                                        <?php if ($user_data['first_name'] || $user_data['last_name']): ?>
                                            <small><?php echo htmlspecialchars(trim($user_data['first_name'] . ' ' . $user_data['last_name'])); ?></small>
                                        <?php endif; ?>
                                    </div>
                                    <div class="user-email"><?php echo htmlspecialchars($user_data['email']); ?></div>
                                </div>
                            </td>
                            <td>
                                <span class="role-badge role-<?php echo $user_data['role']; ?>">
                                    <?php echo getRoleDisplayName($user_data['role']); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($user_data['email_verified']): ?>
                                    <span class="status-badge status-active">Verified</span>
                                <?php else: ?>
                                    <span class="status-badge status-inactive">Unverified</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="activity-info">
                                    <span><?php echo $user_data['activity_count']; ?> actions</span>
                                    <span><?php echo $user_data['achievement_count']; ?> achievements</span>
                                </div>
                            </td>
                            <td>
                                <?php echo $user_data['last_login'] ? formatDate($user_data['last_login']) : 'Never'; ?>
                            </td>
                            <td><?php echo formatDate($user_data['created_at']); ?></td>
                            <td>
                                <div class="action-buttons">
                                    <a href="user_profile.php?id=<?php echo $user_data['id']; ?>" class="btn btn-xs">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="user_create.php?id=<?php echo $user_data['id']; ?>" class="btn btn-xs btn-secondary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($users)): ?>
            <div class="no-users">
                <i class="fas fa-users"></i>
                <p>No users found matching your criteria.</p>
            </div>
        <?php endif; ?>
    </form>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php
            $query_string = http_build_query(array_filter([
                'search' => $search,
                'role' => $role_filter,
                'status' => $status_filter
            ]));

            if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&<?php echo $query_string; ?>" class="page-link">Previous</a>
            <?php endif; ?>

            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <a href="?page=<?php echo $i; ?>&<?php echo $query_string; ?>"
                   class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&<?php echo $query_string; ?>" class="page-link">Next</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Select all checkbox
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.user-checkbox');

    selectAll.addEventListener('change', function() {
        checkboxes.forEach(cb => cb.checked = this.checked);
    });

    // Show role select when changing role
    const bulkAction = document.getElementById('bulk-action');
    const roleSelect = document.getElementById('role-select');

    bulkAction.addEventListener('change', function() {
        if (this.value === 'change_role') {
            roleSelect.style.display = 'inline-block';
            roleSelect.required = true;
        } else {
            roleSelect.style.display = 'none';
            roleSelect.required = false;
        }
    });
});
</script>

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