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

/**
 * Admin Area Functionality
 *
 * Handles admin menu registration, asset enqueuing, and admin-related functionality.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/admin
 */
class Kitsune_AI_Platform_Admin {

    /**
     * Domain handlers.
     */
    private $settings_admin;
    private $kb_admin;
    private $models_admin;
    private $automation_admin;
    private $integrations_admin;
    private $forms_content_admin;
    private $chatbot_admin;
    private $inbox_analytics_admin;

    /**
     * The plugin name.
     */
    private $plugin_name;

    /**
     * The plugin version.
     */
    private $version;

    /**
     * Initialize the class.
     *
     * @param string $plugin_name Plugin slug.
     * @param string $version Plugin version.
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-settings.php';
        $this->settings_admin = new Kitsune_AI_Platform_Admin_Settings();
        $this->settings_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-knowledge-base.php';
        $this->kb_admin = new Kitsune_AI_Platform_Admin_Knowledge_Base();
        $this->kb_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-models.php';
        $this->models_admin = new Kitsune_AI_Platform_Admin_Models();
        $this->models_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-automation.php';
        $this->automation_admin = new Kitsune_AI_Platform_Admin_Automation();
        $this->automation_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-integrations.php';
        $this->integrations_admin = new Kitsune_AI_Platform_Admin_Integrations();
        $this->integrations_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-forms-content.php';
        $this->forms_content_admin = new Kitsune_AI_Platform_Admin_Forms_Content();
        $this->forms_content_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-chatbot.php';
        $this->chatbot_admin = new Kitsune_AI_Platform_Admin_Chatbot();
        $this->chatbot_admin->register_hooks();

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/class-kitsune-ai-platform-admin-inbox-analytics.php';
        $this->inbox_analytics_admin = new Kitsune_AI_Platform_Admin_Inbox_Analytics();
        $this->inbox_analytics_admin->register_hooks();

        add_action('enqueue_block_editor_assets', array($this, 'enqueue_editor_assets'));
    }

    /**
    * Get user permissions for Kitsune AI Platform.
     */
    public function get_user_permissions() {
        $user = wp_get_current_user();
        $roles = $user->roles;
        $is_admin = in_array('administrator', $roles, true) || is_super_admin();

        $default_perms = array(
            'models'         => false,
            'chatbots'       => false,
            'content'        => false,
            'knowledge_base' => false,
            'automation'     => false,
            'analytics'      => false,
            'integrations'   => false,
            'settings'       => false,
        );

        if ($is_admin) {
            foreach ($default_perms as $key => $val) {
                $default_perms[$key] = true;
            }
            return $default_perms;
        }

        $saved_roles = get_option('kitsune_ai_platform_access_control', array());
        $saved_map = array();
        if (is_array($saved_roles)) {
            foreach ($saved_roles as $row) {
                if (isset($row['slug'])) {
                    $saved_map[$row['slug']] = $row;
                }
            }
        }

        foreach ($roles as $role) {
            if (isset($saved_map[$role])) {
                $perms = $saved_map[$role];
                foreach ($default_perms as $key => $val) {
                    if (!empty($perms[$key])) {
                        $default_perms[$key] = true;
                    }
                }
            }
        }

        return $default_perms;
    }

    /**
     * Register the admin menu.
     * Creates ONE main page for the Vue.js SPA.
     */
    public function add_plugin_admin_menu() {
        $perms = $this->get_user_permissions();
        $has_any_access = in_array(true, $perms, true);

        if (!$has_any_access) {
            return;
        }

        add_menu_page(
            __('Kitsune AI Platform', 'kitsune-ai-platform'),
            __('Kitsune AI Platform', 'kitsune-ai-platform'),
            'read',
            'kitsune-ai-platform',
            array($this, 'display_admin_page'),
            'dashicons-admin-generic',
            30
        );

        if ($perms['chatbots']) {
            add_menu_page(
                __('Inbox', 'kitsune-ai-platform'),
                __('Inbox', 'kitsune-ai-platform'),
                'read',
                'kitsune-ai-platform-inbox',
                array($this, 'display_admin_page'),
                'dashicons-email',
                31
            );
        }

        add_submenu_page(
            'kitsune-ai-platform',
            __('Dashboard', 'kitsune-ai-platform'),
            __('Dashboard', 'kitsune-ai-platform'),
            'read',
            'kitsune-ai-platform',
            array($this, 'display_admin_page')
        );

        $submenus = array();
        if ($perms['models'])         $submenus['kitsune-ai-platform-models']         = __('AI Models', 'kitsune-ai-platform');
        if ($perms['chatbots'])       $submenus['kitsune-ai-platform-chatbots']       = __('Chatbots', 'kitsune-ai-platform');
        if ($perms['content'])        $submenus['kitsune-ai-platform-content']        = __('Content Studio', 'kitsune-ai-platform');
        if ($perms['content'])        $submenus['kitsune-ai-platform-forms']          = __('AI Forms', 'kitsune-ai-platform');
        if ($perms['knowledge_base']) $submenus['kitsune-ai-platform-knowledge-base'] = __('Knowledge Base', 'kitsune-ai-platform');
        if ($perms['automation'])     $submenus['kitsune-ai-platform-automation']     = __('Automation', 'kitsune-ai-platform');
        if ($perms['analytics'])      $submenus['kitsune-ai-platform-analytics']      = __('Analytics', 'kitsune-ai-platform');
        if ($perms['integrations'])   $submenus['kitsune-ai-platform-integrations']   = __('Integrations', 'kitsune-ai-platform');
        if ($perms['settings'])       $submenus['kitsune-ai-platform-settings']       = __('Settings', 'kitsune-ai-platform');
        $submenus['kitsune-ai-platform-help'] = __('Help & Support', 'kitsune-ai-platform');

        foreach ($submenus as $slug => $title) {
            add_submenu_page(
                'kitsune-ai-platform',
                $title,
                $title,
                'read',
                $slug,
                array($this, 'display_admin_page')
            );
        }
    }

    /**
     * Render the admin page container.
     */
    public function display_admin_page() {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $perms = $this->get_user_permissions();

        $page_capability_map = array(
            'kitsune-ai-platform-models'         => 'models',
            'kitsune-ai-platform-chatbots'       => 'chatbots',
            'kitsune-ai-platform-inbox'          => 'chatbots',
            'kitsune-ai-platform-content'        => 'content',
            'kitsune-ai-platform-forms'          => 'content',
            'kitsune-ai-platform-knowledge-base' => 'knowledge_base',
            'kitsune-ai-platform-automation'     => 'automation',
            'kitsune-ai-platform-analytics'      => 'analytics',
            'kitsune-ai-platform-integrations'   => 'integrations',
            'kitsune-ai-platform-settings'       => 'settings',
        );

        if (isset($page_capability_map[$page])) {
            $feature = $page_capability_map[$page];
            if (empty($perms[$feature])) {
                wp_die(__('You do not have sufficient permissions to access this page.', 'kitsune-ai-platform'));
            }
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/views/admin-page.php';
    }

    /**
     * Enqueue admin scripts and styles.
     *
     * @param string $hook Current admin hook suffix.
     */
    public function enqueue_admin_scripts($hook) {
        if (strpos($hook, 'kitsune-ai-platform') === false) {
            return;
        }

        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $initial_view = 'dashboard';

        $view_map = array(
            'kitsune-ai-platform'               => 'dashboard',
            'kitsune-ai-platform-models'        => 'models',
            'kitsune-ai-platform-chatbots'      => 'chatbots',
            'kitsune-ai-platform-inbox'         => 'inbox',
            'kitsune-ai-platform-content'       => 'content',
            'kitsune-ai-platform-forms'         => 'forms',
            'kitsune-ai-platform-knowledge-base'=> 'knowledge-base',
            'kitsune-ai-platform-automation'    => 'automation',
            'kitsune-ai-platform-analytics'     => 'analytics',
            'kitsune-ai-platform-integrations'  => 'integrations',
            'kitsune-ai-platform-settings'      => 'settings',
            'kitsune-ai-platform-help'          => 'help',
        );

        if (array_key_exists($page, $view_map)) {
            $initial_view = $view_map[$page];
        }

        wp_enqueue_style(
            $this->plugin_name . '-chatbot-preview',
            KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/css/chatbot-preview.css',
            array(),
            $this->version
        );

        $vite_js = KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/assets/dist/admin-app.js';
        $vite_css = KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/assets/dist/admin-app.css';

        if (file_exists($vite_js)) {
            if (file_exists($vite_css)) {
                wp_enqueue_style(
                    $this->plugin_name . '-app',
                    KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/dist/admin-app.css',
                    array(),
                    filemtime($vite_css)
                );
            }

            wp_enqueue_script(
                $this->plugin_name . '-app',
                KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/dist/admin-app.js',
                array('wp-api-fetch', 'wp-i18n'),
                filemtime($vite_js),
                true
            );
        } else {
            wp_enqueue_style(
                $this->plugin_name . '-tailwind',
                KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/css/tailwind.css',
                array(),
                $this->version
            );

            wp_enqueue_script(
                $this->plugin_name . '-admin-app',
                KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/js/admin-app.js',
                array(),
                $this->version,
                true
            );
        }

        wp_localize_script(
            $this->plugin_name . '-app',
            'kitsuneAiPlatformConfig',
            array(
                'ajaxUrl'       => admin_url('admin-ajax.php'),
                'restUrl'       => rest_url('kitsune-ai-platform/v1/'),
                'restNonce'     => wp_create_nonce('wp_rest'),
                'ajaxNonce'     => wp_create_nonce('kitsune_ai_platform_nonce'),
                'pluginUrl'     => KITSUNE_AI_PLATFORM_PLUGIN_URL,
                'initialView'   => $initial_view,
                'currentUser'   => array(
                    'id'    => get_current_user_id(),
                    'name'  => wp_get_current_user()->display_name,
                    'email' => wp_get_current_user()->user_email,
                    'role'  => !empty(wp_get_current_user()->roles) ? wp_get_current_user()->roles[0] : 'subscriber'
                ),
                'settings'      => $this->settings_admin->get_plugin_settings(),
                'capabilities'  => array(
                    'manageOptions' => current_user_can('manage_options'),
                    'editPosts'     => current_user_can('edit_posts'),
                    'publishPosts'  => current_user_can('publish_posts'),
                    'permissions'   => $this->get_user_permissions(),
                ),
                'i18n'          => Kitsune_AI_Platform_I18n_Strings::get(), // @see includes/constants/class-kitsune-ai-platform-i18n-strings.php
                'features'      => array(
                    'chatbots'      => true,
                    'content'       => true,
                    'forms'         => true,
                    'knowledgeBase' => true,
                    'automation'    => true,
                    'analytics'     => true,
                ),
                'onboarding'    => array(
                    'complete' => get_option('kitsune_ai_platform_onboarding_complete', false),
                ),
                'models'        => kitsune_ai_platform_get_frontend_model_map(),
            )
        );
    }

    /**
     * Add action links to plugins page.
     *
     * @param array $links Existing links.
     * @return array
     */
    public function add_action_links($links) {
        $settings_link = sprintf(
            '<a href="%s">%s</a>',
            admin_url('admin.php?page=kitsune-ai-platform'),
            __('Settings', 'kitsune-ai-platform')
        );

        array_unshift($links, $settings_link);

        return $links;
    }

    /**
     * Enqueue editor assets (Gutenberg).
     */
    public function enqueue_editor_assets() {
        $settings = $this->settings_admin->get_plugin_settings();

        if (empty($settings['enable_in_editor'])) {
            return;
        }

        $editor_js = KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/assets/dist/editor-app.js';
        $editor_css = KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/assets/dist/editor-app.css';

        if (file_exists($editor_js)) {
            wp_enqueue_script(
                'kitsune-ai-platform-editor',
                KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/dist/editor-app.js',
                array('wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-compose', 'wp-api-fetch'),
                filemtime($editor_js),
                true
            );

            if (file_exists($editor_css)) {
                wp_enqueue_style(
                    'kitsune-ai-platform-editor-styles',
                    KITSUNE_AI_PLATFORM_PLUGIN_URL . 'admin/assets/dist/editor-app.css',
                    array(),
                    filemtime($editor_css)
                );
            }

            wp_localize_script(
                'kitsune-ai-platform-editor',
                'kitsuneAiPlatformEditorConfig',
                array(
                    'settings' => $settings,
                    'user'     => wp_get_current_user(),
                    'nonce'    => wp_create_nonce('wp_rest'),
                    'apiRoot'  => esc_url_raw(rest_url()),
                )
            );
        }
    }
}
