<?php

namespace App\Repositories;

use Illuminate\Support\Facades\Session;

class RecentlyViewed
{
    /**
     * Add recently viewed record
     *
     * @param string $category
     * @param int $record_id
     * @return void
     */
    public function add(string $category, int $record_id): void
    {
        $records = Session::get("recently-viewed.$category", []);
        if (!in_array($record_id, $records)) {
            array_unshift($records, $record_id);
            Session::put("recently-viewed.$category", $records);
        }
    }

    /**
     * Get recently viewed entries
     *
     * @param string $category
     * @param int|null $exclude
     * @param int $count
     * @return array
     */
    public function get(string $category, ?int $exclude = null, int $count = 4): array
    {
        return collect(Session::get("recently-viewed.$category", []))
            ->filter(fn ($record) => $record !== $exclude)
            ->take($count)
            ->toArray();
    }
}
