<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Main plugin bootstrap class.
 * Initializes all services and registers their hooks with WordPress.
 */
class EEP_Plugin_Bootstrap {

    /**
     * @var array Holds all instantiated services.
     */
    private $services = [];

    /**
     * @var string The main post type slug.
     */
    private $post_type = 'nexdirectory_event';

    /**
     * Initializes the plugin, loads services, and registers hooks.
     */
    public function run() {
        $this->instantiate_services();
        $this->register_hooks();
    }

    /**
     * Wires up the Dependency Injection container.
     */
    private function instantiate_services() {
        $chatbot_table = 'eep_event_embeddings';

        // 1. Independent Services
        $this->services['logger']    = new EEP_Runtime_Log_Service();
        $this->services['date']      = new EEP_Date_Helper();
        $this->services['user_caps'] = new EEP_User_Capabilities($this->post_type);
        $this->services['taxonomy']  = new EEP_Taxonomy_Service();
        $this->services['nav']       = new EEP_Frontend_Navigation_Service($this->post_type);
        $this->services['analytics'] = new EEP_Analytics_Service($this->post_type, $this->services['logger']);

        // 2. Base Helpers
        $this->services['media']      = new EEP_Media_Helper($this->services['user_caps']);
        $this->services['event_meta'] = new EEP_Event_Meta_Service($this->services['user_caps'], $this->services['date'], $this->services['media']);
        $this->services['email']      = new EEP_Email_Service($this->services['date'], $this->services['logger']);
        
        // 3. UI, Imports & Notifications
        $this->services['spa']        = new EEP_SPA_Service($this->services['nav']);
        $this->services['admin_ui']   = new EEP_Admin_UI_Service($this->post_type, $this->services['user_caps'], $this->services['event_meta'], $this->services['nav']);
        $this->services['importer']   = new EEP_Import_Service($this->post_type, $this->services['date'], $this->services['event_meta'], $this->services['taxonomy'], $this->services['user_caps']);
        $this->services['notifier']   = new EEP_Notification_Service($this->services['email'], $this->services['date']);

        // 4. Chatbot Ecosystem (Resolving circular dependencies safely)
        $this->services['chatbot_ranking']   = new EEP_Chatbot_Ranking_Service(null); // Will inject knowledge service later
        $this->services['chatbot_state']     = new EEP_Chatbot_State_Service($this->services['chatbot_ranking']);
        $this->services['chatbot']           = new EEP_Chatbot_Service(null, $this->services['chatbot_ranking'], $this->services['chatbot_state'], $this->services['media'], $this->services['date'], $this->services['logger']);
        $this->services['chatbot_knowledge'] = new EEP_Chatbot_Knowledge_Service($this->post_type, $chatbot_table, $this->services['chatbot'], $this->services['chatbot_ranking'], $this->services['event_meta'], $this->services['logger']);
        
        // Late Bindings for Chatbot
        if (method_exists($this->services['chatbot_ranking'], 'set_knowledge_service')) {
            $this->services['chatbot_ranking']->set_knowledge_service($this->services['chatbot_knowledge']);
        }
        if (method_exists($this->services['chatbot'], 'set_knowledge_service')) {
            $this->services['chatbot']->set_knowledge_service($this->services['chatbot_knowledge']);
        }
    }

    /**
     * Maps service methods to WordPress actions and filters.
     */
    private function register_hooks() {
        
        // --- 1. Runtime Logger ---
        register_shutdown_function([$this->services['logger'], 'capture_fatal_error']);
        add_action('admin_post_eep_clear_logs', [$this->services['logger'], 'handle_clear_logs']);

        // --- 1.1 Demo Lock Enforcement ---
        add_filter('map_meta_cap', [$this->services['user_caps'], 'filter_map_meta_cap_for_demo_lock'], 20, 4);
        add_action('pre_post_update', [$this->services['user_caps'], 'action_block_locked_demo_pre_post_update'], 10, 2);
        add_filter('pre_trash_post', [$this->services['user_caps'], 'filter_pre_trash_post_for_demo_lock'], 10, 3);
        add_filter('pre_delete_post', [$this->services['user_caps'], 'filter_pre_delete_post_for_demo_lock'], 10, 3);

        // --- 2. Admin UI Service ---
        add_filter('show_admin_bar', [$this->services['admin_ui'], 'filter_show_admin_bar_for_submitter'], 999);
        add_action('admin_init', [$this->services['admin_ui'], 'enforce_submitter_dashboard_lockout']);
        
        // Admin List View overrides
        add_filter('get_edit_post_link', [$this->services['admin_ui'], 'filter_admin_event_edit_link'], 10, 3);
        add_action('admin_bar_menu', [$this->services['admin_ui'], 'add_demo_limit_admin_bar_node'], 190);
        add_action('admin_bar_menu', [$this->services['admin_ui'], 'replace_admin_bar_event_edit_link'], 999);
        add_filter('post_row_actions', [$this->services['admin_ui'], 'filter_admin_event_row_actions'], 10, 2);
        add_action('admin_action_eep_duplicate_event', [$this->services['admin_ui'], 'handle_admin_duplicate_event']);
        
        // Admin Table UI enforcement
        add_action('load-edit.php', [$this->services['admin_ui'], 'enforce_admin_event_list_mode']);
        add_action('admin_head-edit.php', [$this->services['admin_ui'], 'hide_admin_event_list_descriptions']);
        add_action('load-post.php', [$this->services['admin_ui'], 'maybe_redirect_admin_event_editor']);

        // Custom Columns (Official Classification)
        add_filter("manage_{$this->post_type}_posts_columns", [$this->services['admin_ui'], 'add_admin_official_classification_column']);
        add_action("manage_{$this->post_type}_posts_custom_column", [$this->services['admin_ui'], 'render_admin_official_classification_column'], 10, 2);
        
        // Bulk/Quick Edit hooks
        add_action('bulk_edit_custom_box', [$this->services['admin_ui'], 'render_bulk_edit_official_field'], 10, 2);
        add_action('quick_edit_custom_box', [$this->services['admin_ui'], 'render_bulk_edit_official_field'], 10, 2);
        add_action('save_post', [$this->services['admin_ui'], 'handle_bulk_edit_official_field_save'], 10, 3);

        // --- 3. Frontend Navigation Service ---
        add_filter('login_url', [$this->services['nav'], 'filter_wp_login_url'], 10, 3);
        add_action('login_init', [$this->services['nav'], 'maybe_redirect_wp_login_screen']);
        add_filter('body_class', [$this->services['nav'], 'filter_body_class_for_plugin_pages']);
        add_action('wp_enqueue_scripts', [$this->services['nav'], 'enqueue_app_page_assets'], 11);
        add_filter('template_include', [$this->services['nav'], 'filter_template_include_for_app_pages'], 999);
        add_filter('post_thumbnail_html', [$this->services['nav'], 'filter_platform_featured_image_html'], 20, 5);
        add_action('wp_head', [$this->services['nav'], 'output_plugin_page_theme_override_css'], 99);
        add_filter('comments_open', [$this->services['nav'], 'filter_comments_open_for_plugin_pages'], 20, 2);
        if (is_callable([$this->services['nav'], 'output_frontend_auth_links_global'])) {
            add_action('wp_footer', [$this->services['nav'], 'output_frontend_auth_links_global']);
        }

        // --- 4. Email & Notification Services ---
        add_action('phpmailer_init', [$this->services['email'], 'configure_phpmailer'], 999);
        // Note: Author/Admin notification methods (notify_author_status, notify_admin_submission) 
        // should be hooked into your post transition hooks (e.g., transition_post_status) wherever you handle save logic.

        // --- 5. Chatbot Cron ---
        add_action('eep_chatbot_reindex_cron', [$this->services['chatbot_knowledge'], 'run_chatbot_reindex_cron']);
        add_action('eep_chatbot_daily_reindex', [$this->services['chatbot_knowledge'], 'run_chatbot_reindex_cron']);
    }

    /**
     * Returns a specific service instance (useful if other files need to call a service).
     */
    public function get_service($key) {
        return $this->services[$key] ?? null;
    }
}
