<?php
/**
 * Onboarding Wizard Handler
 *
 * @package SAAI\Classes
 */

namespace SAAI\Classes;

use SAAI\Helpers\Connect;
use SAAI\Helpers\Helper;
use SAAI\Factories\Vite_App;
use SAAI\Traits\Singleton_Trait;

/**
 * Onboarding_Wizard class - handles the onboarding wizard functionality
 *
 * @since 1.0.0
 */
class Onboarding_Wizard {

    use Singleton_Trait;

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

    /**
     * Onboarding wizard page slug
     *
     * @since 1.0.0
     */
    public const WIZARD_SLUG = 'storeagent-onboarding';

    /**
     * Option key for tracking wizard status
     *
     * @since 1.0.0
     */
    public const WIZARD_STATUS_OPTION = 'saai_onboarding_wizard_status';

    /**
     * Wizard status values
     *
     * @since 1.0.0
     */
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_SKIPPED   = 'skipped';

    /**
     * Check if wizard should be shown
     *
     * @since 1.0.0
     * @return bool
     */
    public static function should_show_wizard() {
        // Don't show if already completed or skipped.
        $wizard_status = get_option( self::WIZARD_STATUS_OPTION, '' );
        if ( in_array( $wizard_status, array( self::STATUS_COMPLETED, self::STATUS_SKIPPED ), true ) ) {
            return false;
        }

        // Don't show if not connected yet (show connect page instead).
        if ( ! Connect::is_connected() ) {
            return false;
        }

        return true;
    }

    /**
     * Redirect to wizard if needed
     *
     * @since 1.0.0
     * @return void
     */
    public function maybe_redirect_to_wizard() {
        global $pagenow;

        // Only redirect on admin pages.
        if ( 'admin.php' !== $pagenow ) {
            return;
        }

        // Check if we're on StoreAgent dashboard page.
        $current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
        if ( Admin_Menu_Handler::PARENT_SLUG !== $current_page ) {
            return;
        }

        // Check if wizard should be shown.
        if ( ! self::should_show_wizard() ) {
            return;
        }

        // Redirect to wizard.
        wp_safe_redirect( admin_url( 'admin.php?page=' . self::WIZARD_SLUG ) );
        exit;
    }

    /**
     * Register wizard page
     *
     * @since 1.0.0
     * @return void
     */
    public function register_wizard_page() {
        // Only register if wizard should be shown.
        if ( ! self::should_show_wizard() ) {
            return;
        }

        add_submenu_page(
            '',  // No parent menu (hidden from sidebar).
            __( 'StoreAgent Onboarding', 'storeagent-ai-for-woocommerce' ),
            __( 'Onboarding', 'storeagent-ai-for-woocommerce' ),
            'manage_options',
            self::WIZARD_SLUG,
            array( $this, 'render_wizard_page' )
        );
    }

    /**
     * Render wizard page
     *
     * @since 1.0.0
     * @return void
     */
    public function render_wizard_page() {
        require_once SAAI_PLUGIN_DIR_PATH . 'templates/admin/onboarding-wizard.php';
    }

    /**
     * Enqueue wizard scripts
     *
     * @since 1.0.0
     * @return void
     */
    public function enqueue_wizard_scripts() {
        $current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

        // Only load on wizard page.
        if ( self::WIZARD_SLUG !== $current_page ) {
            return;
        }

        // Enqueue our fonts.
        wp_enqueue_style(
            'storeagent-fonts',
            plugins_url( 'static/fonts/fonts.css', SAAI_PLUGIN_FILE ),
            array(),
            filemtime( SAAI_PLUGIN_DIR_PATH . 'static/fonts/fonts.css' )
        );

        $wizard_base_url_args = array( 'page' => self::WIZARD_SLUG );
        if ( defined( 'HMR_DEV' ) && 'saai' === HMR_DEV ) {
            $wizard_base_url_args['hmr'] = HMR_DEV;
        }

        $l10n = Helper::vite_app_common_l10n(
            array(
                'isConnected'              => Connect::is_connected(),
                'connectUrl'               => esc_url_raw( Connect::get_url() ),
                'restUrl'                  => esc_url_raw( rest_url() ),
                'wpNonce'                  => wp_create_nonce( 'wp_rest' ),
                'wcNonce'                  => wp_create_nonce( 'wc_store_api' ),
                'ajaxUrl'                  => esc_url_raw( admin_url( 'admin-ajax.php' ) ),
                'chatSetupNonce'           => wp_create_nonce( 'saai-start-chat-setup' ),
                'adminBaseUrl'             => esc_url_raw(
                    add_query_arg( array( 'page' => Admin_Menu_Handler::PARENT_SLUG ), admin_url( 'admin.php', 'relative' ) )
                ),
                'wizardBaseUrl'            => esc_url_raw(
                    add_query_arg( $wizard_base_url_args, admin_url( 'admin.php', 'relative' ) )
                ),
                'aiAgents'                 => Helper::get_ai_agent_modules_with_settings(),
                'dataOptions'              => Helper::get_data_options(),
                'chatDefaultSettings'      => \SAAI\REST\Chat\Chat_Widget_Settings::get_default_settings(),
                'chatPostTypesAndSettings' => Helper::get_chat_post_types_and_settings(),
                'plansUrl'                 => esc_url_raw( Helper::get_utm_url( 'plans', 'saai', 'onboarding', 'chooseyourplan', 'https://app.storeagent.ai/' ) ),
            )
        );

        $l10n['allowedTags']  = array_merge( $l10n['allowedTags'], array( 'iframe', 'svg', 'path' ) );
        $l10n['allowedAttrs'] = array_merge( $l10n['allowedAttrs'], array( 'viewBox', 'fill', 'xmlns', 'd' ) );

        $app = new Vite_App(
            self::WIZARD_SLUG,
            'src/apps/admin/storeagent-onboarding/index.ts',
            array(
                'wp-i18n',
                'wp-url',
                'wp-hooks',
                'wp-html-entities',
                'lodash',
            ),
            $l10n,
            'saaiObj',
            array( 'storeagent-fonts' )
        );

        $app->enqueue();
    }

    /**
     * Initialize hooks
     *
     * @since 1.0.0
     * @return void
     */
    public function init() {
        add_action( 'admin_menu', array( $this, 'register_wizard_page' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_wizard_scripts' ) );
        add_action( 'admin_init', array( $this, 'maybe_redirect_to_wizard' ), 5 );
    }

    /**
     * Run the class.
     *
     * @since 1.0.0
     * @return void
     */
    public function run() {
        $this->init();
    }
}
