<?php
declare(strict_types=1);

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

golder_require_method('POST');

$master = golder_master_pdo();
$ctx = golder_require_current_web_customer_session($master);
$input = golder_api_input();

$deviceNameCookie = trim((string)($_COOKIE['golder_web_dev_name'] ?? ''));
if ($deviceNameCookie !== '' && !str_starts_with($deviceNameCookie, 'WEB-')) {
    $deviceId = (int)($ctx['session']['device_id'] ?? 0);
    if ($deviceId > 0) {
        golder_rename_device($master, (int)$ctx['customer_id'], $deviceId, $deviceNameCookie);
    }
}

$sessionId = trim((string)($input['sessionId'] ?? $input['session_id'] ?? ''));
$tabId = trim((string)($input['tabId'] ?? $input['tab_id'] ?? ''));

if ($sessionId === '') {
    golder_json_error(400, 'INVALID_REQUEST', 'sessionId is required.');
}
if (!hash_equals($ctx['session_uuid'], $sessionId)) {
    golder_json_error(403, 'SESSION_MISMATCH', 'Session does not match current login.');
}

$ip = golder_client_ip();
$userAgent = golder_user_agent();
$touched = golder_touch_web_session($master, $ctx['session_uuid'], $tabId, $ip, $userAgent, true);
if (!$touched) {
    golder_clear_web_app_customer_session();
    golder_json_error(401, 'SESSION_EXPIRED', 'Session expired or disconnected.');
}

$sessionRow = golder_validate_web_session($master, $ctx['session_uuid'], $ctx['session_token']);
if (!$sessionRow) {
    golder_clear_web_app_customer_session();
    golder_json_error(401, 'SESSION_EXPIRED', 'Session expired or disconnected.');
}

golder_json_response([
    'status' => 'ok',
    'session' => [
        'id' => $ctx['session_uuid'],
        'last_activity' => (string)($sessionRow['last_activity'] ?? ''),
        'timeout_seconds' => golder_web_session_timeout_seconds(),
        'heartbeat_interval_seconds' => golder_web_session_heartbeat_interval_seconds(),
        'active_tabs' => golder_count_active_web_session_tabs($master, $ctx['session_uuid']),
    ],
]);


