<?php
// POST /api/auth/users_list.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user            = requireAuth();
$db              = getDB();
$roleId          = (int)post('role_id', 0);
$includeInactive = post('include_inactive', 0);

$where  = [];
$params = [];

// By default only active users — unless include_inactive passed
if (!$includeInactive) {
    $where[] = 'is_active = 1';
}
if ($roleId) { $where[] = 'role_id = ?'; $params[] = $roleId; }

$whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $db->prepare("SELECT id, full_name, username, email, role_id, is_active, last_login FROM users $whereClause ORDER BY is_active DESC, full_name ASC");
try {
    $stmt->execute($params);
    $users = $stmt->fetchAll();
} catch (PDOException $e) {
    // Fallback without last_login if column doesn't exist
    $stmt2 = $db->prepare("SELECT id, full_name, username, email, role_id, is_active, NULL AS last_login FROM users $whereClause ORDER BY is_active DESC, full_name ASC");
    $stmt2->execute($params);
    $users = $stmt2->fetchAll();
}
apiSuccess(['users' => $users]);