<?php
/**
 * Autoloader for BoostBot classes.
 *
 * @package BoostBot
 * @since   1.0.0
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class BoostBot_Autoloader
 *
 * Handles automatic loading of plugin classes.
 *
 * @since 1.0.0
 */
class BoostBot_Autoloader {

    /**
     * Class mapping for special cases.
     *
     * @var array
     */
    private static $class_map = array(
        // Core classes
        'BoostBot'              => 'includes/class-boostbot.php',
        'BoostBot_Loader'       => 'includes/class-loader.php',
        'BoostBot_Activator'    => 'includes/class-activator.php',
        'BoostBot_Deactivator'  => 'includes/class-deactivator.php',

        // Database classes
        'BoostBot_DB_Manager'              => 'includes/database/class-db-manager.php',
        'BoostBot_Base_Model'              => 'includes/database/class-base-model.php',
        'BoostBot_Localizable'             => 'includes/database/trait-localizable.php',
        'BoostBot_Lead_Model'              => 'includes/database/class-lead-model.php',
        'BoostBot_Conversation_Model'      => 'includes/database/class-conversation-model.php',
        'BoostBot_Bot_Model'               => 'includes/database/class-bot-model.php',
        'BoostBot_Personality_Model'       => 'includes/database/class-personality-model.php',
        'BoostBot_Personality_Trait_Model' => 'includes/database/class-personality-trait-model.php',
        'BoostBot_Tone_Model'              => 'includes/database/class-tone-model.php',
        'BoostBot_Contact_List_Model'      => 'includes/database/class-contact-list-model.php',
        'BoostBot_Contact_Model'           => 'includes/database/class-contact-model.php',
        'BoostBot_Widget_Model'            => 'includes/database/class-widget-model.php',
        'BoostBot_Form_Field_Model'        => 'includes/database/class-form-field-model.php',
        'BoostBot_Gallery_Model'             => 'includes/database/class-gallery-model.php',
        'BoostBot_Appearance_Preset_Model'   => 'includes/database/class-appearance-preset-model.php',
        'BoostBot_Opening_Screen_Preset_Model' => 'includes/database/class-opening-screen-preset-model.php',
        'BoostBot_Meeting_Model'             => 'includes/database/class-meeting-model.php',
        'BoostBot_Bundle_Model'              => 'includes/database/class-bundle-model.php',

        // Utility classes
        'BoostBot_Logger'       => 'includes/utilities/class-logger.php',
        'BoostBot_Validator'    => 'includes/utilities/class-validator.php',
        'BoostBot_Sanitizer'    => 'includes/utilities/class-sanitizer.php',
        'BoostBot_Settings'     => 'includes/utilities/class-settings.php',
        'BoostBot_Language'        => 'includes/utilities/class-language.php',
        'BoostBot_Prompt_Strings'  => 'includes/utilities/class-prompt-strings.php',

        // API classes (Week 2)
        'BoostBot_API_Manager'            => 'includes/api/class-api-manager.php',
        'BoostBot_Base_Endpoint'          => 'includes/api/class-base-endpoint.php',
        'BoostBot_Chat_Endpoint'          => 'includes/api/class-chat-endpoint.php',
        'BoostBot_Config_Endpoint'        => 'includes/api/class-config-endpoint.php',
        'BoostBot_Credits_Endpoint'       => 'includes/api/class-credits-endpoint.php',
        'BoostBot_Indexing_Credits_Endpoint' => 'includes/api/class-indexing-credits-endpoint.php',
        'BoostBot_Pricing_Endpoint'       => 'includes/api/class-pricing-endpoint.php',
        'BoostBot_Purchases_Endpoint'     => 'includes/api/class-purchases-endpoint.php',
        'BoostBot_Subscriptions_Endpoint' => 'includes/api/class-subscriptions-endpoint.php',
        'BoostBot_Migration_Endpoint'     => 'includes/api/class-migration-endpoint.php',
        'BoostBot_Widget_Endpoint'        => 'includes/api/class-widget-endpoint.php',
        'BoostBot_Leads_Endpoint'         => 'includes/api/class-leads-endpoint.php',
        'BoostBot_Conversations_Endpoint' => 'includes/api/class-conversations-endpoint.php',
        'BoostBot_Settings_Endpoint'      => 'includes/api/class-settings-endpoint.php',
        'BoostBot_Analytics_Endpoint'     => 'includes/api/class-analytics-endpoint.php',
        'BoostBot_Export_Endpoint'        => 'includes/api/class-export-endpoint.php',
        'BoostBot_Index_Endpoint'         => 'includes/api/class-index-endpoint.php',
        'BoostBot_License_Endpoint'       => 'includes/api/class-license-endpoint.php',
        'BoostBot_WooCommerce_Endpoint'   => 'includes/api/class-woocommerce-endpoint.php',
        'BoostBot_Feedback_Endpoint'      => 'includes/api/class-feedback-endpoint.php',
        'BoostBot_CRM_Export_Endpoint'    => 'includes/api/class-crm-export-endpoint.php',
        'BoostBot_Bots_Endpoint'          => 'includes/api/class-bots-endpoint.php',
        'BoostBot_Personalities_Endpoint' => 'includes/api/class-personalities-endpoint.php',
        'BoostBot_Contact_Lists_Endpoint' => 'includes/api/class-contact-lists-endpoint.php',
        'BoostBot_Widgets_Endpoint'       => 'includes/api/class-widgets-endpoint.php',
        'BoostBot_Tones_Endpoint'               => 'includes/api/class-tones-endpoint.php',
        'BoostBot_Appearance_Presets_Endpoint'  => 'includes/api/class-appearance-presets-endpoint.php',
        'BoostBot_Usage_Endpoint'               => 'includes/api/class-usage-endpoint.php',
        'BoostBot_Google_Endpoint'              => 'includes/api/class-google-endpoint.php',
        'BoostBot_Meetings_Endpoint'            => 'includes/api/class-meetings-endpoint.php',
        'BoostBot_Opening_Screen_Endpoint'      => 'includes/api/class-opening-screen-endpoint.php',
        'BoostBot_Opening_Screen_Presets_Endpoint' => 'includes/api/class-opening-screen-presets-endpoint.php',
        // BoostBot_Files_Endpoint archived — see boostbot/_archive/files-endpoint/
        'BoostBot_Brand_Card_Endpoint'         => 'includes/api/class-brand-card-endpoint.php',
        'BoostBot_Session_Endpoint'            => 'includes/api/class-session-endpoint.php',
        'BoostBot_Retrieval_Endpoint'          => 'includes/api/class-retrieval-endpoint.php',
        'BoostBot_Widget_Analyzer_Endpoint'    => 'includes/api/class-widget-analyzer-endpoint.php',
        'BoostBot_Languages_Endpoint'          => 'includes/api/class-languages-endpoint.php',
        'BoostBot_Support_Endpoint'            => 'includes/api/class-support-endpoint.php',
        'BoostBot_Alerts_Endpoint'             => 'includes/api/class-alerts-endpoint.php',
        'BoostBot_External_KB_Keys'            => 'includes/api/class-external-kb-keys.php',
        'BoostBot_External_KB_Endpoint'        => 'includes/api/class-external-kb-endpoint.php',

        // Security classes (Week 2)
        'BoostBot_Rate_Limiter'     => 'includes/security/class-rate-limiter.php',
        'BoostBot_Message_Limiter'  => 'includes/security/class-message-limiter.php',
        'BoostBot_Input_Validator'  => 'includes/security/class-input-validator.php',
        'BoostBot_Usage_Tracker'    => 'includes/security/class-usage-tracker.php',

        // Licensing classes (Week 2 + Week 19)
        'BoostBot_License_Manager'       => 'includes/licensing/class-license-manager.php',
        'BoostBot_PayPal_Handler'        => 'includes/licensing/class-paypal-handler.php',
        'BoostBot_PayPal_API'            => 'includes/licensing/class-paypal-api.php',

        // Internationalization (Week 2.5)
        'BoostBot_i18n'            => 'includes/class-i18n.php',

        // Public (Frontend Widget)
        // BoostBot_Public archived — see boostbot/_archive/legacy-public-class/

        // Multilingual
        'BoostBot_Language_Manager'  => 'includes/class-language-manager.php',

        // Bot Resolution (Week 10.7)
        'BoostBot_Bot_Resolver'      => 'includes/class-bot-resolver.php',
        'BoostBot_Content_Extractor' => 'includes/class-content-extractor.php',

        // AI classes (Week 5)
        'BoostBot_Claude_Client'    => 'includes/ai/class-claude-client.php',
        'BoostBot_Gemini_Client'    => 'includes/ai/class-gemini-client.php',
        'BoostBot_Backend_AI_Client'=> 'includes/ai/class-backend-ai-client.php',
        'BoostBot_Prompt_Builder'   => 'includes/ai/class-prompt-builder.php',
        'BoostBot_Chat_Handler'    => 'includes/ai/class-chat-handler.php',

        // Service classes (Week 10.10)
        'BoostBot_WooCommerce_Coupon_Service' => 'includes/services/class-woocommerce-coupon-service.php',
        'BoostBot_CRM_Webhook_Service'        => 'includes/services/class-crm-webhook-service.php',
        'BoostBot_Google_Calendar_Service'    => 'includes/services/class-google-calendar-service.php',
        'BoostBot_Contact_Extractor'          => 'includes/services/class-contact-extractor.php',
        'BoostBot_Bundle_Builder_Service'     => 'includes/services/class-bundle-builder-service.php',
        'BoostBot_Credits_Backend_Client'     => 'includes/services/class-credits-backend-client.php',
        'BoostBot_Low_Credits_Monitor'        => 'includes/services/class-low-credits-monitor.php',
        'BoostBot_Registration_Monitor'       => 'includes/services/class-registration-monitor.php',
        'BoostBot_Spam_Alert_Monitor'         => 'includes/services/class-spam-alert-monitor.php',
        'BoostBot_Indexing_Credits_Backend_Client' => 'includes/services/class-indexing-credits-backend-client.php',
        'BoostBot_Indexing_Backend_Client'    => 'includes/services/class-indexing-backend-client.php',
        
        // Bundle Builder Services (Week 20 Enhancement)
        'BoostBot_Bundle_Product_Selector'    => 'includes/services/class-bundle-product-selector.php',
        'BoostBot_Bundle_Discount_Calculator' => 'includes/services/class-bundle-discount-calculator.php',
        'BoostBot_Bundle_Coupon_Service'      => 'includes/services/class-bundle-coupon-service.php',

        // WooCommerce Widget Manager (auto-managed widgets)
        'BoostBot_WooCommerce_Widget_Manager' => 'includes/services/class-woocommerce-widget-manager.php',

        // Knowledge Base classes (Week 6)
        'BoostBot_Site_Scanner'        => 'includes/knowledge/class-site-scanner.php',
        'BoostBot_Content_Processor'   => 'includes/knowledge/class-content-processor.php',
        'BoostBot_Embedding_Generator' => 'includes/knowledge/class-embedding-generator.php',
        'BoostBot_Knowledge_Index'     => 'includes/knowledge/class-knowledge-index.php',
        'BoostBot_Index_Job'           => 'includes/knowledge/class-index-job.php',
        'BoostBot_Background_Indexer'  => 'includes/knowledge/class-background-indexer.php',
        'BoostBot_Index_Rules'         => 'includes/knowledge/class-index-rules.php',

        // Content Extraction classes (Week 10.11)
        'BoostBot_Elementor_Parser'    => 'includes/content/class-elementor-parser.php',
        'BoostBot_Specs_Extractor'     => 'includes/content/class-specs-extractor.php',
        'BoostBot_Price_Extractor'     => 'includes/content/class-price-extractor.php',

        // Widget classes (Week 7)
        'BoostBot_Widget_Manager'       => 'includes/widgets/class-widget-manager.php',
        'BoostBot_Widget_Base'          => 'includes/widgets/class-widget-base.php',
        'BoostBot_Lead_Form_Widget'     => 'includes/widgets/class-lead-form-widget.php',
        'BoostBot_Contact_Card_Widget' => 'includes/widgets/class-contact-card-widget.php',
        'BoostBot_Product_Card_Widget'  => 'includes/widgets/class-product-card-widget.php',
        'BoostBot_Calendar_Widget'      => 'includes/widgets/class-calendar-widget.php',
        'BoostBot_Survey_Widget'          => 'includes/widgets/class-survey-widget.php',
        'BoostBot_Opening_Screen_Widget'  => 'includes/widgets/class-opening-screen-widget.php',
        'BoostBot_Bundle_Builder_Widget'  => 'includes/widgets/class-bundle-builder-widget.php',

        // WooCommerce Integration classes (Week 8)
        'BoostBot_WooCommerce_Service'  => 'includes/integrations/class-woocommerce-service.php',
        'BoostBot_Product_Recommender'  => 'includes/integrations/class-product-recommender.php',
        'BoostBot_Order_Service'        => 'includes/integrations/class-order-service.php',

        // Helper classes
        'BoostBot_Polylang_Context'     => 'includes/helpers/class-polylang-context.php',
    );

    /**
     * Register the autoloader.
     *
     * @return void
     */
    public static function init() {
        spl_autoload_register( array( __CLASS__, 'autoload' ) );
    }

    /**
     * Autoload a class file.
     *
     * @param string $class_name The name of the class to load.
     * @return void
     */
    public static function autoload( $class_name ) {
        // Handle namespaced BoostBot classes (e.g., BoostBot\Templates\Template_Manager)
        if ( strpos( $class_name, 'BoostBot\\' ) === 0 ) {
            $file = self::get_namespaced_file_path( $class_name );
            if ( $file && file_exists( $file ) ) {
                require_once $file;
            }
            return;
        }

        // Only handle BoostBot_ prefixed classes
        if ( strpos( $class_name, 'BoostBot' ) !== 0 ) {
            return;
        }

        // Check class map first
        if ( isset( self::$class_map[ $class_name ] ) ) {
            $file = BOOSTBOT_PLUGIN_DIR . self::$class_map[ $class_name ];
            if ( file_exists( $file ) ) {
                require_once $file;
                return;
            }
        }

        // Try to auto-resolve the file path
        $file = self::get_file_path( $class_name );
        if ( $file && file_exists( $file ) ) {
            require_once $file;
        }
    }

    /**
     * Convert a class name to a file path.
     *
     * @param string $class_name The class name.
     * @return string|false The file path or false if not found.
     */
    private static function get_file_path( $class_name ) {
        // Remove 'BoostBot_' prefix
        $class_name = str_replace( 'BoostBot_', '', $class_name );

        // Convert to lowercase and replace underscores with hyphens
        $file_name = 'class-' . strtolower( str_replace( '_', '-', $class_name ) ) . '.php';

        // Define possible directories
        $directories = array(
            BOOSTBOT_PLUGIN_DIR . 'includes/',
            BOOSTBOT_PLUGIN_DIR . 'includes/admin/',
            BOOSTBOT_PLUGIN_DIR . 'includes/api/',
            BOOSTBOT_PLUGIN_DIR . 'includes/ai/',
            BOOSTBOT_PLUGIN_DIR . 'includes/knowledge/',
            BOOSTBOT_PLUGIN_DIR . 'includes/conversation/',
            BOOSTBOT_PLUGIN_DIR . 'includes/widgets/',
            BOOSTBOT_PLUGIN_DIR . 'includes/integrations/',
            BOOSTBOT_PLUGIN_DIR . 'includes/database/',
            BOOSTBOT_PLUGIN_DIR . 'includes/utilities/',
            BOOSTBOT_PLUGIN_DIR . 'includes/licensing/',
            BOOSTBOT_PLUGIN_DIR . 'includes/security/',
            BOOSTBOT_PLUGIN_DIR . 'includes/services/',
            BOOSTBOT_PLUGIN_DIR . 'includes/helpers/',
        );

        // Search for the file
        foreach ( $directories as $directory ) {
            $file_path = $directory . $file_name;
            if ( file_exists( $file_path ) ) {
                return $file_path;
            }
        }

        return false;
    }

    /**
     * Get all registered classes.
     *
     * @return array
     */
    public static function get_class_map() {
        return self::$class_map;
    }

    /**
     * Convert a namespaced class to a file path.
     *
     * Handles classes like BoostBot\Templates\Template_Manager
     *
     * @param string $class_name The full namespaced class name.
     * @return string|false The file path or false if not found.
     */
    private static function get_namespaced_file_path( $class_name ) {
        // Remove BoostBot\ prefix
        $relative = str_replace( 'BoostBot\\', '', $class_name );

        // Split into namespace parts and class name
        $parts = explode( '\\', $relative );
        $class = array_pop( $parts );

        // Convert namespace to directory path
        $namespace_path = '';
        foreach ( $parts as $part ) {
            $namespace_path .= strtolower( str_replace( '_', '-', $part ) ) . '/';
        }

        // Convert class name to file name
        $file_name = 'class-' . strtolower( str_replace( '_', '-', $class ) ) . '.php';

        // Build full path
        $file_path = BOOSTBOT_PLUGIN_DIR . 'includes/' . $namespace_path . $file_name;

        return file_exists( $file_path ) ? $file_path : false;
    }
}

