<?php
/**
 * Admin Menu Handler
 *
 * @package SAAI\Classes
 */

namespace SAAI\Classes;

use SAAI\Helpers\Connect;
use SAAI\Helpers\Helper;
use SAAI\Factories\Vite_App;
use SAAI\Factories\Admin_Notice;
use SAAI\Traits\Singleton_Trait;
use SAAI\Classes\Notification;
use SAAI\Classes\Plan_Manager;
use SAAI\Classes\Chat\Chat_Widget;
use SAAI\Classes\Onboarding_Wizard;
use SAAI\AI_Agents\Advanced_Coupons\Coupon_Generator_AI;
use SAAI\Integrations\Wholesale_Suite;

/**
 * Admin_Menu_Handler class - centralized menu registration
 *
 * @since 1.0.0
 */
class Admin_Menu_Handler {

    use Singleton_Trait;

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

    /**
     * Main parent menu slug and dashboard page slug
     *
     * @since 1.0.0
     */
    public const PARENT_SLUG = 'storeagent-dashboard';

    /**
     * Original parent menu slug - kept for backward compatibility
     *
     * @since 1.0.0
     */
    public const LEGACY_PARENT_SLUG = 'storeagent';

    /**
     * Settings page slug
     *
     * @since 1.0.0
     */
    public const SETTINGS_SLUG = 'storeagent-settings';

    /**
     * Agents page slug
     *
     * @since 1.0.0
     */
    public const AGENTS_SLUG = 'storeagent-agents';

    /**
     * Register admin menu
     *
     * @since 1.0.0
     * @return void
     */
    public function register_menus() {
        // Register main menu with Dashboard as the default page.
        add_menu_page(
            __( 'StoreAgent', 'storeagent-ai-for-woocommerce' ),
            __( 'StoreAgent', 'storeagent-ai-for-woocommerce' ),
            'manage_options',
            self::PARENT_SLUG,
            array( $this, 'render_dashboard_page' ),
            'dashicons-analytics',
            56
        );

        // Register Dashboard submenu explicitly to ensure it shows as Dashboard.
        add_submenu_page(
            self::PARENT_SLUG,
            __( 'Dashboard', 'storeagent-ai-for-woocommerce' ),
            __( 'Dashboard', 'storeagent-ai-for-woocommerce' ),
            'manage_options',
            self::PARENT_SLUG,
            array( $this, 'render_dashboard_page' )
        );

        // Only add these menu items if connected to StoreAgent and onboarding is complete.
        if ( Connect::is_connected() && ! Onboarding_Wizard::should_show_wizard() ) {
            // Register Settings submenu.
            add_submenu_page(
                self::PARENT_SLUG,
                __( 'Settings', 'storeagent-ai-for-woocommerce' ),
                __( 'Settings', 'storeagent-ai-for-woocommerce' ),
                'manage_options',
                self::SETTINGS_SLUG,
                array( $this, 'render_settings_page' )
            );
        }
    }

    /**
     * Enqueue chat widget script for settings page preview.
     *
     * @since 1.0.0
     * @return void
     */
    public function enqueue_chat_widget_script() {
        $current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

        if ( self::SETTINGS_SLUG !== $current_page ) {
            return;
        }

        $chat_widget = Chat_Widget::instance();
        $script_url  = $chat_widget->get_chat_widget_script_url();

        echo '<script type="module" src="' . esc_url_raw( $script_url ) . '"></script>'; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
    }

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

        // Only load on our pages.
        if ( ! in_array(
            $current_page,
            array(
                self::LEGACY_PARENT_SLUG,
                self::PARENT_SLUG,
                self::SETTINGS_SLUG,
                self::AGENTS_SLUG,
            ),
            true
        ) ) {
            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' )
        );

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

        // Get current plan name for frontend.
        $plan_data    = Plan_Manager::instance()->get_plan_data();
        $current_plan = ! empty( $plan_data['plan_name'] ) ? strtolower( $plan_data['plan_name'] ) : 'lite';

        // Check if WC Vendors plugin is active.
        $is_wc_vendors_active = false;

        // First check if WC Vendors class/function exists (more reliable).
        if ( class_exists( 'WC_Vendors' ) || function_exists( 'WCV_Vendors' ) || class_exists( 'WCV_Vendors' ) ) {
            $is_wc_vendors_active = true;
        } else {
            // Fallback to plugin check.
            if ( ! function_exists( 'is_plugin_active' ) ) {
                require_once ABSPATH . 'wp-admin/includes/plugin.php';
            }
            if ( function_exists( 'is_plugin_active' ) ) {
                $is_wc_vendors_active = is_plugin_active( 'wc-vendors/wc-vendors.php' );
            }
        }

        // Check if Wholesale Suite plugin is active.
        $is_wholesale_suite_active = Wholesale_Suite::is_wwp_active();

        // Check if Advanced Coupons plugins are active.
        $coupon_agent    = Coupon_Generator_AI::instance();
        $is_acfw_active  = $coupon_agent->is_acfw_active();
        $is_acfwp_active = $coupon_agent->is_acfwp_active();

        $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' ),
                'newAccountUrl'            => esc_url_raw( Helper::get_utm_url( 'refer-a-friend', 'saai', 'free-credits', 'claimfreecredits', 'https://app.storeagent.ai/' ) ),
                'viewAccountUrl'           => esc_url_raw( Helper::get_utm_url( 'my-account', 'saai', 'clientsite', 'viewaccount', 'https://app.storeagent.ai/' ) ),
                'upgradeUrl'               => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'chat-escalation', 'upgrade' ) ),
                'featureGateUrls'          => array(
                    'supportEscalation' => array(
                        'upgrade' => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'feature-gate-modal', 'upgrade-support-escalation' ) ),
                        'compare' => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'feature-gate-modal', 'compare-plans-support-escalation' ) ),
                    ),
                    'chatHistory'       => array(
                        'upgrade' => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'feature-gate-modal', 'upgrade-chat-history' ) ),
                        'compare' => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'feature-gate-modal', 'compare-plans-chat-history' ) ),
                    ),
                    'exportChatLogs'    => array(
                        'upgrade' => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'feature-gate-modal', 'upgrade-export-chat-logs' ) ),
                        'compare' => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'feature-gate-modal', 'compare-plans-export-chat-logs' ) ),
                    ),
                ),
                'adminBaseUrl'             => esc_url_raw(
                    add_query_arg( $admin_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(),
                'currentPlan'              => $current_plan,
                'usageData'                => Plan_Manager::instance()->get_highest_usage_resource(),
                'usageBarUpgradeUrl'       => esc_url_raw( Helper::get_utm_url( 'pricing', 'saai', 'usage-bar', 'upgrade' ) ),
                'isWcVendorsActive'        => $is_wc_vendors_active,
                'isWholesaleSuiteActive'   => $is_wholesale_suite_active,
                'isAcfwActive'             => $is_acfw_active,
                'isAcfwpActive'            => $is_acfwp_active,
            )
        );

        $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::PARENT_SLUG,
            'src/apps/admin/storeagent-admin/index.ts',
            array(
                'wp-i18n',
                'wp-url',
                'wp-hooks',
                'wp-html-entities',
                'lodash',
            ),
            $l10n,
            'saaiObj',
            array( 'storeagent-fonts' )
        );

        $app->enqueue();

        // Enqueue chat widget script on settings page for preview.
        if ( self::SETTINGS_SLUG === $current_page ) {
            $this->enqueue_chat_widget_script();
        }
    }

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

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

    /**
     * Highlight active admin menu
     *
     * @param string $parent_file Parent file.
     * @return string
     */
    public function highlight_active_admin_menu( $parent_file ) {
        global $submenu_file, $pagenow;

        $current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

        // Only process our pages.
        if ( 'admin.php' === $pagenow && in_array(
            $current_page,
            array(
                self::LEGACY_PARENT_SLUG,
                self::PARENT_SLUG,
                self::SETTINGS_SLUG,
                self::AGENTS_SLUG,
            ),
            true
        ) ) {
            // Handle legacy menu slug redirection.
            if ( self::LEGACY_PARENT_SLUG === $current_page ) {
                wp_safe_redirect( admin_url( 'admin.php?page=' . self::PARENT_SLUG ) );
                exit;
            }

            $submenu_file = $current_page; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
            $parent_file  = self::PARENT_SLUG;
        }

        return $parent_file;
    }

    /**
     * Handle admin notices for StoreAgent
     *
     * @since 1.0.0
     * @return void
     */
    public function handle_admin_notices() {
        global $pagenow;

        if ( 'admin.php' !== $pagenow ) {
            return;
        }

        $current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

        // Only for our pages.
        if ( ! in_array(
            $current_page,
            array(
                self::LEGACY_PARENT_SLUG,
                self::PARENT_SLUG,
                self::SETTINGS_SLUG,
                self::AGENTS_SLUG,
            ),
            true
        ) ) {
            return;
        }

        // Remove default notices.
        remove_all_actions( 'admin_notices' );
        remove_all_actions( 'all_admin_notices' );

        // Check for HTTPS.
        if ( ! is_ssl() ) {
            add_action( 'admin_notices', array( $this, 'show_https_notice' ) );
        }

        // Add our custom notices.
        add_action( 'admin_notices', array( $this, 'show_admin_notices' ) );
    }

    /**
     * Save credentials from auth token.
     *
     * @since 1.0.0
     * @return void
     */
    public function maybe_save_storeagent_credentials() {
        global $pagenow;

        if ( wp_doing_ajax() || 'admin.php' !== $pagenow ) {
            return;
        }

        $definition = array(
            'page'       => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
            'auth_token' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
            'saai_nonce' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
        );

        $query_params = filter_input_array( INPUT_GET, $definition );
        if ( empty( $query_params ) ||
            ( self::PARENT_SLUG !== $query_params['page'] && self::LEGACY_PARENT_SLUG !== $query_params['page'] ) ||
            empty( $query_params['auth_token'] ) ||
            empty( $query_params['saai_nonce'] ) ||
            ! wp_verify_nonce( $query_params['saai_nonce'], 'storeagent-auth' )
        ) {
            return;
        }

        $token_url = Helper::get_storeagent_base_url( 'api' ) . '/storeagent/v1/auth-tokens/' . $query_params['auth_token'];
        $response  = wp_remote_get( $token_url, array( 'headers' => array( 'X-Origin' => wp_parse_url( home_url(), PHP_URL_HOST ) ) ) );

        if ( is_wp_error( $response ) ) {
            $admin_notice = new Admin_Notice( $response->get_error_message() );
            $admin_notice->run();
            return;
        }

        $data        = json_decode( wp_remote_retrieve_body( $response ), true );
        $status_code = wp_remote_retrieve_response_code( $response );

        if ( 200 !== $status_code ) {
            $message      = $data['message'] ?? esc_html__( 'Token auth failed.', 'storeagent-ai-for-woocommerce' );
            $admin_notice = new Admin_Notice( $message );
            $admin_notice->run();
            return;
        }

        [
            'key_id'          => $key_id,
            'consumer_key'    => $consumer_key,
            'consumer_secret' => $consumer_secret,
        ] = $data;

        if ( empty( $key_id ) || empty( $consumer_key ) || empty( $consumer_secret ) ) {
            $consumer_key    = mb_substr( $consumer_key, 0, 7 ) . '...' . mb_substr( $consumer_key, -4 );
            $consumer_secret = mb_substr( $consumer_secret, 0, 7 ) . '...' . mb_substr( $consumer_secret, -4 );
            $message         = sprintf(/* translators: %s = JSON encoded  */
                __( 'Unable to save StoreAgent Auth data due to missing values: %s', 'storeagent-ai-for-woocommerce' ),
                wp_json_encode( compact( 'key_id', 'consumer_key', 'consumer_secret' ) )
            );

            $admin_notice = new Admin_Notice( $message );
            $admin_notice->run();
            return;
        }

        Connect::update_consumer_secret( $consumer_secret );
        Connect::update_consumer_key( $consumer_key );
        Connect::update_consumer_key_id( (int) $key_id );

        wp_safe_redirect( admin_url( 'admin.php?page=' . self::PARENT_SLUG ) );
        exit;
    }

    /**
     * Display HTTPS requirement notice
     *
     * @since 1.0.0
     * @return void
     */
    public function show_https_notice() {
        ?>
        <div class="notice notice-error">
            <p>
                <?php
                printf(
                    /* translators: %1$s = opening <code> tag; %2$s = closing </code> tag */
                    esc_html__( 'StoreAgent AI requires HTTPS to be able to %1$sconnect%2$s to the AI service and work properly.', 'storeagent-ai-for-woocommerce' ),
                    '<code>',
                    '</code>'
                );
                ?>
            </p>
        </div>
        <?php
    }

    /**
     * Show admin notices
     *
     * @since 1.0.0
     * @return void
     */
    public function show_admin_notices() {
        do_action( 'saai_admin_notices' );
    }

    /**
     * Add pending notifications count to the main menu.
     *
     * @since 1.0.0
     * @return void
     */
    public function maybe_add_pending_notifications_count() {
        global $menu;

        // Get the count of pending notifications.
        $count = Notification::instance()->count_all(
            array(
                'status' => array( Notification::STATUS_PENDING ),
            )
        );

        // Only proceed if we have pending notifications.
        if ( $count > 0 ) {
            // Find the StoreAgent AI top level menu item.
            foreach ( $menu as $key => $item ) {
                if ( isset( $item[2] ) && self::PARENT_SLUG === $item[2] ) {
                    // Add the notification bubble to the top level menu.
                    // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
                    $menu[ $key ][0] .= sprintf(
                        ' <span class="awaiting-mod count-%s"><span class="pending-count">%s</span></span>',
                        $count,
                        $count
                    );
                    break;
                }
            }
        }
    }

    /**
     * Redirect to onboarding if user tries to access settings without completing onboarding
     *
     * @since 1.0.0
     * @return void
     */
    public function maybe_redirect_to_onboarding() {
        global $pagenow;

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

        // Get current page.
        $current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

        // Check if we're on a settings page.
        if ( ! in_array( $current_page, array( self::SETTINGS_SLUG, self::AGENTS_SLUG ), true ) ) {
            return;
        }

        // Check if wizard should be shown (connected but onboarding not completed).
        if ( ! Onboarding_Wizard::should_show_wizard() ) {
            return;
        }

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

    /**
     * Initialize hooks
     *
     * @since 1.0.0
     * @return void
     */
    public function init() {
        add_action( 'admin_menu', array( $this, 'register_menus' ) );
        add_action( 'admin_menu', array( $this, 'maybe_add_pending_notifications_count' ), 100 );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'admin_init', array( $this, 'handle_admin_notices' ) );
        add_action( 'admin_init', array( $this, 'maybe_save_storeagent_credentials' ), 1 );
        add_action( 'admin_init', array( $this, 'maybe_redirect_to_onboarding' ), 6 );
        add_filter( 'parent_file', array( $this, 'highlight_active_admin_menu' ) );
        add_action( 'admin_footer', array( $this, 'enqueue_chat_widget_script' ) );
    }

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