<?php
/**
 * List Assignments for a Company
 * GET /v1/assignments?company_id=...
 */

declare(strict_types=1);

use App\Core\Database;
use App\Core\Encryption;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$companyId = input('company_id');

if (!$companyId) {
    json_error('company_id is required', 422);
}

$db = Database::getInstance();

try {
    $stmt = $db->prepare("
        SELECT a.id, a.user_id, a.is_active, u.name, u.email, u.role
        FROM user_company_assignments a
        JOIN users u ON a.user_id = u.id
        WHERE a.company_id = ? AND a.is_active = 1
    ");
    $stmt->execute([$companyId]);
    $assignments = $stmt->fetchAll();

    foreach ($assignments as &$a) {
        $a['name'] = Encryption::decrypt($a['name']) ?: $a['name'];
        $a['email'] = Encryption::decrypt($a['email']) ?: $a['email'];
    }

    json_success($assignments);

} catch (\Exception $e) {
    json_error('SQL Error: ' . $e->getMessage(), 500);
}
