<?php

namespace App\Core;

use PDO;
use Throwable;

final class UserSessionTracker
{
    public static function touch(PDO $db, int $userId, int $tenantId): void
    {
        if ($userId <= 0) {
            return;
        }
        try {
            $db->query('SELECT id FROM user_session_log LIMIT 1');
        } catch (Throwable $e) {
            return;
        }
        $sid = session_id();
        if ($sid === '') {
            return;
        }
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        $ua = mb_substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500);
        try {
            $st = $db->prepare('SELECT id FROM user_session_log WHERE user_id = ? AND session_id = ? LIMIT 1');
            $st->execute([$userId, $sid]);
            $row = $st->fetch();
            if ($row) {
                $db->prepare('UPDATE user_session_log SET last_seen_at = NOW(), ip_address = ?, user_agent = ? WHERE id = ?')
                    ->execute([$ip, $ua, (int)$row['id']]);
            } else {
                $db->prepare('INSERT INTO user_session_log (user_id, tenant_id, session_id, ip_address, user_agent, last_seen_at) VALUES (?,?,?,?,?,NOW())')
                    ->execute([$userId, $tenantId, $sid, $ip, $ua]);
            }
        } catch (Throwable $e) {
        }
    }
}
