<?php

namespace App\Models;

use App\Core\Database;

/**
 * Per-user "seen" state for the KPI notification chips in the workspace header.
 *
 * The chips are derived live from KPI state, so they had no read/unread
 * concept and persisted after being opened. This records which chip a user
 * has already clicked through, so it can be hidden afterwards.
 *
 * Every key carries a version component (a timestamp or a message id).
 * Dismissing "the review on record 6 as it stood at 20:08" does not dismiss
 * a *newer* comment on record 6 — that produces a different key, so the chip
 * correctly reappears. Nothing is ever permanently suppressed.
 *
 * All methods fail soft: if the table is missing (migration not yet run),
 * nothing is marked seen and every chip simply behaves as it did before.
 */
class KpiNotifSeen
{
    /** Mark one chip key as seen for this user. Idempotent. */
    public static function markSeen(string $userType, int $userId, string $key): void
    {
        $key = trim($key);
        if ($key === '') return;
        try {
            Database::connection()->prepare(
                "INSERT IGNORE INTO kpi_notif_seen (user_type, user_id, notif_key)
                 VALUES (:t, :u, :k)"
            )->execute(['t' => $userType, 'u' => $userId, 'k' => mb_substr($key, 0, 190)]);
        } catch (\Throwable $e) {
            // Table not present yet — chips keep their previous behaviour.
        }
    }

    /** All chip keys this user has already seen. */
    public static function seenKeys(string $userType, int $userId): array
    {
        try {
            $stmt = Database::connection()->prepare(
                "SELECT notif_key FROM kpi_notif_seen WHERE user_type = :t AND user_id = :u"
            );
            $stmt->execute(['t' => $userType, 'u' => $userId]);
            return array_flip($stmt->fetchAll(\PDO::FETCH_COLUMN));
        } catch (\Throwable $e) {
            return [];
        }
    }

    /** Has this user already seen this exact chip version? */
    public static function isSeen(array $seenKeys, string $key): bool
    {
        return $key !== '' && isset($seenKeys[$key]);
    }
}
