<?php
/**
 * Author: Rymera Web Co
 *
 * @package SAAI
 */

namespace SAAI\REST;

use SAAI\Abstracts\Abstract_REST;
use SAAI\Classes\Onboarding_Wizard;
use SAAI\Helpers\Connect;
use SAAI\Helpers\Helper;
use SAAI\Traits\Singleton_Trait;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

defined( 'ABSPATH' ) || exit;

/**
 * Class Onboarding
 *
 * @since   1.0.0
 * @package SAAI
 */
class Onboarding extends Abstract_REST {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @var Onboarding $instance object
     * @since 1.0.0
     */
    protected static $instance;

    /**
     * Works as constructor for this class.
     *
     * @since 1.0.0
     * @return void
     */
    public function register_plugin_routes() {

        $this->rest_base = 'onboarding';
        parent::register_plugin_routes();
    }

    /**
     * Checks if a given request has permission to access onboarding endpoints.
     *
     * @param WP_REST_Request $request Full data about the request.
     *
     * @since 1.0.0
     * @return WP_Error|bool True if the request has access, WP_Error object otherwise.
     */
    public function permissions_check( $request ) {

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            return new WP_Error(
                'rest_forbidden',
                __( 'You do not have permission to access this resource.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 403 )
            );
        }

        return true;
    }

    /**
     * Register the routes for the objects of the controller.
     *
     * @since 1.0.0
     */
    public function register_routes() {

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/status",
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_status' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            )
        );

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/complete",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'complete_wizard' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            )
        );

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/skip",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'skip_wizard' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            )
        );

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/save-tools",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'save_selected_tools' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            )
        );

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/save-chat",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'save_chat_settings' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            )
        );
    }

    /**
     * Get onboarding wizard status
     *
     * @param WP_REST_Request $request REST request object.
     *
     * @return WP_REST_Response
     */
    public function get_status( $request ) {

        $wizard_status = get_option( Onboarding_Wizard::WIZARD_STATUS_OPTION, '' );

        $response = array(
            'status'       => $wizard_status,
            'completed'    => Onboarding_Wizard::STATUS_COMPLETED === $wizard_status,
            'skipped'      => Onboarding_Wizard::STATUS_SKIPPED === $wizard_status,
            'is_connected' => Connect::is_connected(),
        );

        return $this->rest_response( $response, $request );
    }

    /**
     * Mark wizard as completed
     *
     * @param WP_REST_Request $request REST request object.
     *
     * @return WP_REST_Response
     */
    public function complete_wizard( $request ) {

        update_option( Onboarding_Wizard::WIZARD_STATUS_OPTION, Onboarding_Wizard::STATUS_COMPLETED, false );

        $response = array(
            'success' => true,
            'message' => __( 'Onboarding wizard completed successfully!', 'storeagent-ai-for-woocommerce' ),
        );

        return $this->rest_response( $response, $request );
    }

    /**
     * Mark wizard as skipped
     *
     * @param WP_REST_Request $request REST request object.
     *
     * @return WP_REST_Response
     */
    public function skip_wizard( $request ) {

        update_option( Onboarding_Wizard::WIZARD_STATUS_OPTION, Onboarding_Wizard::STATUS_SKIPPED, false );

        $response = array(
            'success' => true,
            'message' => __( 'Onboarding wizard skipped.', 'storeagent-ai-for-woocommerce' ),
        );

        return $this->rest_response( $response, $request );
    }

    /**
     * Save selected AI tools/agents
     *
     * @param WP_REST_Request $request REST request object.
     *
     * @return WP_REST_Response
     */
    public function save_selected_tools( $request ) {

        $selected_tools = $request->get_param( 'tools' );

        if ( ! is_array( $selected_tools ) ) {
            return new WP_Error(
                'rest_invalid_params',
                __( 'Invalid tools parameter.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 400 )
            );
        }

        $agents = Helper::get_ai_agents();

        // Update status for each agent.
        foreach ( $agents as $agent ) {
            $agent_id         = $agent['id'];
            $class_name       = str_replace( ' ', '_', $agent['title'] );
            $ai_agent_class   = 'SAAI\AI_Agents\\' . $class_name;
            $ai_agent_key     = 'saai_' . str_replace( '-', '_', $agent_id );
            $is_selected      = in_array( $agent_id, $selected_tools, true );
            $agent_enabled    = $is_selected ? 'yes' : 'no';
            $existing_options = (array) get_option( $ai_agent_key, array() );

            if ( class_exists( $ai_agent_class ) ) {
                $existing_options = wp_parse_args( $existing_options, $ai_agent_class::instance()->default_settings );
            }

            $existing_options['enabled'] = $agent_enabled;
            update_option( $ai_agent_key, $existing_options, false );
        }

        $response = array(
            'success' => true,
            'message' => __( 'AI tools settings saved!', 'storeagent-ai-for-woocommerce' ),
        );

        return $this->rest_response( $response, $request );
    }

    /**
     * Save chat settings
     *
     * @param WP_REST_Request $request REST request object.
     *
     * @return WP_REST_Response
     */
    public function save_chat_settings( $request ) {

        $enabled = $request->get_param( 'enabled' );
        $sources = $request->get_param( 'sources' );

        if ( ! is_bool( $enabled ) || ! is_array( $sources ) ) {
            return new WP_Error(
                'rest_invalid_params',
                __( 'Invalid parameters.', 'storeagent-ai-for-woocommerce' ),
                array( 'status' => 400 )
            );
        }

        // Save chat widget enabled status.
        $chat_settings            = get_option( 'saai_chat_widget_settings', \SAAI\REST\Chat\Chat_Widget_Settings::get_default_settings() );
        $chat_settings['enabled'] = $enabled; // Boolean value (true/false).
        update_option( 'saai_chat_widget_settings', $chat_settings, false );

        // Update chat post types settings - enable all selected post types.
        $chat_post_types_settings = get_option( 'saai_chat_post_types', array() );

        // Get all public post types to ensure we disable everything first.
        $all_post_types = get_post_types( array( 'public' => true ), 'names' );

        // First, disable all post types (including ones not yet in settings).
        foreach ( $all_post_types as $post_type ) {
            if ( ! isset( $chat_post_types_settings[ $post_type ] ) ) {
                $chat_post_types_settings[ $post_type ] = array();
            }
            $chat_post_types_settings[ $post_type ]['enabled'] = 'no';
        }

        // Then enable the selected ones.
        foreach ( $sources as $post_type ) {
            if ( ! isset( $chat_post_types_settings[ $post_type ] ) ) {
                $chat_post_types_settings[ $post_type ] = array();
            }
            $chat_post_types_settings[ $post_type ]['enabled'] = 'yes';

            // Ensure meta_keys is set if it doesn't exist.
            if ( ! isset( $chat_post_types_settings[ $post_type ]['meta_keys'] ) ) {
                $chat_post_types_settings[ $post_type ]['meta_keys'] = array();
            }
        }

        update_option( 'saai_chat_post_types', $chat_post_types_settings, false );

        // Trigger sync if products are enabled.
        if ( in_array( 'product', $sources, true ) ) {
            // Schedule product sync.
            do_action( 'saai_schedule_product_sync' );
        }

        $response = array(
            'success' => true,
            'message' => __( 'Chat settings saved!', 'storeagent-ai-for-woocommerce' ),
        );

        return $this->rest_response( $response, $request );
    }
}
