<?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');
$master = $ctx['master'];
$customerId = $ctx['customer_id'];

golder_ensure_pairing_schema($master);

$customer = golder_customer_by_id($master, (int)$customerId);
if (!$customer) {
    golder_json_response(['status' => 'error', 'message' => 'Musteri hesabi bulunamadi.'], 404);
}

$failure = golder_customer_web_access_failure($customer);
if (is_array($failure)) {
    golder_json_response([
        'status' => 'error',
        'code' => (string)($failure['code'] ?? 'WEB_ACCESS_DISABLED'),
        'message' => (string)($failure['message'] ?? 'Bu hesap icin web cihaz ekleme yetkisi kapali.'),
    ], 403);
}
$effectivePlan = golder_customer_effective_plan($customer);
$maxWebAllowed = (int)($effectivePlan['max_web_sessions'] ?? 0);

$activeDeviceCount = golder_count_active_web_devices($master, (int)$customerId);
if ($activeDeviceCount >= $maxWebAllowed) {
    golder_json_response([
        'status' => 'error',
        'message' => sprintf(
            'Web cihaz siniriniz dolu (%d / %d). Yeni cihaz eklemek icin once bir cihaz silin.',
            $activeDeviceCount,
            $maxWebAllowed
        ),
    ], 403);
}

$master->exec("DELETE FROM device_pairing_requests WHERE expires_at < UTC_TIMESTAMP()");

$token = bin2hex(random_bytes(32));
$pin = sprintf('%06d', random_int(0, 999999));
$expires = gmdate('Y-m-d H:i:s', time() + 180);

$st = $master->prepare(
    "INSERT INTO device_pairing_requests (customer_id, pairing_token, pin_code, expires_at) 
     VALUES (?, ?, ?, ?)"
);
$st->execute([$customerId, $token, $pin, $expires]);

golder_json_response([
    'status' => 'ok',
    'pairing_token' => $token,
    'pin_code' => $pin,
    'expires_at' => $expires
]);


