<?php
/**
 * Script de Limpieza de Cache
 * Sistema de Inventario Forestal de Guatemala
 * 
 * Este script limpia el cache del sistema para optimizar el rendimiento
 */

require_once __DIR__ . '/../api/config/environment.php';

class CacheCleanup {
    private $cacheDir;
    private $cacheTTL;
    
    public function __construct() {
        $this->cacheDir = __DIR__ . '/../cache/';
        $this->cacheTTL = Environment::get('CACHE_TTL', 3600); // 1 hora por defecto
        
        // Crear directorio de cache si no existe
        if (!is_dir($this->cacheDir)) {
            mkdir($this->cacheDir, 0755, true);
        }
    }
    
    /**
     * Limpiar cache completo
     */
    public function clearAll() {
        $results = [
            'timestamp' => date('Y-m-d H:i:s'),
            'action' => 'clear_all',
            'files_deleted' => 0,
            'space_freed' => 0,
            'errors' => []
        ];
        
        $files = glob($this->cacheDir . '*');
        
        foreach ($files as $file) {
            if (is_file($file)) {
                $size = filesize($file);
                if (unlink($file)) {
                    $results['files_deleted']++;
                    $results['space_freed'] += $size;
                } else {
                    $results['errors'][] = 'No se pudo eliminar: ' . basename($file);
                }
            }
        }
        
        return $results;
    }
    
    /**
     * Limpiar cache expirado
     */
    public function clearExpired() {
        $results = [
            'timestamp' => date('Y-m-d H:i:s'),
            'action' => 'clear_expired',
            'files_deleted' => 0,
            'space_freed' => 0,
            'errors' => []
        ];
        
        $files = glob($this->cacheDir . '*');
        $cutoffTime = time() - $this->cacheTTL;
        
        foreach ($files as $file) {
            if (is_file($file) && filemtime($file) < $cutoffTime) {
                $size = filesize($file);
                if (unlink($file)) {
                    $results['files_deleted']++;
                    $results['space_freed'] += $size;
                } else {
                    $results['errors'][] = 'No se pudo eliminar: ' . basename($file);
                }
            }
        }
        
        return $results;
    }
    
    /**
     * Obtener estadísticas de cache
     */
    public function getStats() {
        $stats = [
            'total_files' => 0,
            'total_size' => 0,
            'expired_files' => 0,
            'expired_size' => 0,
            'by_type' => []
        ];
        
        $files = glob($this->cacheDir . '*');
        $cutoffTime = time() - $this->cacheTTL;
        
        foreach ($files as $file) {
            if (is_file($file)) {
                $size = filesize($file);
                $stats['total_files']++;
                $stats['total_size'] += $size;
                
                // Verificar si está expirado
                if (filemtime($file) < $cutoffTime) {
                    $stats['expired_files']++;
                    $stats['expired_size'] += $size;
                }
                
                // Agrupar por tipo
                $type = $this->getCacheType($file);
                if (!isset($stats['by_type'][$type])) {
                    $stats['by_type'][$type] = ['count' => 0, 'size' => 0];
                }
                $stats['by_type'][$type]['count']++;
                $stats['by_type'][$type]['size'] += $size;
            }
        }
        
        // Formatear tamaños
        $stats['total_size_formatted'] = $this->formatBytes($stats['total_size']);
        $stats['expired_size_formatted'] = $this->formatBytes($stats['expired_size']);
        
        foreach ($stats['by_type'] as &$type) {
            $type['size_formatted'] = $this->formatBytes($type['size']);
        }
        
        return $stats;
    }
    
    /**
     * Determinar tipo de cache basado en el nombre del archivo
     */
    private function getCacheType($file) {
        $basename = basename($file);
        
        if (strpos($basename, 'api_') === 0) {
            return 'api';
        } elseif (strpos($basename, 'query_') === 0) {
            return 'database';
        } elseif (strpos($basename, 'species_') === 0) {
            return 'species';
        } elseif (strpos($basename, 'report_') === 0) {
            return 'reports';
        } elseif (strpos($basename, 'calc_') === 0) {
            return 'calculations';
        } else {
            return 'other';
        }
    }
    
    /**
     * Formatear bytes a formato legible
     */
    private function formatBytes($bytes, $precision = 2) {
        $units = array('B', 'KB', 'MB', 'GB', 'TB');
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, $precision) . ' ' . $units[$i];
    }
}

// Ejecutar limpieza si se llama directamente
if (php_sapi_name() === 'cli' || (isset($_GET['action']) && $_GET['action'] === 'cache')) {
    $cache = new CacheCleanup();
    
    $action = $_GET['type'] ?? 'expired';
    
    if ($action === 'stats') {
        $stats = $cache->getStats();
        
        if (php_sapi_name() === 'cli') {
            echo "=== CACHE STATISTICS ===\n";
            echo "Total archivos: " . $stats['total_files'] . "\n";
            echo "Tamaño total: " . $stats['total_size_formatted'] . "\n";
            echo "Archivos expirados: " . $stats['expired_files'] . "\n";
            echo "Tamaño expirado: " . $stats['expired_size_formatted'] . "\n";
            
            echo "\nPor tipo:\n";
            foreach ($stats['by_type'] as $type => $data) {
                echo "  {$type}: {$data['count']} archivos, {$data['size_formatted']}\n";
            }
            
            echo "========================\n";
        } else {
            header('Content-Type: application/json');
            echo json_encode($stats, JSON_PRETTY_PRINT);
        }
    } else {
        if ($action === 'all') {
            $results = $cache->clearAll();
        } else {
            $results = $cache->clearExpired();
        }
        
        if (php_sapi_name() === 'cli') {
            echo "=== CACHE CLEANUP REPORT ===\n";
            echo "Fecha: " . $results['timestamp'] . "\n";
            echo "Acción: " . $results['action'] . "\n";
            echo "Archivos eliminados: " . $results['files_deleted'] . "\n";
            echo "Espacio liberado: " . number_format($results['space_freed'] / 1024, 2) . " KB\n";
            
            if (!empty($results['errors'])) {
                echo "\nErrores:\n";
                foreach ($results['errors'] as $error) {
                    echo "  - {$error}\n";
                }
            }
            
            echo "============================\n";
        } else {
            header('Content-Type: application/json');
            echo json_encode($results, JSON_PRETTY_PRINT);
        }
    }
}
?>