<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class HybridTopRssPostKeywords extends Model
{
    // Disable timestamps as this is not a table model
    public $timestamps = false;

    // Define fillable attributes
    protected $fillable = ['value', 'value_lowercased', 'value_count'];

    // Override the table and primary key as this is an abstract model
    protected $table = null;

    protected $primaryKey = null;

    // Disable incrementing as this is an abstract model
    public $incrementing = false;

    // Static method to get top keywords
    public static function get($days = 1, $limit = 10)
    {

        return Cache::remember('top_rss_post_keywords_by_day_'.$days.'_'.$limit, 180, function () use ($days, $limit) {

            $queryResults = DB::table('rss_post_keywords')
                ->select('value', 'value_lowercased', DB::raw('COUNT(value_lowercased) as value_count'))
                ->where('created_at', '>=', now()->subDays($days))
                ->whereNotIn('value_lowercased', ['techcrunch', 'the verge', 'forbes', 'producthunt', 'vox media','engadget'])
                ->groupBy('value', 'value_lowercased')
                ->orderBy(DB::raw('COUNT(value_lowercased)'), 'desc')
                ->limit($limit)
                ->get();

            return self::hydrate($queryResults->toArray());

        });
    }
}
