<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'users', 'view', $pdo);

/* FILTERS */
$company_filter = isset($_GET['company_id']) ? (int)$_GET['company_id'] : null;
$role_filter    = isset($_GET['role']) ? trim($_GET['role']) : null;

$sql = "
SELECT 
    u.id,
    u.first_name,
    u.last_name,
    u.email,
    u.role,
    u.status,
    u.company_id,
    c.company_name,
    r.name AS rsp_name,
    c.rsp_id
FROM users u
LEFT JOIN companies c ON c.id = u.company_id
LEFT JOIN rsps r ON r.id = c.rsp_id
";

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

/* TENANT ISOLATION */
if (!empty($user['rsp_id'])) {
    $where[] = "c.rsp_id = ?";
    $params[] = (int)$user['rsp_id'];
}

/* FILTERS */
if ($company_filter) {
    $where[] = "u.company_id = ?";
    $params[] = $company_filter;
}

if ($role_filter) {
    $where[] = "u.role = ?";
    $params[] = $role_filter;
}

/* APPLY WHERE */
if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY u.created_at DESC LIMIT 500";

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

$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* REMOVE INTERNAL FIELDS */
foreach ($users as &$u) {
    unset($u['rsp_id']);
}

json_response(true, 'Users fetched.', [
    'count' => count($users),
    'users' => $users
]);