<?php

namespace OtomaticAi\Utils;

use Exception;
use OtomaticAi\Vendors\Carbon\Carbon;
use OtomaticAi\Vendors\GuzzleHttp\Client;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class GoogleTrends
{
    static public function fetch(Language $language)
    {
        $items = [];

        try {
            $api = new Client([
                "base_uri" => "https://trends.google.com/trending/rss",
                "headers" => [
                    "User-Agent" => "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96",
                ]
            ]);

            $rss = $api->get("", [
                "query" => ["geo" => $language->google_trends],
            ]);
            $rss = $rss->getBody()->getContents();
            $rss = simplexml_load_string($rss);

            $rss = @json_decode(@json_encode($rss), 1);
            $items = Arr::get($rss, "channel.item", []);
            return Arr::map($items, function ($item) {
                return [
                    "title" => Arr::get($item, "title"),
                    "url" => Arr::get($item, "link"),
                    "pub_date" => Carbon::parse(Arr::get($item, "pubDate"))
                        ->setTimezone("UTC")
                        ->format("Y-m-d H:i:s"),
                ];
            });
        } catch (Exception $e) {
        }

        return $items;
    }
}
