<?php
/**
 * Create User-Company Assignment
 * POST /v1/assignments/create
 */

declare(strict_types=1);

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

// Only Admin/Super Admin
$decoded = RoleMiddleware::require(['super_admin', 'admin']);

$data = input();
$userId = $data['user_id'] ?? null;
$companyId = $data['company_id'] ?? null;

if (!$userId || !$companyId) {
    json_error('userId and companyId are required', 422);
}

$db = Database::getInstance();

try {
    // Check if user belongs to the same tenant (if not super_admin)
    if ($decoded['role'] !== 'super_admin') {
        $stmt = $db->prepare("SELECT tenant_id FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $userTenant = $stmt->fetchColumn();
        
        if ($userTenant !== $decoded['tenant_id']) {
            json_error('User does not belong to your office', 403);
        }
    }

    $stmt = $db->prepare("
        INSERT INTO user_company_assignments (id, user_id, company_id, is_active, created_at)
        VALUES (?, ?, ?, 1, ?)
        ON DUPLICATE KEY UPDATE is_active = 1
    ");
    
    $stmt->execute([
        Database::generateUuid(),
        $userId,
        $companyId,
        date('Y-m-d H:i:s')
    ]);

    json_success(null, 'تم تخصيص المستخدم للشركة بنجاح');

} catch (\Exception $e) {
    json_error('حدث خطأ أثناء التخصيص: ' . $e->getMessage(), 500);
}
