<?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'];

$input = golder_api_input();
$token = trim((string)($input['pairing_token'] ?? ''));

if ($token === '') {
    golder_json_response(['status' => 'error', 'message' => 'Token is required'], 400);
}

$st = $master->prepare(
    "SELECT status, expires_at FROM device_pairing_requests WHERE customer_id = ? AND pairing_token = ? LIMIT 1"
);
$st->execute([$ctx['customer_id'], $token]);
$row = $st->fetch();

if (!$row) {
    golder_json_response(['status' => 'error', 'message' => 'Token not found'], 404);
}

if ($row['status'] === 'pending' && strtotime($row['expires_at']) < time()) {
    $master->prepare("UPDATE device_pairing_requests SET status = 'expired' WHERE pairing_token = ?")->execute([$token]);
    $row['status'] = 'expired';
}

golder_json_response([
    'status' => 'ok',
    'pairing_status' => $row['status']
]);


