<?php
/**
 * Modules REST API Controller
 * 
 * @package WooNooW\Api
 */

namespace WooNooW\Api;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use WooNooW\Core\ModuleRegistry;

class ModulesController extends WP_REST_Controller {
    
    /**
     * REST API namespace
     */
    protected $namespace = 'woonoow/v1';
    
    /**
     * REST API base
     */
    protected $rest_base = 'modules';
    
    /**
     * Register routes
     */
    public function register_routes() {
        // GET /woonoow/v1/modules
        register_rest_route($this->namespace, '/' . $this->rest_base, [
            [
                'methods' => WP_REST_Server::READABLE,
                'callback' => [$this, 'get_modules'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
        
        // POST /woonoow/v1/modules/toggle
        register_rest_route($this->namespace, '/' . $this->rest_base . '/toggle', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'toggle_module'],
                'permission_callback' => [$this, 'check_permission'],
                'args' => [
                    'module_id' => [
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                    'enabled' => [
                        'required' => true,
                        'type' => 'boolean',
                    ],
                ],
            ],
        ]);
        
        // GET /woonoow/v1/modules/enabled (public endpoint for frontend)
        register_rest_route($this->namespace, '/' . $this->rest_base . '/enabled', [
            [
                'methods' => WP_REST_Server::READABLE,
                'callback' => [$this, 'get_enabled_modules'],
                'permission_callback' => '__return_true',
            ],
        ]);
    }
    
    /**
     * Check permission
     * 
     * @return bool
     */
    public function check_permission() {
        return current_user_can('manage_options');
    }
    
    /**
     * Get all modules with status
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function get_modules($request) {
        $modules = ModuleRegistry::get_all_with_status();
        $grouped = ModuleRegistry::get_grouped_modules();
        
        // Add enabled status to grouped modules
        $enabled_modules = ModuleRegistry::get_enabled_modules();
        foreach ($grouped as $category => &$category_modules) {
            foreach ($category_modules as &$module) {
                $module['enabled'] = in_array($module['id'], $enabled_modules);
            }
        }
        
        return new WP_REST_Response([
            'modules' => $modules,
            'grouped' => $grouped,
            'categories' => ModuleRegistry::get_categories(),
        ], 200);
    }
    
    /**
     * Toggle module enabled/disabled
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function toggle_module($request) {
        $module_id = $request->get_param('module_id');
        $enabled = $request->get_param('enabled');
        
        if (empty($module_id)) {
            return new WP_Error(
                'missing_module_id',
                __('Module ID is required', 'woonoow'),
                ['status' => 400]
            );
        }
        
        // Get all modules to validate module_id
        $all_modules = ModuleRegistry::get_all_modules();
        $module_exists = false;
        foreach ($all_modules as $module) {
            if ($module['id'] === $module_id) {
                $module_exists = true;
                break;
            }
        }
        
        if (!$module_exists) {
            return new WP_Error(
                'invalid_module',
                __('Invalid module ID', 'woonoow'),
                ['status' => 400]
            );
        }
        
        // Toggle module
        if ($enabled) {
            ModuleRegistry::enable($module_id);
        } else {
            ModuleRegistry::disable($module_id);
        }
        
        // Return success response
        return rest_ensure_response([
            'success' => true,
            'module_id' => $module_id,
            'enabled' => $enabled,
            'enabled_modules' => ModuleRegistry::get_enabled_modules(),
            'nav_tree' => class_exists('\WooNooW\Compat\NavigationRegistry')
                ? \WooNooW\Compat\NavigationRegistry::get_frontend_nav_tree()
                : [],
        ]);
    }
    
    /**
     * Get enabled modules (public endpoint)
     * 
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function get_enabled_modules($request) {
        $enabled = ModuleRegistry::get_enabled_modules();
        
        return new WP_REST_Response([
            'enabled' => $enabled,
        ], 200);
    }
}
