<?php
namespace IntentDeep\VirtualFiles\Bootstrap;

use IntentDeep\VirtualFiles\Core\Option;

class PluginManager {
    private string $pluginSlug;
    private const ERROR_PREFIX = 'Virtual Files';

    private const DEFAULT_OPTIONS = [
        'routing_enabled' => true,
        'allowed_extensions' => ['txt', 'md', 'json'],
        'remove_settings_on_uninstall' => false,
    ];

    private const PRO_OPTIONS = [
        'max_files_pro' => -1, // unlimited
        'extended_extensions' => ['xml', 'rss', 'csv', 'yml', 'yaml', 'log'],
        'advanced_editor' => true,
        'cache_enabled' => true, // Enable caching by default for Pro users
        'cache_expiration' => 3600, // 1 hour default
        'analytics_enabled' => true,
    ];

    public function __construct(string $pluginSlug) {
        $this->pluginSlug = $pluginSlug;
    }

    public function init(): void {
        try {
            $this->registerHooks();
        } catch (\Exception $e) {
            intentdeep_vf_log(sprintf("%s Plugin Error: %s", self::ERROR_PREFIX, $e->getMessage()));
        }
    }

    private function registerHooks(): void {
        // WordPress 4.6+ automatically loads textdomains for wp.org hosted plugins
        // No need to manually call load_plugin_textdomain()
    }

    public function activate(): void {
        try {
            // Register the custom post type
            $this->registerVirtualFileCPT();

            // Initialize default options
            $options = get_option('intentdeep_vf_settings');

            if (!is_array($options)) {
                $defaultOptions = self::DEFAULT_OPTIONS;

                // Only add pro options if Freemius is available
                if (function_exists('intentdeep_vf_fs') && intentdeep_vf_fs()->can_use_premium_code__premium_only()) {
                    $defaultOptions = array_merge($defaultOptions, self::PRO_OPTIONS);
                }

                update_option('intentdeep_vf_settings', $defaultOptions);
            }

            // Register virtual file rewrite rules BEFORE flushing
            $this->registerVirtualFileRewriteRules();

            // Flush rewrite rules for virtual file routing
            flush_rewrite_rules();
        } catch (\Exception $e) {
            intentdeep_vf_log(sprintf("%s Activation Error: %s", self::ERROR_PREFIX, $e->getMessage()));
        }
    }
    
    public function deactivate(): void {
        try {
            if (Option::check('remove_settings_on_uninstall')) {
                $this->cleanupPluginData();
            }

            // Flush rewrite rules to remove virtual file routes
            flush_rewrite_rules();
        } catch (\Exception $e) {
            intentdeep_vf_log(sprintf("%s Deactivation Error: %s", self::ERROR_PREFIX, $e->getMessage()));
        }
    }

    private function registerVirtualFileCPT(): void {
        register_post_type('idep_virtual_file', array(
            'labels' => array(
                'name' => __('Virtual Files', 'intentdeep-virtual-files'),
                'singular_name' => __('Virtual File', 'intentdeep-virtual-files'),
                'menu_name' => __('Virtual Files', 'intentdeep-virtual-files'),
                'add_new' => __('Add New File', 'intentdeep-virtual-files'),
                'add_new_item' => __('Add New Virtual File', 'intentdeep-virtual-files'),
                'edit_item' => __('Edit Virtual File', 'intentdeep-virtual-files'),
                'new_item' => __('New Virtual File', 'intentdeep-virtual-files'),
                'view_item' => __('View Virtual File', 'intentdeep-virtual-files'),
                'search_items' => __('Search Virtual Files', 'intentdeep-virtual-files'),
                'not_found' => __('No virtual files found', 'intentdeep-virtual-files'),
                'not_found_in_trash' => __('No virtual files found in trash', 'intentdeep-virtual-files'),
            ),
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => true,
            'menu_icon' => 'dashicons-text-page',
            'capability_type' => 'post',
            'hierarchical' => false,
            'supports' => array('title'),
            'has_archive' => false,
            'rewrite' => false,
            'publicly_queryable' => false,
        ));
    }

    /**
     * Register virtual file rewrite rules during activation
     */
    private function registerVirtualFileRewriteRules(): void {
        // Check if routing is enabled
        $settings = get_option('intentdeep_vf_settings', []);
        if (empty($settings['routing_enabled'])) {
            return;
        }

        // Get all active virtual files
        $virtual_files = get_posts([
            'post_type' => 'idep_virtual_file',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'meta_query' => [
                [
                    'key' => '_vf_status',
                    'value' => 'active',
                    'compare' => '='
                ],
                [
                    'key' => '_vf_filename',
                    'value' => '',
                    'compare' => '!='
                ]
            ]
        ]);

        $registered_filenames = [];

        foreach ($virtual_files as $file) {
            $filename = get_post_meta($file->ID, '_vf_filename', true);

            if (!empty($filename) && !in_array($filename, $registered_filenames)) {
                // Register rewrite rule for exact filename without trailing slash
                add_rewrite_rule(
                    '^' . preg_quote($filename, '/') . '$',
                    'index.php?idep_virtual_file=1&file_id=' . intval($file->ID),
                    'top'
                );

                // Create separate rule for with trailing slash
                add_rewrite_rule(
                    '^' . preg_quote($filename, '/') . '/$',
                    'index.php?idep_virtual_file=1&file_id=' . intval($file->ID),
                    'top'
                );

                $registered_filenames[] = $filename;
            }
        }
    }

    private static function cleanupPluginData(): void {
        // Delete all virtual files
        $files = get_posts(array(
            'post_type' => 'idep_virtual_file',
            'posts_per_page' => -1,
            'post_status' => 'any',
        ));

        foreach ($files as $file) {
            wp_delete_post($file->ID, true);
        }

        // Delete options
        delete_option('intentdeep_vf_settings');
        delete_option('intentdeep_vf_onboarding_status');
    }

    public function loadTextDomain(): void {
        // WordPress.org automatically loads translations since 4.6
        // Function kept for compatibility with older WordPress versions only
        // Note: No longer needed for WordPress.org plugins
        
        // Do nothing - WordPress handles textdomain loading automatically
        return;
    }
}