<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';
require_once __DIR__ . '/../system/modules_service.php';
require_once __DIR__ . '/../system/modules_guard.php';

header('Content-Type: application/json');

/* =========================
   AUTH
   ========================= */
$actor = require_auth($pdo);

/*
 | Single enforcement point
 | Platform admins bypass inside the guard if needed
 */
requireModule('USERS');

/* =========================
   INPUT
   ========================= */
$page  = max(1, (int)($_GET['page'] ?? 1));
$limit = max(1, min(100, (int)($_GET['limit'] ?? 10)));
$offset = ($page - 1) * $limit;

$search    = trim((string)($_GET['search'] ?? ''));
$companyId = (int)($_GET['company_id'] ?? 0);
$rspId     = (int)($_GET['rsp_id'] ?? 0);
$role      = trim((string)($_GET['role'] ?? ''));

/* =========================
   WHERE BUILD
   ========================= */
$where = ['u.deleted_at IS NULL'];
$params = [];

/* Product isolation */
if (empty($actor['is_global'])) {
    $where[] = 'c.product_id = :actor_product';
    $params['actor_product'] = (int)$actor['product_id'];
}

/* Scope enforcement */
if ($actor['role_key'] === 'company_admin') {
    $where[] = 'u.company_id = :actor_company';
    $params['actor_company'] = (int)$actor['company_id'];
}

if ($actor['role_key'] === 'rsp_admin' || $actor['role_key'] === 'rsp_owner') {
    $where[] = '(c.id = :actor_rsp OR c.rsp_id = :actor_rsp)';
    $params['actor_rsp'] = (int)$actor['company_id'];
}

/* Filters */
if ($search !== '') {
    $where[] = 'u.email LIKE :search';
    $params['search'] = '%' . $search . '%';
}

if ($companyId > 0) {
    $where[] = 'u.company_id = :company_id';
    $params['company_id'] = $companyId;
}

if ($rspId > 0) {
    $where[] = 'c.rsp_id = :rsp_id';
    $params['rsp_id'] = $rspId;
}

if ($role !== '') {
    $where[] = 'u.role_key = :role';
    $params['role'] = $role;
}

/* =========================
   COUNT
   ========================= */
$countSql = "
    SELECT COUNT(*)
    FROM users u
    JOIN companies c ON c.id = u.company_id
    WHERE " . implode(' AND ', $where);

$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();

/* =========================
   DATA
   ========================= */
$dataSql = "
    SELECT
        u.id,
        u.email,
        u.first_name,
        u.last_name,
        u.role_key,
        u.status,
        u.email_verified,
        u.company_id,
        c.company_name,
        rsp.company_name AS rsp_name
    FROM users u
    JOIN companies c ON c.id = u.company_id
    LEFT JOIN companies rsp ON rsp.id = c.rsp_id
    WHERE " . implode(' AND ', $where) . "
    ORDER BY u.email
    LIMIT $limit OFFSET $offset
";

$stmt = $pdo->prepare($dataSql);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   RESPONSE
   ========================= */
success('Users loaded', [
    'users' => $users,
    'total' => $total
]);