<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\OptionsController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\SystemController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\UserController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\SecurityController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\UpdateController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\ScannerController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\FeedbackController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\TestModeController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\SiteStatusController;
// REMOVED: SecurityHeadersController - server-level feature (see docs/SERVER_LEVEL_FEATURES.md)
// Note: Trusted Devices routes are registered in AuthenticationRoutes.php with Pro protection
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\WizardController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\SettingsController;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers\LoginNotificationsController;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\ServerProtectionDetector;
use WPUltimateSecurity\UltimateSecurity\Presentation\API\Routes\RouteManager;

use WP_REST_Response;
use WP_REST_Request;
/**
 * Rest API Router
 *
 * Registers all REST API endpoints and routes them to appropriate controllers
 */
class RestAPI
{
    private const NAMESPACE = 'ultimate-security/v1';
    /**
     * Register REST API hooks
     */
    public static function register()
    {
        add_action('rest_api_init', [self::class, 'ultimate_security_rest_api_init']);
    }

    /**
     * Initialize all REST API endpoints
     */
    public static function ultimate_security_rest_api_init()
    {
        self::register_plugin_endpoints();
        self::register_option_endpoints();
        self::register_system_endpoints();
        self::register_user_endpoints();
        self::register_security_endpoints();
        self::register_update_endpoints();
        self::register_scanner_endpoints();
        self::register_test_mode_endpoints();
        self::register_site_status_endpoints();
        // REMOVED: self::register_security_headers_endpoints() - server-level feature
        // REMOVED: self::register_trusted_devices_endpoints() - registered in AuthenticationRoutes.php with Pro protection
        self::register_wizard_endpoints();
        self::register_login_notifications_endpoints();
        self::register_settings_endpoints();
        self::register_server_protection_endpoints();
        RouteManager::getInstance()->registerAll();
    }
    /**
     * Register plugin information endpoints
     */
    private static function register_plugin_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/plugin-info',
            array(
                'methods' => 'GET',
                'callback' => [SystemController::class, 'get_plugin_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );
    }

    /**
     * Register options-related endpoints
     */
    private static function register_option_endpoints()
    {
        // GET options
        register_rest_route(
            self::NAMESPACE,
            '/options',
            array(
                'methods' => 'GET',
                'callback' => [OptionsController::class, 'get_options'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // POST/UPDATE options
        register_rest_route(
            self::NAMESPACE,
            '/options',
            array(
                'methods' => 'POST',
                'callback' => [OptionsController::class, 'update_options'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // Save recovery URL
        register_rest_route(
            self::NAMESPACE,
            '/save-recovery-url',
            array(
                'methods' => 'POST',
                'callback' => [OptionsController::class, 'save_recovery_url'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // Get encryption database keys
        register_rest_route(
            self::NAMESPACE,
            '/get-enable-encryption-database-keys',
            array(
                'methods' => 'GET',
                'callback' => [OptionsController::class, 'get_encryption_database_keys'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );
    }

    /**
     * Register system information endpoints
     */
    private static function register_system_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/get-ip',
            array(
                'methods' => 'GET',
                'callback' => [SystemController::class, 'get_ip'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-post-types',
            array(
                'methods' => 'GET',
                'callback' => [SystemController::class, 'get_post_types'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/site-health-report',
            [
                'methods' => 'GET',
                'callback' => [SystemController::class, 'get_site_health_data'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        register_rest_route(
            self::NAMESPACE,
            '/setup-complete',
            [
                'methods' => 'POST',
                'callback' => [SystemController::class, 'setup_complete'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        register_rest_route(
            self::NAMESPACE,
            '/system-info',
            [
                'methods' => 'GET',
                'callback' => [SystemController::class, 'get_system_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );
    }

    /**
     * Register user-related endpoints
     */
    private static function register_user_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/get-admin-emails',
            array(
                'methods' => 'GET',
                'callback' => [UserController::class, 'get_admin_emails'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-users',
            array(
                'methods' => 'GET',
                'callback' => [UserController::class, 'get_users'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-roles',
            array(
                'methods' => 'GET',
                'callback' => [UserController::class, 'get_roles'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-all-users',
            array(
                'methods' => 'GET',
                'callback' => [UserController::class, 'get_all_users'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-setting-theme',
            array(
                'methods' => 'GET',
                'callback' => [UserController::class, 'get_setting_theme'],
                'permission_callback' => [self::class, 'check_manage_options'], 
            )
        );
        register_rest_route(
            self::NAMESPACE,
            '/set-setting-theme',
            array(
                'methods' => 'POST',
                'callback' => [UserController::class, 'set_setting_theme'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'user_id'       => [ 'sanitize_callback' => 'absint' ],
                    'settings_theme' => [ 'sanitize_callback' => 'sanitize_text_field' ],
                ],
            )
        );
    }

    /**
     * Register security-related endpoints
     */
    private static function register_security_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/get-salt',
            array(
                'methods' => 'GET',
                'callback' => [SecurityController::class, 'get_salt'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/generate-salt',
            array(
                'methods' => 'GET',
                'callback' => [SecurityController::class, 'generate_salts'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-login-failed-logs',
            array(
                'methods' => 'GET',
                'callback' => [SecurityController::class, 'get_login_failed_logs'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // Salt info endpoint (last changed date, next scheduled, rate limit status)
        register_rest_route(
            self::NAMESPACE,
            '/salt-info',
            array(
                'methods' => 'GET',
                'callback' => [SecurityController::class, 'get_salt_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // Salt backup endpoint
        register_rest_route(
            self::NAMESPACE,
            '/salt-backup',
            array(
                'methods' => 'GET',
                'callback' => [SecurityController::class, 'get_salt_backup'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // Restore salt backup endpoint
        register_rest_route(
            self::NAMESPACE,
            '/salt-backup/restore',
            array(
                'methods' => 'POST',
                'callback' => [SecurityController::class, 'restore_salt_backup'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        // Pause salt schedule endpoint
        register_rest_route(
            self::NAMESPACE,
            '/salt-schedule/pause',
            array(
                'methods' => 'POST',
                'callback' => [SecurityController::class, 'pause_salt_schedule'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'until_date' => ['sanitize_callback' => 'sanitize_text_field'],
                ],
            )
        );

        // Skip next salt change endpoint
        register_rest_route(
            self::NAMESPACE,
            '/salt-schedule/skip-next',
            array(
                'methods' => 'POST',
                'callback' => [SecurityController::class, 'skip_next_salt_change'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'skip' => ['sanitize_callback' => 'rest_sanitize_boolean'],
                ],
            )
        );

        // Salt change history endpoint
        register_rest_route(
            self::NAMESPACE,
            '/salt-history',
            array(
                'methods' => 'GET',
                'callback' => [SecurityController::class, 'get_salt_history'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/feedback',
            array(
                'methods' => 'POST',
                'callback' => [FeedbackController::class, 'submit_feedback'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );
    }

    /**
     * Register update-related endpoints
     */
    private static function register_update_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/get-latest-version',
            array(
                'methods' => 'GET',
                'callback' => [UpdateController::class, 'get_latest_version'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-update-info',
            array(
                'methods' => 'GET',
                'callback' => [UpdateController::class, 'get_update_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/update-plugin-info',
            [
                'methods' => 'GET',
                'callback' => [UpdateController::class, 'get_update_plugin_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-plugins-info',
            array(
                'methods' => 'GET',
                'callback' => [UpdateController::class, 'get_plugins_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );

        register_rest_route(
            self::NAMESPACE,
            '/get-themes-info',
            array(
                'methods' => 'GET',
                'callback' => [UpdateController::class, 'get_themes_info'],
                'permission_callback' => [self::class, 'check_manage_options'],
            )
        );
    }

    /**
     * Register scanner endpoints
     */
    private static function register_scanner_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/core-scan-check-integrity-status',
            [
                'methods' => 'GET',
                'callback' => [ScannerController::class, 'check_integrity'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );
    }

    /**
     * Register site status endpoints (SSL and uptime)
     */
    private static function register_site_status_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/site-status',
            [
                'methods' => 'GET',
                'callback' => [SiteStatusController::class, 'get_site_status'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );
    }

    /**
     * Register test mode endpoints
     */
    private static function register_test_mode_endpoints()
    {
        // Get test mode data (settings, stats, available roles)
        register_rest_route(
            self::NAMESPACE,
            '/test-mode',
            [
                'methods' => 'GET',
                'callback' => [TestModeController::class, 'get_test_mode_data'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get simulation logs
        register_rest_route(
            self::NAMESPACE,
            '/test-mode/logs',
            [
                'methods' => 'GET',
                'callback' => [TestModeController::class, 'get_simulation_logs'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'page' => ['sanitize_callback' => 'absint'],
                    'per_page' => ['sanitize_callback' => 'absint'],
                ],
            ]
        );

        // Clear simulation logs
        register_rest_route(
            self::NAMESPACE,
            '/test-mode/logs',
            [
                'methods' => 'DELETE',
                'callback' => [TestModeController::class, 'clear_logs'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get simulation logs
        register_rest_route(
            self::NAMESPACE,
            '/update-option',
            [
                'methods' => 'GET',
                'callback' => [self::class, 'update_option'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'key' => ['sanitize_callback' => 'sanitize_text_field'],
                    'value' => ['sanitize_callback' => 'sanitize_text_field'],
                ],
            ]
        );
        register_rest_route(
            self::NAMESPACE,
            '/get-option',
            [
                'methods' => 'GET',
                'callback' => [self::class, 'get_option'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'key' => ['sanitize_callback' => 'sanitize_text_field'],
                ],
            ]
        );
    }

    /**
     * Permission callback to check if user can manage options
     *
     * @return bool
     */
    public static function check_manage_options()
    {
        return current_user_can('manage_options');
    }
    public static function update_option(WP_REST_Request $request)
    {
        if (!current_user_can('manage_options')) {
            return new WP_REST_Response([
                'error_message' => esc_html__('You do not have permission to access this resource.', 'ultimate-security')
            ], 403);
        }
        $key = trim($request->get_param('key') ?? '');
        $value = trim($request->get_param('value') ?? '');
        $result = update_option($key, $value);
        return new WP_REST_Response(['success' => $result], $result ? 200 : 500);
    }
    public static function get_option(WP_REST_Request $request)
    {
        if (!current_user_can('manage_options')) {
            return new WP_REST_Response([
                'error_message' => esc_html__('You do not have permission to access this resource.', 'ultimate-security')
            ], 403);
        }
        $key = trim($request->get_param('key') ?? '');
        $value = get_option($key);
        return new WP_REST_Response(['success' => true, 'value' => $value], 200);
    }

    // REMOVED: register_security_headers_endpoints() - server-level feature (see docs/SERVER_LEVEL_FEATURES.md)
    // REMOVED: register_trusted_devices_endpoints() - now registered in AuthenticationRoutes.php with Pro protection

    /**
     * Register security wizard endpoints
     */
    private static function register_wizard_endpoints()
    {
        // Get wizard status
        register_rest_route(
            self::NAMESPACE,
            '/wizard/status',
            [
                'methods' => 'GET',
                'callback' => [WizardController::class, 'getStatus'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Run security scan
        register_rest_route(
            self::NAMESPACE,
            '/wizard/scan',
            [
                'methods' => 'GET',
                'callback' => [WizardController::class, 'runScan'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get available profiles
        register_rest_route(
            self::NAMESPACE,
            '/wizard/profiles',
            [
                'methods' => 'GET',
                'callback' => [WizardController::class, 'getProfiles'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get profile comparison with current settings
        register_rest_route(
            self::NAMESPACE,
            '/wizard/compare',
            [
                'methods' => 'GET',
                'callback' => [WizardController::class, 'getProfileComparison'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'level' => [
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ]
        );

        // Apply selected profile
        register_rest_route(
            self::NAMESPACE,
            '/wizard/apply',
            [
                'methods' => 'POST',
                'callback' => [WizardController::class, 'applyProfile'],
                'permission_callback' => [self::class, 'check_manage_options'],

                'args' => [
                    'level' => [
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ]
        );

        // Undo wizard changes
        register_rest_route(
            self::NAMESPACE,
            '/wizard/undo',
            [
                'methods' => 'POST',
                'callback' => [WizardController::class, 'undoChanges'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Skip wizard
        register_rest_route(
            self::NAMESPACE,
            '/wizard/skip',
            [
                'methods' => 'POST',
                'callback' => [WizardController::class, 'skipWizard'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get 2FA wizard data
        register_rest_route(
            self::NAMESPACE,
            '/wizard/2fa',
            [
                'methods' => 'GET',
                'callback' => [WizardController::class, 'get2FAWizardData'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Update 2FA wizard data
        register_rest_route(
            self::NAMESPACE,
            '/wizard/2fa',
            [
                'methods' => 'POST',
                'callback' => [WizardController::class, 'update2FAWizardData'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'wizard_data' => [
                        'required' => true,
                        'validate_callback' => function($param) {
                            return is_array($param);
                        },
                    ],
                ],
            ]
        );
    }

    /**
     * Register login notifications endpoints
     */
    private static function register_login_notifications_endpoints()
    {
        // Get login notification settings
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/settings',
            [
                'methods' => 'GET',
                'callback' => [LoginNotificationsController::class, 'get_settings'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Update login notification settings
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/settings',
            [
                'methods' => 'POST',
                'callback' => [LoginNotificationsController::class, 'update_settings'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get recent notifications
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/recent',
            [
                'methods' => 'GET',
                'callback' => [LoginNotificationsController::class, 'get_recent'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'limit' => [
                        'sanitize_callback' => 'absint',
                        'default' => 50,
                    ],
                ],
            ]
        );

        // Send test notification
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/test',
            [
                'methods' => 'POST',
                'callback' => [LoginNotificationsController::class, 'send_test'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'email' => [
                        'sanitize_callback' => 'sanitize_email',
                    ],
                ],
            ]
        );

        // Clear notification history
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/clear',
            [
                'methods' => 'DELETE',
                'callback' => [LoginNotificationsController::class, 'clear_history'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );

        // Get notification statistics
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/stats',
            [
                'methods' => 'GET',
                'callback' => [LoginNotificationsController::class, 'get_stats'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'period' => [
                        'sanitize_callback' => 'sanitize_text_field',
                        'default' => '24h',
                    ],
                ],
            ]
        );

        // Trigger digest manually (for testing)
        register_rest_route(
            self::NAMESPACE,
            '/login-notifications/trigger-digest',
            [
                'methods' => 'POST',
                'callback' => [LoginNotificationsController::class, 'trigger_digest'],
                'permission_callback' => [self::class, 'check_manage_options'],
                'args' => [
                    'type' => [
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ]
        );
    }

    /**
     * Register settings management endpoints
     */
    private static function register_settings_endpoints()
    {
        // Purge all caches (LiteSpeed, WP Super Cache, W3 Total Cache)
        register_rest_route(
            self::NAMESPACE,
            '/settings/purge-cache',
            [
                'methods' => 'POST',
                'callback' => [self::class, 'handle_purge_cache'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );
    }

    /**
     * Handle cache purge request
     *
     * @param WP_REST_Request $request The request object
     * @return WP_REST_Response
     */
    public static function handle_purge_cache(WP_REST_Request $request): WP_REST_Response
    {
        $controller = new SettingsController();
        $controller->purge_caches();

        return new WP_REST_Response([
            'success' => true,
            'message' => __('All caches have been purged successfully.', 'ultimate-security'),
        ], 200);
    }

    /**
     * Register server protection detection endpoints
     */
    private static function register_server_protection_endpoints()
    {
        register_rest_route(
            self::NAMESPACE,
            '/server-protection',
            [
                'methods' => 'GET',
                'callback' => [self::class, 'get_server_protection'],
                'permission_callback' => [self::class, 'check_manage_options'],
            ]
        );
    }

    /**
     * Get server protection detection status
     *
     * @return WP_REST_Response
     */
    public static function get_server_protection(): WP_REST_Response
    {
        return new WP_REST_Response(ServerProtectionDetector::get_status(), 200);
    }
}
