<?php
// Diagnóstico rápido — acesse via browser: localhost:8000/diag-cache.php
// REMOVER APÓS USO
header('Content-Type: text/plain; charset=utf-8');

// Qual caminho o Cache usa quando chamado pelo Apache?
$cacheClass = dirname(__DIR__) . '/app/Core/Cache.php';
require_once $cacheClass;

// Verifica o auto-init path
$reflection = new ReflectionClass('App\Core\Cache');
$dirProp = $reflection->getProperty('dir');
$dirProp->setAccessible(true);
$currentDir = $dirProp->getValue();

echo "=== DIAGNÓSTICO DE CACHE ===\n\n";
echo "PHP __DIR__ (desta pasta public): " . __DIR__ . "\n";
echo "dirname(__DIR__, 2) desde app/Core: " . dirname(dirname(__DIR__) . '/app/Core') . "\n";

// Simula o auto-init
$autoDir = dirname(dirname(__DIR__) . '/app/Core', 2) . '/storage/cache';
// Actually: __DIR__ no Cache.php = APP_ROOT/app/Core, então dirname 2x up = APP_ROOT
$cacheAutoDir = dirname(__DIR__) . '/app/Core';
$cacheAutoDir2 = dirname($cacheAutoDir, 2) . '/storage/cache'; // correto

echo "Cache auto-dir (simulado): " . $cacheAutoDir2 . "\n";
echo "Cache dir atual (estático): '" . $currentDir . "'\n\n";

// Verifica os arquivos de cache em cada caminho possível
$paths = [
    'C:\BI\storage\cache',
    'C:\Program Files\Premium Express Gestão\storage\cache',
    dirname(__DIR__) . '\storage\cache',
    $cacheAutoDir2,
];

foreach (array_unique($paths) as $path) {
    $files = glob($path . '/*.json') ?: [];
    $exists = is_dir($path);
    echo "PATH: {$path}\n";
    echo "  dir_exists: " . ($exists ? 'YES' : 'NO') . "\n";
    echo "  json_files: " . count($files) . "\n";
    if ($files) {
        $newest = max(array_map('filemtime', $files));
        echo "  newest: " . date('H:i:s', $newest) . " (" . round((time()-$newest)/60) . " min atrás)\n";
        // Check if a sample file is valid (not expired)
        $sample = json_decode(file_get_contents($files[0]), true);
        $exp = $sample['expires'] ?? 0;
        echo "  sample_expires: " . date('H:i:s', $exp) . " (" . ($exp > time() ? 'VÁLIDO' : 'EXPIRADO') . ")\n";
    }
    echo "\n";
}

// Test actually reading a cache key
\App\Core\Cache::init($cacheAutoDir2);
$testKey = 'dash_ultima_data_5';
$val = \App\Core\Cache::get($testKey);
echo "Cache read test (dash_ultima_data_5): " . ($val !== null ? "HIT = " . json_encode($val) : "MISS") . "\n";
