<?php
namespace App\Models;

class HistoryModel extends BaseModel
{
    public function add(int $keyId, int $userId, string $info): void
    {
        $stmt = $this->db->prepare('INSERT INTO history (key_id, user_id, info, created_at) VALUES (?, ?, ?, NOW())');
        $stmt->execute([$keyId, $userId, $info]);
    }

    public function listLatest(int $limit = 20): array
    {
        $stmt = $this->db->prepare('SELECT h.*, u.username, k.user_key FROM history h INNER JOIN keys_code k ON k.id = h.key_id LEFT JOIN users u ON u.id = h.user_id ORDER BY h.id DESC LIMIT ?');
        $stmt->bindValue(1, $limit, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function listLatestForUser(int $userId, int $limit = 20): array
    {
        $stmt = $this->db->prepare('SELECT h.*, u.username, k.user_key FROM history h INNER JOIN keys_code k ON k.id = h.key_id LEFT JOIN users u ON u.id = h.user_id WHERE h.user_id = ? ORDER BY h.id DESC LIMIT ?');
        $stmt->bindValue(1, $userId, \PDO::PARAM_INT);
        $stmt->bindValue(2, $limit, \PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
