<?php
declare(strict_types=1);

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

golder_require_method('POST');
$master = golder_master_pdo();

golder_ensure_pairing_schema($master);

golder_apply_default_rate_limit($master, 'api_pair_device_ip', 15, 60);

$input = golder_api_input();
$token = trim((string)($input['pairing_token'] ?? ''));
$pin = trim((string)($input['pin_code'] ?? ''));
$hardwareId = trim((string)($input['hardware_id'] ?? ''));

// GÜNCELLEME: Kullanıcının girdiği ismi önceliklendir. Yoksa Web Tarayıcı yap.
$deviceNameInput = trim((string)($_POST['device_name'] ?? $input['device_name'] ?? ''));
$deviceName = ($deviceNameInput !== '') ? substr($deviceNameInput, 0, 100) : 'Web Tarayıcı';

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

if ($token !== '') {
    $st = $master->prepare("SELECT * FROM device_pairing_requests WHERE pairing_token = ? LIMIT 1");
    $st->execute([$token]);
} elseif ($pin !== '') {
    $st = $master->prepare("SELECT * FROM device_pairing_requests WHERE pin_code = ? AND status = 'pending' LIMIT 1");
    $st->execute([$pin]);
} else {
    golder_json_response(['status' => 'error', 'message' => 'Lutfen QR okutun veya Pin kodu girin.'], 400);
}

$requestRow = $st->fetch();

if (!$requestRow) {
    golder_json_response(['status' => 'error', 'message' => 'Girdiginiz kod gecersiz.'], 404);
}

if ($requestRow['status'] !== 'pending' || strtotime($requestRow['expires_at']) < time()) {
    golder_json_response(['status' => 'error', 'message' => 'Bu kodun suresi dolmus. Lutfen bilgisayardan yeni bir QR olusturun.'], 403);
}

$customerId = (int)$requestRow['customer_id'];
$customer = golder_customer_by_id($master, $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'] ?? 'Web/mobil erisimi kapali.'),
    ], 403);
}

$webSession = golder_open_web_session(
    $master,
    $customer,
    $deviceName,
    golder_client_ip(),
    golder_user_agent(),
    24 * 365,
    $hardwareId
);

if (empty($webSession['ok'])) {
    golder_json_response(['status' => 'error', 'message' => $webSession['message'] ?? 'Oturum olusturulamadi.'], 403);
}

$master->prepare("UPDATE device_pairing_requests SET status = 'paired' WHERE id = ?")->execute([$requestRow['id']]);

golder_json_response([
    'status' => 'ok',
    'session_uuid' => $webSession['session_uuid'],
    'session_token' => $webSession['session_token']
]);


