<?php
class Cache {
    private $cacheDir;
    private $ttl;
    
    public function __construct($ttl = 300) { // 5 minutos padrão
        $this->cacheDir = __DIR__ . '/../cache/';
        $this->ttl = $ttl;
        if (!is_dir($this->cacheDir)) mkdir($this->cacheDir, 0755, true);
    }
    
    public function get($key) {
        $file = $this->cacheDir . md5($key) . '.cache';
        if (file_exists($file) && (time() - filemtime($file)) < $this->ttl) {
            return unserialize(file_get_contents($file));
        }
        return null;
    }
    
    public function set($key, $data) {
        $file = $this->cacheDir . md5($key) . '.cache';
        file_put_contents($file, serialize($data));
    }
    
    public function clear($pattern = null) {
        $files = glob($this->cacheDir . ($pattern ? md5($pattern) . '*': '*') . '.cache');
        foreach ($files as $file) unlink($file);
    }
}

// Uso no dashboard:
$cache = new Cache(300); // 5 minutos
$dashboardData = $cache->get('dashboard_metrics');
if (!$dashboardData) {
    // Buscar do banco
    $stmt = $pdo->query("SELECT * FROM vw_dashboard_metrics");
    $dashboardData = $stmt->fetch(PDO::FETCH_ASSOC);
    $cache->set('dashboard_metrics', $dashboardData);
}