<?php

namespace Core;

class Cache
{
    protected static $cacheDir = __DIR__ . '/../../cache/';

    public static function set($key, $data, $ttl = 3600)
    {
        if (!is_dir(self::$cacheDir)) {
            mkdir(self::$cacheDir, 0777, true);
        }
        $content = [
            'expires' => time() + $ttl,
            'data' => $data
        ];
        file_put_contents(self::$cacheDir . md5($key) . '.cache', serialize($content));
    }

    public static function get($key)
    {
        $file = self::$cacheDir . md5($key) . '.cache';
        if (file_exists($file)) {
            $content = unserialize(file_get_contents($file));
            if ($content['expires'] > time()) {
                return $content['data'];
            }
            unlink($file);
        }
        return null;
    }

    public static function delete($key)
    {
        $file = self::$cacheDir . md5($key) . '.cache';
        if (file_exists($file)) {
            unlink($file);
            return true;
        }
        return false;
    }

    public static function clear()
    {
        if (is_dir(self::$cacheDir)) {
            $files = glob(self::$cacheDir . '*.cache');
            foreach ($files as $file) {
                unlink($file);
            }
        }
    }
}
