<?php
/**
 * Admin - User Management
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
admin_only();

$pageTitle = 'User Management';
$db = Database::getInstance();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $action = $_POST['action'] ?? '';
    $userId = (int) ($_POST['user_id'] ?? 0);

    if ($action === 'toggle_status' && $userId > 0) {
        $user = $db->fetch("SELECT status FROM users WHERE id = ?", [$userId]);
        if ($user) {
            $newStatus = $user['status'] === 'active' ? 'inactive' : 'active';
            $db->update('users', ['status' => $newStatus], 'id = ?', [$userId]);
            log_action(SessionManager::getUserId(), 'update', 'users', $userId, ['status' => $newStatus]);
            set_success('User status updated.');
        }
    } elseif ($action === 'delete' && $userId > 0 && $userId !== SessionManager::getUserId()) {
        $db->delete('users', 'id = ?', [$userId]);
        log_action(SessionManager::getUserId(), 'delete', 'users', $userId);
        set_success('User deleted.');
    }

    redirect(APP_URL . '/admin/users.php');
}

// Search & Filter
$search = trim($_GET['search'] ?? '');
$roleFilter = $_GET['role'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$page = max(1, (int) ($_GET['page'] ?? 1));

$where = '1=1';
$params = [];
if ($search) {
    $where .= " AND (username LIKE ? OR email LIKE ? OR full_name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($roleFilter) {
    $where .= " AND role = ?";
    $params[] = $roleFilter;
}
if ($statusFilter) {
    $where .= " AND status = ?";
    $params[] = $statusFilter;
}

$total = $db->fetchColumn("SELECT COUNT(*) FROM users WHERE $where", $params);
$pagination = new Pagination($total, ITEMS_PER_PAGE, $page);
$users = $db->fetchAll("SELECT * FROM users WHERE $where ORDER BY created_at DESC LIMIT {$pagination->getLimit()} OFFSET {$pagination->getOffset()}", $params);

include APP_ROOT . '/templates/header.php';
?>

<div class="toolbar">
    <div class="toolbar-left" style="display:flex;gap:10px;flex-wrap:wrap">
        <a href="<?= APP_URL ?>/register.php" class="btn btn-primary">+ Add User</a>
    </div>
    <form method="GET" class="toolbar-right" style="display:flex;gap:10px;flex-wrap:wrap">
        <div class="search-box">
            <input type="text" name="search" class="form-control" placeholder="Search users..." value="<?= e($search) ?>">
        </div>
        <select name="role" class="form-control" style="width:auto">
            <option value="">All Roles</option>
            <option value="admin" <?= $roleFilter === 'admin' ? 'selected' : '' ?>>Admin</option>
            <option value="controller" <?= $roleFilter === 'controller' ? 'selected' : '' ?>>Controller</option>
            <option value="counter" <?= $roleFilter === 'counter' ? 'selected' : '' ?>>Counter</option>
            <option value="checker" <?= $roleFilter === 'checker' ? 'selected' : '' ?>>Checker</option>
        </select>
        <select name="status" class="form-control" style="width:auto">
            <option value="">All Status</option>
            <option value="active" <?= $statusFilter === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $statusFilter === 'inactive' ? 'selected' : '' ?>>Inactive</option>
        </select>
        <button type="submit" class="btn btn-outline">Filter</button>
    </form>
</div>

<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Last Login</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($users)): ?>
                <tr><td colspan="8" class="text-center text-muted" style="padding:40px">No users found.</td></tr>
                <?php else: foreach ($users as $user): ?>
                <tr>
                    <td><strong><?= e($user['full_name']) ?></strong></td>
                    <td><?= e($user['username']) ?></td>
                    <td><?= e($user['email']) ?></td>
                    <td><?= status_badge($user['role']) ?></td>
                    <td><?= status_badge($user['status']) ?></td>
                    <td><?= $user['last_login'] ? time_ago($user['last_login']) : '<span class="text-muted">Never</span>' ?></td>
                    <td><?= format_date($user['created_at']) ?></td>
                    <td>
                        <div class="table-actions">
                            <form method="POST" style="display:inline">
                                <?= Csrf::field() ?>
                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                <input type="hidden" name="action" value="toggle_status">
                                <button type="submit" class="btn btn-sm <?= $user['status'] === 'active' ? 'btn-warning' : 'btn-success' ?>" title="<?= $user['status'] === 'active' ? 'Deactivate' : 'Activate' ?>">
                                    <?= $user['status'] === 'active' ? '&#9632;' : '&#9658;' ?>
                                </button>
                            </form>
                            <?php if ($user['id'] !== SessionManager::getUserId()): ?>
                            <form method="POST" style="display:inline" onsubmit="return confirm('Are you sure you want to delete this user?')">
                                <?= Csrf::field() ?>
                                <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                <input type="hidden" name="action" value="delete">
                                <button type="submit" class="btn btn-sm btn-danger" title="Delete">&#128465;</button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($pagination->getTotalPages() > 1): ?>
    <div class="card-footer">
        <?= $pagination->render(get_current_url()) ?>
    </div>
    <?php endif; ?>
</div>

<?php include APP_ROOT . '/templates/footer.php'; ?>
