<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_bootstrap.php';
require_once dirname(__DIR__, 2) . '/common/session_store.php';

golder_require_method('POST');
$ctx = golder_api_auth('desktop_sync');
$input = golder_api_input();

$tokenRow = is_array($ctx['token'] ?? null) ? $ctx['token'] : [];
$metadataRaw = $tokenRow['metadata_json'] ?? null;
$metadata = [];
if (is_string($metadataRaw) && trim($metadataRaw) !== '') {
    $decoded = json_decode($metadataRaw, true);
    if (is_array($decoded)) {
        $metadata = $decoded;
    }
}

$hardwareId = substr(trim((string)($input['hardware_id'] ?? ($metadata['hardware_id'] ?? ''))), 0, 120);
if ($hardwareId === '') {
    golder_json_response([
        'status' => 'error',
        'message' => 'Bu masaustu oturumu icin hardware_id bulunamadi.',
    ], 400);
}

$customer = is_array($ctx['customer'] ?? null) ? $ctx['customer'] : [];
$maxPcDevices = max(1, (int)(golder_customer_effective_plan($customer)['max_pc_devices'] ?? 1));
$revokedTokens = golder_revoke_desktop_tokens_by_device_uid(
    $ctx['master'],
    (int)$ctx['customer_id'],
    $hardwareId
);
$remainingPcSlots = max(0, $maxPcDevices - golder_count_active_desktop_devices($ctx['master'], (int)$ctx['customer_id']));

golder_json_response([
    'status' => 'ok',
    'revoked_tokens' => $revokedTokens,
    'remaining_pc_slots' => $remainingPcSlots,
    'max_pc_devices' => $maxPcDevices,
]);


