<?php

/**
 * Onboarding REST API Controller
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

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

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


/**
 * Handles onboarding-related REST API endpoints
 */


class OnboardingController extends BaseController {
    
    /**
     * Route base
     *
     * @var string
     */
    protected $rest_base = 'onboarding';
    
    /**
     * Settings manager instance
     *
     * @var SettingsManager|null
     */
    private ?SettingsManager $settings_manager = null;
    
    /**
     * Set settings manager
     *
     * @param SettingsManager $settings_manager
     * @return void
     */
    public function set_settings_manager(SettingsManager $settings_manager): void {
        $this->settings_manager = $settings_manager;
    }
    
    /**
     * Register routes
     *
     * @return void
     */
    public function register_routes(): void {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/complete',
            [
                [
                    'methods'             => \WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'complete_onboarding'],
                    'permission_callback' => [$this, 'check_permission'],
                    'args'                => $this->get_endpoint_args_for_item_schema(false),
                ],
            ]
        );
    }
    
    /**
     * Complete onboarding process
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function complete_onboarding(WP_REST_Request $request) {
        if (!$this->settings_manager) {
            return $this->get_error_response(
                __('Settings manager not available.', 'prorank-seo'),
                500
            );
        }
        
        try {
            // Get parameters
            $site_type = $request->get_param('site_type');
            
            // Validate site type
            $valid_site_types = ['blog', 'shop', 'business'];
            if (!empty($site_type) && !in_array($site_type, $valid_site_types, true)) {
                return $this->get_error_response(
                    __('Invalid site type selected.', 'prorank-seo'),
                    400
                );
            }
            
            // Save settings
            $updates = [];
            
            if (!empty($site_type)) {
                $updates['site_type'] = $site_type;
            }
            
            // Save onboarding settings
            if (!empty($updates)) {
                try {
                    $this->settings_manager->update_settings_group('onboarding', $updates);
                } catch (\Exception $e) {
                    prorank_log('[ProRank SEO] Failed to save settings: ' . $e->getMessage());
                    return $this->get_error_response(
                        __('Failed to save onboarding settings.', 'prorank-seo'),
                        500
                    );
                }
            }
            
            // Mark onboarding as completed
            try {
                $this->settings_manager->update_setting('onboarding', 'completed', true);
            } catch (\Exception $e) {
                prorank_log('[ProRank SEO] Failed to mark completed: ' . $e->getMessage());
                return $this->get_error_response(
                    __('Failed to mark onboarding as completed.', 'prorank-seo'),
                    500
                );
            }
            
            // Clear the onboarding modal flag
            delete_option('prorank_show_onboarding_modal');
            
            return $this->get_success_response(
                [
                    'site_type' => $site_type,
                ],
                __('Onboarding completed successfully.', 'prorank-seo')
            );
        } catch (\Exception $e) {
            prorank_log('[ProRank SEO] Onboarding exception: ' . $e->getMessage());
            if (defined('WP_DEBUG') && WP_DEBUG) {
                prorank_log($e->getTraceAsString());
            }
            return $this->get_error_response(
                __('An unexpected error occurred.', 'prorank-seo'),
                500
            );
        }
    }
    
    /**
     * Get schema for endpoint
     *
     * @return array
     */
    public function get_item_schema(): array {
        $schema = [
            '$schema'    => 'http://json-schema.org/draft-04/schema#',
            'title'      => 'onboarding',
            'type'       => 'object',
            'properties' => [
                'site_type' => [
                    'description' => __('Type of website', 'prorank-seo'),
                    'type'        => 'string',
                    'enum'        => ['blog', 'shop', 'business'],
                    'required'    => false,
                ],
            ],
        ];
        
        return $schema;
    }
}
