<?php

namespace App\Console\Commands;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;

class FetchRemoteScriptsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'remoteScripts:fetch';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch remote scripts';

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        $data = file_get_contents("https://www.google-analytics.com/analytics.js");
        echo "Fetching Analytics...".PHP_EOL;
        echo "File found... ".strlen($data)." bytes".PHP_EOL;
        $path = base_path() . "/core/js/analytics.js";

        if($data !== false){
            echo "Writing file...".PHP_EOL;
            file_put_contents($path, $data);
        }

        echo "Done.".PHP_EOL;

        $client = new Client();
        $res = $client->request('GET', 'https://widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js');
        $path = base_path() . "/core/js/trustpilot.js";
        if(!empty($res->getBody())) {
            echo "Writing file...".PHP_EOL;
            file_put_contents($path, $res->getBody());
        }

        echo "Done.".PHP_EOL;
        return 0;
    }
}
