<?php
declare(strict_types=1);

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

try {
    $actor = require_auth($pdo);
    $role  = $actor['role_key'];

    if (!in_array(
        $role,
        ['super_admin', 'platform_admin', 'rsp_admin', 'company_admin'],
        true
    )) {
        error_forbidden('Forbidden');
    }

    $userId = (int)($_GET['id'] ?? 0);
    if ($userId <= 0) {
        error_bad_request('Invalid user id');
    }

    $stmt = $pdo->prepare("
        SELECT
            u.id,
            u.email,
            u.role_key,
            u.status,
            u.email_verified,
            u.company_id,
            c.company_name
        FROM users u
        LEFT JOIN companies c
            ON c.id = u.company_id
           AND c.deleted_at IS NULL
        WHERE u.id = ?
          AND u.deleted_at IS NULL
        LIMIT 1
    ");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        error_not_found('User not found');
    }

    // Company admin isolation
    if (
        $role === 'company_admin' &&
        (int)$actor['company_id'] !== (int)$user['company_id']
    ) {
        error_forbidden('Forbidden');
    }

    success('User loaded', $user);

} catch (Throwable $e) {
    error_log('USER VIEW ERROR: ' . $e->getMessage());
    error_server('Failed to load user');
}
