<?php

namespace OtomaticAi\Utils;

use OtomaticAi\Vendors\Illuminate\Support\Carbon;
use OtomaticAi\Vendors\Illuminate\Support\Collection;

class Cache
{
    public Collection $items;
    static private $instance;

    public function __construct()
    {
        $this->items = new Collection;
    }

    static public function has($key): bool
    {
        // if already fetched
        if (self::instance()->items->has($key)) {
            return true;
        }

        // fetch item from database if exist
        self::instance()->fetchItem($key);

        // final verification
        return self::instance()->items->has($key);
    }

    static public function get($key, $default = null)
    {
        if (self::instance()->has($key)) {
            return self::instance()->items->get($key);
        }

        $item = new CacheItem();
        $item->data = $default;

        return $item;
    }

    static public function store($key, $data)
    {
        if (function_exists('update_option')) {
            $item = new CacheItem();
            $item->data = $data;
            $item->cached_at = Carbon::now();

            update_option($key, $item->toArray(), false);

            self::instance()->items->put($key, $item);
        }
    }

    static public function instance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    static private function fetchItem($key)
    {
        if (function_exists("get_option")) {
            $cached = get_option($key, null);

            if ($cached !== null) {
                self::instance()->items->put($key, CacheItem::make($cached));
            }
        }
    }
}
