<?php

namespace App\Jobs\Tasks;

use Carbon\Carbon;
use Vedmant\FeedReader\Facades\FeedReader;

class BrowseRSSLatestNewsTask
{
    public static function handleMulti($hours = 3)
    {
        $rss_urls = config('platform.global.rss');

        $raw_posts = [];

        foreach ($rss_urls as $rss_url) {
            $this_rss_posts = array_merge(self::handleSingle($rss_url, $hours));

            foreach ($this_rss_posts as $item) {
                $raw_posts[] = $item;
            }
        }

        return $raw_posts;
    }

    public static function handleSingle($rss_url, $hours = 3)
    {
        $blacklist_rss_post_domain = config('platform.global.blacklist_rss_post_domain');
        $blacklist_rss_post_keywords = config('platform.global.blacklist_rss_post_keywords');

        $f = FeedReader::read($rss_url);

        $raw_posts = [];

        foreach ($f->get_items() as $item) {
            $post_datetime = Carbon::parse($item->get_date(\DateTime::ATOM));

            if (! $post_datetime->isBetween(now()->subHours($hours), now())) {
                continue;
            }

            $title = trim($item->get_title());
            $description = trim($item->get_content());

            $domain = get_domain_from_url($item->get_link());

            if (in_array($domain, $blacklist_rss_post_domain)) {
                continue;
            }

            $blacklist_rss_post_keywords = array_merge($blacklist_rss_post_keywords, get_country_names(true));

            foreach ($blacklist_rss_post_keywords as $blacklist_keyword)
            {
              if (str_contains(strtolower($title), $blacklist_keyword))
              {
                continue 2;
              }
            }

            

            $raw_posts[] = (object) [
                'source' => $f->get_title(),
                'source_url' => $rss_url,
                'title' => $title,
                'link' => $item->get_link(),
                'description' => $description,
                'date' => $post_datetime,
                'category' => $item->get_category()?->term,
            ];
        }

        unset($f);

        return $raw_posts;

    }
}
