<?php
declare(strict_types=1);

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

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

// Authenticate
$currentUser = require_auth($pdo);

// Super admin only
if ($currentUser['role'] !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

// Read JSON input
$data = json_decode(file_get_contents('php://input'), true);

$userId    = (int)($data['user_id'] ?? 0);
$companyId = (int)($data['company_id'] ?? 0);

if ($userId <= 0 || $companyId <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid user_id or company_id']);
    exit;
}

// Ensure company exists
$checkCompany = $pdo->prepare("SELECT id FROM companies WHERE id = ?");
$checkCompany->execute([$companyId]);
if (!$checkCompany->fetch()) {
    http_response_code(404);
    echo json_encode(['error' => 'Company not found']);
    exit;
}

// Ensure user exists
$checkUser = $pdo->prepare("SELECT id FROM users WHERE id = ?");
$checkUser->execute([$userId]);
if (!$checkUser->fetch()) {
    http_response_code(404);
    echo json_encode(['error' => 'User not found']);
    exit;
}

// Assign user to company + admin role
$stmt = $pdo->prepare("
    UPDATE users
    SET company_id = :company_id,
        role = 'admin'
    WHERE id = :user_id
");
$stmt->execute([
    'company_id' => $companyId,
    'user_id'    => $userId
]);

// Audit log
audit_log(
    $pdo,
    (int)$currentUser['id'],
    $companyId,
    'assign_company_admin',
    $userId,
    ['company_id' => $companyId]
);

echo json_encode([
    'status' => 'success',
    'assigned_user_id' => $userId,
    'company_id' => $companyId
]);
