<?php
require_once __DIR__ . '/../utils/Cache.php';
require_once __DIR__ . '/../middleware/AuthMiddleware.php';
require_once __DIR__ . '/../middleware/RoleMiddleware.php';

class CacheController {
    
    public function __construct() {
        // Initialize cache directory
        Cache::init();
    }

    // GET /api/cache/stats - Get cache statistics (Admin only)
    public function getStats() {
        try {
            // Verificar autenticación
            $user = AuthMiddleware::authenticate();
            
            // Solo administradores pueden ver estadísticas de cache
            RoleMiddleware::checkRole(['Administrador']);
            
            $stats = Cache::getStats();
            
            http_response_code(200);
            return json_encode([
                'success' => true,
                'data' => [
                    'cache_files' => $stats['files'],
                    'total_size' => $stats['size'],
                    'size_formatted' => $stats['size_formatted'],
                    'cache_directory' => realpath(__DIR__ . '/../../cache/'),
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);
            
        } catch (Exception $e) {
            error_log("Error en getStats: " . $e->getMessage());
            http_response_code(500);
            return json_encode([
                'success' => false,
                'message' => 'Error al obtener estadísticas de cache'
            ]);
        }
    }

    // DELETE /api/cache/clear - Clear all cache (Admin only)
    public function clearAll() {
        try {
            // Verificar autenticación
            $user = AuthMiddleware::authenticate();
            
            // Solo administradores pueden limpiar cache
            RoleMiddleware::checkRole(['Administrador']);
            
            $cleared = Cache::clear();
            
            if ($cleared) {
                http_response_code(200);
                return json_encode([
                    'success' => true,
                    'message' => 'Cache limpiado exitosamente'
                ]);
            } else {
                http_response_code(500);
                return json_encode([
                    'success' => false,
                    'message' => 'Error al limpiar cache'
                ]);
            }
            
        } catch (Exception $e) {
            error_log("Error en clearAll: " . $e->getMessage());
            http_response_code(500);
            return json_encode([
                'success' => false,
                'message' => 'Error al limpiar cache'
            ]);
        }
    }

    // DELETE /api/cache/cleanup - Cleanup expired cache entries (Admin only)
    public function cleanup() {
        try {
            // Verificar autenticación
            $user = AuthMiddleware::authenticate();
            
            // Solo administradores pueden hacer cleanup
            RoleMiddleware::checkRole(['Administrador']);
            
            $deleted = Cache::cleanup();
            
            http_response_code(200);
            return json_encode([
                'success' => true,
                'message' => 'Cleanup de cache completado',
                'data' => [
                    'expired_entries_deleted' => $deleted
                ]
            ]);
            
        } catch (Exception $e) {
            error_log("Error en cleanup: " . $e->getMessage());
            http_response_code(500);
            return json_encode([
                'success' => false,
                'message' => 'Error en cleanup de cache'
            ]);
        }
    }

    // DELETE /api/cache/invalidate/{tag} - Invalidate cache by tag (Admin only)
    public function invalidateTag($tag) {
        try {
            // Verificar autenticación
            $user = AuthMiddleware::authenticate();
            
            // Solo administradores pueden invalidar cache por tags
            RoleMiddleware::checkRole(['Administrador']);
            
            if (empty($tag)) {
                http_response_code(400);
                return json_encode([
                    'success' => false,
                    'message' => 'Tag requerido para invalidación'
                ]);
            }
            
            $deleted = Cache::invalidateTag($tag);
            
            http_response_code(200);
            return json_encode([
                'success' => true,
                'message' => "Cache invalidado para tag: $tag",
                'data' => [
                    'entries_deleted' => $deleted
                ]
            ]);
            
        } catch (Exception $e) {
            error_log("Error en invalidateTag: " . $e->getMessage());
            http_response_code(500);
            return json_encode([
                'success' => false,
                'message' => 'Error al invalidar cache por tag'
            ]);
        }
    }

    // POST /api/cache/warm - Warm up cache with frequent queries (Admin only)
    public function warmUp() {
        try {
            // Verificar autenticación
            $user = AuthMiddleware::authenticate();
            
            // Solo administradores pueden hacer warm up
            RoleMiddleware::checkRole(['Administrador']);
            
            $warmedQueries = 0;
            
            // Warm up species cache
            require_once __DIR__ . '/SpeciesController.php';
            $speciesController = new SpeciesController(Database::getConnection());
            $speciesController->getAll();
            $speciesController->getRecommended();
            $warmedQueries += 2;
            
            // Warm up project lists for active users
            require_once __DIR__ . '/ProjectController.php';
            $projectController = new ProjectController(Database::getConnection());
            
            // Get active users to warm their project caches
            $query = "SELECT id, rol FROM usuarios WHERE activo = 1 AND rol IN ('Administrador', 'Regente')";
            $stmt = Database::getConnection()->prepare($query);
            $stmt->execute();
            
            while ($userRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
                // Simulate user context for cache warming
                $_SESSION['user'] = [
                    'user_id' => $userRow['id'],
                    'rol' => $userRow['rol']
                ];
                
                try {
                    $projectController->index();
                    $warmedQueries++;
                } catch (Exception $e) {
                    // Continue warming other caches even if one fails
                    error_log("Error warming project cache for user {$userRow['id']}: " . $e->getMessage());
                }
            }
            
            // Clean up session
            unset($_SESSION['user']);
            
            http_response_code(200);
            return json_encode([
                'success' => true,
                'message' => 'Cache warm up completado',
                'data' => [
                    'queries_warmed' => $warmedQueries
                ]
            ]);
            
        } catch (Exception $e) {
            error_log("Error en warmUp: " . $e->getMessage());
            http_response_code(500);
            return json_encode([
                'success' => false,
                'message' => 'Error en warm up de cache'
            ]);
        }
    }
}
?>