<?php
declare(strict_types=1);

require_once __DIR__ . '/admin_bootstrap.php';

$pdo = admin_get_pdo();
$auth = admin_require_auth($pdo);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'POST') {
    // szybki ping "piszę"; bez payloadu
    try {
        $stmt = $pdo->prepare(
            'INSERT INTO admin_chat_typing (user_id, username, updated_at) '
            . 'VALUES (:user_id, :username, CURRENT_TIMESTAMP) '
            . 'ON DUPLICATE KEY UPDATE username = VALUES(username), updated_at = CURRENT_TIMESTAMP'
        );
        $stmt->execute([
            ':user_id' => (int)$auth['user_id'],
            ':username' => (string)$auth['username'],
        ]);

        admin_json_response(['success' => true]);
    } catch (Throwable $e) {
        admin_json_error('Błąd zapisu typing', 500);
    }
}

if ($method === 'GET') {
    // Kto pisze w ostatnich 6 sekundach
    $ttlSeconds = 6;

    try {
        $stmt = $pdo->prepare(
            'SELECT user_id, username, updated_at, UNIX_TIMESTAMP(updated_at) AS updated_at_ts '
            . 'FROM admin_chat_typing '
            . 'WHERE updated_at >= (CURRENT_TIMESTAMP - INTERVAL :ttl SECOND)'
        );
        $stmt->bindValue(':ttl', $ttlSeconds, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Odfiltruj siebie
        $meId = (int)$auth['user_id'];
        $filtered = [];
        foreach ($rows as $r) {
            if ((int)($r['user_id'] ?? 0) === $meId) {
                continue;
            }
            $filtered[] = $r;
        }

        admin_json_response([
            'success' => true,
            'data' => $filtered,
            'count' => count($filtered),
            'ttlSeconds' => $ttlSeconds,
        ]);
    } catch (Throwable $e) {
        admin_json_error('Błąd pobierania typing', 500);
    }
}

admin_json_error('Metoda niedozwolona', 405);
