<?php
declare(strict_types=1);


namespace ProRank\SEO\Core\RestApi\Controllers;

use ProRank\SEO\Core\RestApi\BaseController;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}




class ModulesController extends BaseController {
    
    public function register_routes() {
        register_rest_route($this->namespace, '/modules', [
            [
                'methods' => \WP_REST_Server::READABLE,
                'callback' => [$this, 'get_modules'],
                'permission_callback' => [$this, 'check_admin_permission'],
            ],
            [
                'methods' => \WP_REST_Server::EDITABLE,
                'callback' => [$this, 'update_module'],
                'permission_callback' => [$this, 'check_admin_permission'],
            ],
        ]);
        
        register_rest_route($this->namespace, '/modules/groups', [
            'methods' => \WP_REST_Server::READABLE,
            'callback' => [$this, 'get_module_groups'],
            'permission_callback' => [$this, 'check_admin_permission'],
        ]);

        // Module status endpoint for dashboard
        register_rest_route($this->namespace, '/modules/status', [
            'methods' => \WP_REST_Server::READABLE,
            'callback' => [$this, 'get_modules_status'],
            'permission_callback' => [$this, 'check_admin_permission'],
        ]);
        
        // Module toggle endpoint
        register_rest_route($this->namespace, '/modules/(?P<module>[a-z0-9-]+)/toggle', [
            [
                'methods' => \WP_REST_Server::CREATABLE,
                'callback' => [$this, 'toggle_module'],
                'permission_callback' => [$this, 'check_admin_permission'],
                'args' => [
                    'module' => [
                        'required' => true,
                        'sanitize_callback' => 'sanitize_key',
                    ],
                    'enabled' => [
                        'required' => true,
                        'type' => 'boolean',
                    ],
                ],
            ],
        ]);
    }
    
    public function get_modules($request) {
        try {
            $modules_manager = $this->container->get('modules');
            $modules = $modules_manager->get_modules();
            
            // Convert module objects to array data
            $module_data = [];
            foreach ($modules as $id => $module) {
                try {
                    $module_data[] = [
                        'id' => $module->id(),
                        'slug' => method_exists($module, 'get_slug') ? $module->get_slug() : $id,
                        'name' => method_exists($module, 'get_name') ? $module->get_name() : ucfirst(str_replace('-', ' ', $id)),
                        'description' => method_exists($module, 'get_description') ? $module->get_description() : '',
                        'tier_required' => $module->tier_required(),
                        'enabled' => $modules_manager->is_active($id),
                        'parent_slug' => method_exists($module, 'get_parent_slug') ? $module->get_parent_slug() : null,
                    ];
                } catch (\Exception $e) {
                    prorank_log('[ProRank SEO] Error processing module ' . $id . ': ' . $e->getMessage());
                }
            }
            
            return $this->success($module_data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 'modules_error', 500);
        }
    }
    
    public function update_module($request) {
        try {
            $module_id = $request->get_param('module_id');
            $enabled = $request->get_param('enabled');
            
            if (empty($module_id)) {
                return $this->error('Module ID is required', 'missing_module_id');
            }
            
            $modules_manager = $this->container->get('modules');
            
            if ($enabled) {
                $result = $modules_manager->enable_module($module_id);
            } else {
                $result = $modules_manager->disable_module($module_id);
            }
            
            if (is_wp_error($result)) {
                return $this->error($result->get_error_message(), $result->get_error_code());
            }
            
            return $this->success([
                'module_id' => $module_id,
                'enabled' => $enabled,
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 'modules_error', 500);
        }
    }
    
    public function get_module_groups($request) {
        try {
            // Define module groups based on ProRank's IA
            $groups = [
                [
                    'id' => 'on-page-seo',
                    'name' => __('On-Page SEO', 'prorank-seo'),
                    'icon' => 'edit',
                    'description' => __('Optimize your content for search engines', 'prorank-seo'),
                    'modules' => ['meta', 'breadcrumbs', 'schema', 'internal_links'],
                ],
                [
                    'id' => 'performance',
                    'name' => __('Performance', 'prorank-seo'),
                    'icon' => 'performance',
                    'description' => __('Speed up your site and improve Core Web Vitals', 'prorank-seo'),
                    'modules' => ['caching', 'asset_opt', 'image_opt', 'db_server'],
                ],
                [
                    'id' => 'technical-seo',
                    'name' => __('Technical SEO', 'prorank-seo'),
                    'icon' => 'admin-tools',
                    'description' => __('Handle technical aspects of SEO', 'prorank-seo'),
                    'modules' => ['sitemaps', 'robots_indexing', 'redirects', 'url_cleanup'],
                ],
            ];
            
            return $this->success($groups);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 'modules_error', 500);
        }
    }
    
    /**
     * Get simplified module status for dashboard
     *
     * @return \WP_REST_Response
     */
    public function get_modules_status($request) {
        try {
            $modules_manager = $this->container->get('modules');
            $modules = $modules_manager->get_modules();

            $module_status = [];
            foreach ($modules as $id => $module) {
                try {
                    $module_status[] = [
                        'slug' => method_exists($module, 'get_slug') ? $module->get_slug() : $id,
                        'name' => method_exists($module, 'get_name') ? $module->get_name() : ucfirst(str_replace('-', ' ', $id)),
                        'enabled' => $modules_manager->is_active($id),
                    ];
                } catch (\Exception $e) {
                    // Skip modules that fail to process
                    continue;
                }
            }

            return new \WP_REST_Response([
                'modules' => $module_status,
            ], 200);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 'modules_error', 500);
        }
    }

    /**
     * Toggle a specific module on or off
     */
    public function toggle_module($request) {
        try {
            $module_slug = $request->get_param('module');
            $enabled = $request->get_param('enabled');
            
            // Handle both boolean and string values
            if (is_string($enabled)) {
                $enabled = ($enabled === 'true' || $enabled === '1');
            }
            
            // Get current settings directly from WordPress options
            $settings = get_option('prorank_settings', []);
            if (!is_array($settings)) {
                $decoded = json_decode((string) $settings, true);
                $settings = is_array($decoded) ? $decoded : [];
            }
            if (!isset($settings['active_modules'])) {
                $settings['active_modules'] = [];
            }
            if (!is_array($settings['active_modules'])) {
                $settings['active_modules'] = [];
            }
            
            // Update both possible keys for the module
            $settings['active_modules'][$module_slug] = $enabled;
            
            // Also try to find and update by module ID
            if ($this->container && $this->container->has('modules')) {
                try {
                    $modules_manager = $this->container->get('modules');
                    $all_modules = $modules_manager->get_modules();
                    foreach ($all_modules as $module_id => $module) {
                        if (method_exists($module, 'get_slug') && $module->get_slug() === $module_slug) {
                            $settings['active_modules'][$module_id] = $enabled;
                            break;
                        }
                    }
                } catch (\Exception $e) {
                    // Continue anyway - module slug update is sufficient
                }
            }
            
            // Save settings
            update_option('prorank_settings', $settings);

            // Cascade sub-settings when performance modules are toggled
            $this->cascade_module_settings($module_slug, $enabled);

            // Return success response
            return $this->success([
                'module' => $module_slug,
                'enabled' => $enabled,
                'message' => $enabled 
                    ? __('Module enabled successfully', 'prorank-seo')
                    : __('Module disabled successfully', 'prorank-seo'),
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 'modules_error', 500);
        }
    }

    /**
     * Cascade sub-settings when a performance module is toggled.
     *
     * When a user enables a module via the toggle, the underlying feature
     * settings should also be activated so the module actually does something.
     * When disabled, sub-settings are left as-is (user may re-enable later).
     *
     * @param string $module_slug Module slug.
     * @param bool   $enabled     Whether the module was enabled.
     */
    private function cascade_module_settings(string $module_slug, bool $enabled): void {
        if (!$enabled) {
            return;
        }

        // Map: module_slug => [ option_name => [ key => value ] ]
        $cascade_map = [
            // JS Optimization → enable defer + delay
            'js_opt' => [
                'prorank_cache_settings' => [
                    'js_defer' => true,
                    'js_delay' => true,
                ],
            ],
            // CSS Optimization → enable minify + async
            'css_opt' => [
                'prorank_cache_settings' => [
                    'css_minify' => true,
                    'css_combine' => true,
                    // Keep async CSS opt-in: forcing async globally can increase CLS.
                    'css_async'  => false,
                ],
            ],
            // Browser Cache
            'browser_cache' => [
                'prorank_cache_settings' => [
                    'browser_cache_enabled' => true,
                ],
            ],
            // Resource Hints
            'resource_hints' => [
                'prorank_cache_settings' => [
                    'dns_prefetch_enabled' => true,
                ],
            ],
            // Page Cache
            'modern_cache' => [
                'prorank_cache_settings' => [
                    'enabled' => true,
                ],
            ],
            'cache' => [
                'prorank_cache_settings' => [
                    'enabled' => true,
                ],
            ],
            // Cache Preload
            'cache_preload' => [
                'prorank_cache_settings' => [
                    'preload_enabled' => true,
                ],
            ],
            // JS Minification
            'js_minify' => [
                'prorank_asset_optimization_settings' => [
                    'js_minify_enabled' => true,
                ],
            ],
            // HTML Minification
            'html_minify' => [
                'prorank_asset_optimization_settings' => [
                    'minify_html' => true,
                ],
            ],
            // Critical CSS
            'critical_css' => [
                'prorank_asset_optimization_settings' => [
                    'critical_css_enabled' => true,
                ],
            ],
            // Unused CSS
            'unused_css' => [
                'prorank_asset_optimization_settings' => [
                    'unused_css_enabled' => true,
                ],
            ],
            // Font Optimization
            'font_optimization' => [
                'prorank_asset_optimization_settings' => [
                    'host_google_fonts_locally' => true,
                    'font_display_swap'         => true,
                ],
            ],
            // LCP Optimizer
            'lcp_optimizer' => [
                'prorank_asset_optimization_settings' => [
                    'lcp_optimizer_enabled'     => true,
                    'lcp_preload_lcp'           => true,
                    'lcp_fetchpriority_enabled' => true,
                ],
            ],
            // INP Optimizer
            'inp_optimizer' => [
                'prorank_asset_optimization_settings' => [
                    'inp_optimizer_enabled' => true,
                ],
            ],
        ];

        if (!isset($cascade_map[$module_slug])) {
            return;
        }

        foreach ($cascade_map[$module_slug] as $option_name => $keys) {
            $option = get_option($option_name, []);
            if (!is_array($option)) {
                $option = [];
            }
            foreach ($keys as $key => $value) {
                $option[$key] = $value;
            }
            update_option($option_name, $option);
        }
    }
}
