<?php

namespace App\View\Components\Guest;

use Closure;
use Exception;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;

class Skm extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        $data = [];
        $url = env('SPLP_URL');
        try {
            $response = Http::throw()->connectTimeout(3)->timeout(3)->withHeaders(['apikey' => env('SPLP_API_KEY')])->get($url);
            if ($response->successful()) {
                $res = json_decode($response->body())->results;
                $data = Cache::remember('skm', 60 * 60 * 24, function () use ($res) {
                    return $res ?? [];
                });
            } else {
               throw new Exception('Gagal ambil data');
            }
        } catch (RequestException $th) {
            $data = [];
        }catch (Throwable $th) {
            $data = [];
        }
        return view('components.guest.skm', compact('data'));
    }
}
