<?php
defined('ABSPATH') or die('Direct access not allowed');

class CodeEditor_PreviewController {
    public function __construct() {
        add_action('wp_ajax_code_editor_preview_plugin', [$this, 'handle_plugin_preview']);
        add_action('wp_ajax_code_editor_preview_theme', [$this, 'handle_theme_preview']);
        add_action('wp_ajax_code_editor_clean_preview', [$this, 'handle_clean_preview']);
        register_shutdown_function([$this, 'cleanup_temp_files']);
    }

    public function handle_plugin_preview() {
        check_ajax_referer('code_editor_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $plugin_slug = isset($_POST['plugin_slug']) ? sanitize_text_field($_POST['plugin_slug']) : '';
        $plugin_content = isset($_POST['plugin_content']) ? $_POST['plugin_content'] : '';
        
        try {
            $temp_dir = $this->create_temp_plugin($plugin_slug, $plugin_content);
            $this->activate_temp_plugin($plugin_slug);
            
            wp_send_json_success([
                'message' => '插件预览已激活',
                'preview_url' => home_url()
            ]);
        } catch (Exception $e) {
            wp_send_json_error('插件预览失败: ' . $e->getMessage(), 500);
        }
    }

    public function handle_theme_preview() {
        check_ajax_referer('code_editor_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $theme_slug = isset($_POST['theme_slug']) ? sanitize_text_field($_POST['theme_slug']) : '';
        $theme_content = isset($_POST['theme_content']) ? $_POST['theme_content'] : '';
        
        try {
            $temp_dir = $this->create_temp_theme($theme_slug, $theme_content);
            switch_theme($theme_slug);
            
            wp_send_json_success([
                'message' => '主题预览已激活',
                'preview_url' => home_url()
            ]);
        } catch (Exception $e) {
            wp_send_json_error('主题预览失败: ' . $e->getMessage(), 500);
        }
    }

    private function create_temp_plugin($slug, $content) {
        $temp_dir = WP_CONTENT_DIR . '/temp-plugins/' . $slug;
        
        if (!file_exists($temp_dir)) {
            wp_mkdir_p($temp_dir);
        }
        
        $main_file = $temp_dir . '/' . $slug . '.php';
        file_put_contents($main_file, $content);
        
        return $temp_dir;
    }

    private function create_temp_theme($slug, $content) {
        $temp_dir = get_theme_root() . '/temp-' . $slug;
        
        if (!file_exists($temp_dir)) {
            wp_mkdir_p($temp_dir);
        }
        
        $style_css = $temp_dir . '/style.css';
        file_put_contents($style_css, $content);
        
        return $temp_dir;
    }

    private function activate_temp_plugin($slug) {
        if (!is_plugin_active($slug . '/' . $slug . '.php')) {
            activate_plugin($slug . '/' . $slug . '.php');
        }
    }

    public function handle_clean_preview() {
        check_ajax_referer('code_editor_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $type = isset($_POST['type']) ? sanitize_text_field($_POST['type']) : '';
        $slug = isset($_POST['slug']) ? sanitize_text_field($_POST['slug']) : '';
        
        try {
            if ($type === 'plugin') {
                $this->cleanup_temp_plugin($slug);
            } elseif ($type === 'theme') {
                $this->cleanup_temp_theme($slug);
            }
            
            wp_send_json_success(['message' => '预览已清理']);
        } catch (Exception $e) {
            wp_send_json_error('清理失败: ' . $e->getMessage(), 500);
        }
    }

    private function cleanup_temp_plugin($slug) {
        $temp_dir = WP_CONTENT_DIR . '/temp-plugins/' . $slug;
        if (file_exists($temp_dir)) {
            $this->rrmdir($temp_dir);
        }
    }

    private function cleanup_temp_theme($slug) {
        $temp_dir = get_theme_root() . '/temp-' . $slug;
        if (file_exists($temp_dir)) {
            $this->rrmdir($temp_dir);
        }
    }

    public function cleanup_temp_files() {
        // 清理所有临时插件
        $plugins_dir = WP_CONTENT_DIR . '/temp-plugins/';
        if (file_exists($plugins_dir)) {
            $this->rrmdir($plugins_dir);
        }
        
        // 清理所有临时主题
        $themes_dir = get_theme_root();
        if ($handle = opendir($themes_dir)) {
            while (false !== ($entry = readdir($handle))) {
                if (strpos($entry, 'temp-') === 0) {
                    $this->rrmdir($themes_dir . '/' . $entry);
                }
            }
            closedir($handle);
        }
    }

    private function rrmdir($dir) {
        if (!file_exists($dir)) {
            return;
        }
        
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file) {
            $path = $dir . '/' . $file;
            is_dir($path) ? $this->rrmdir($path) : unlink($path);
        }
        
        rmdir($dir);
    }
}

new CodeEditor_PreviewController();