<?php

/**
 * Version Management REST API Controller
 *
 * Handles version rollback, beta opt-in, and auto-update settings
 *
 * @package ProRank\SEO\Core\RestApi
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use ProRank\SEO\Core\VersionManager;

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




class VersionController {

    /**
     * Version manager instance
     */
    private VersionManager $version_manager;

    /**
     * REST API namespace
     */
    private const NAMESPACE = 'prorank-seo/v1';

    /**
     * Constructor
     */
    public function __construct() {
        $this->version_manager = new VersionManager();
    }

    /**
     * Register REST API routes
     */
    public function register_routes(): void {
        // Get available versions
        register_rest_route(self::NAMESPACE, '/versions', [
            'methods'             => 'GET',
            'callback'            => [$this, 'get_versions'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        // Get version settings (beta opt-in, auto-update, etc.)
        register_rest_route(self::NAMESPACE, '/versions/settings', [
            'methods'             => 'GET',
            'callback'            => [$this, 'get_settings'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        // Update version settings
        register_rest_route(self::NAMESPACE, '/versions/settings', [
            'methods'             => 'POST',
            'callback'            => [$this, 'update_settings'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        // Create backup before rollback
        register_rest_route(self::NAMESPACE, '/versions/backup', [
            'methods'             => 'POST',
            'callback'            => [$this, 'create_backup'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        // Rollback to a specific version
        register_rest_route(self::NAMESPACE, '/versions/rollback', [
            'methods'             => 'POST',
            'callback'            => [$this, 'rollback_version'],
            'permission_callback' => [$this, 'check_permission'],
        ]);

        // Get rollback history
        register_rest_route(self::NAMESPACE, '/versions/history', [
            'methods'             => 'GET',
            'callback'            => [$this, 'get_history'],
            'permission_callback' => [$this, 'check_permission'],
        ]);
    }

    /**
     * Check if user has permission to access version management
     */
    public function check_permission(): bool {
        return current_user_can('manage_options');
    }

    /**
     * Get available versions for rollback
     */
    public function get_versions(WP_REST_Request $request): WP_REST_Response {
        unset($request);

        $latest_backup = $this->version_manager->get_latest_backup();

        return new WP_REST_Response([
            'success' => true,
            'current_version' => PRORANK_VERSION,
            'versions' => [],
            'can_rollback' => false,
            'message' => __('Free plugin updates are handled by WordPress. Use the Plugins screen for updates, or install an approved package manually if you need a different version.', 'prorank-seo'),
            'latest_backup' => $latest_backup ? [
                'backup_name'  => $latest_backup['file'] ?? '',
                'backup_path'  => $latest_backup['path'] ?? '',
                'created_at'   => $latest_backup['created_at'] ?? '',
                'size'         => $latest_backup['size'] ?? 0,
                'download_url' => $this->version_manager->get_backup_download_url((string) $latest_backup['file']),
            ] : null,
        ], 200);
    }

    /**
     * Get version management settings
     */
    public function get_settings(WP_REST_Request $request): WP_REST_Response {
        unset($request);

        return new WP_REST_Response([
            'success' => true,
            'settings' => [
                'auto_update' => (bool) get_option('prorank_auto_update', false),
            ],
        ], 200);
    }

    /**
     * Update version management settings
     */
    public function update_settings(WP_REST_Request $request): WP_REST_Response {
        $params = $request->get_json_params();
        if (!is_array($params)) {
            $params = $request->get_params();
        }

        if (isset($params['auto_update'])) {
            update_option('prorank_auto_update', rest_sanitize_boolean($params['auto_update']));
        }

        return new WP_REST_Response([
            'success' => true,
            'message' => __('Settings saved successfully', 'prorank-seo'),
        ], 200);
    }

    /**
     * Create backup before rollback
     */
    public function create_backup(WP_REST_Request $request): WP_REST_Response {
        $result = $this->version_manager->create_backup();

        if (is_wp_error($result)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result->get_error_message(),
            ], 500);
        }

        return new WP_REST_Response([
            'success' => true,
            'message' => __('Backup created successfully', 'prorank-seo'),
            'backup_path' => $result['backup_path'] ?? '',
            'backup_name' => $result['backup_name'] ?? '',
            'download_url' => !empty($result['backup_name'])
                ? $this->version_manager->get_backup_download_url((string) $result['backup_name'])
                : '',
        ], 200);
    }

    /**
     * Rollback to a specific version
     */
    public function rollback_version(WP_REST_Request $request): WP_REST_Response {
        $params = $request->get_json_params();
        $target_version = $params['version'] ?? '';

        if (empty($target_version)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => __('Target version is required', 'prorank-seo'),
            ], 400);
        }

        // Check if target version is different from current
        if ($target_version === PRORANK_VERSION) {
            return new WP_REST_Response([
                'success' => false,
                'message' => __('You are already running this version', 'prorank-seo'),
            ], 400);
        }

        $result = $this->version_manager->rollback_to_version($target_version);

        if (is_wp_error($result)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result->get_error_message(),
            ], 500);
        }

        return new WP_REST_Response([
            'success' => true,
            'message' => sprintf(
/* translators: %1$: value */
                __('Successfully rolled back to version %1$s. Please refresh the page.', 'prorank-seo'),
                $target_version
            ),
            'new_version' => $target_version,
        ], 200);
    }

    /**
     * Get rollback history
     */
    public function get_history(WP_REST_Request $request): WP_REST_Response {
        $history = $this->version_manager->get_rollback_history();

        return new WP_REST_Response([
            'success' => true,
            'history' => $history,
        ], 200);
    }

}
