<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * PufferGo Dashboard 页面
 * 
 * 功能说明：
 * 1. 注册 PufferGo 主菜单的首页（点击主菜单时显示）
 * 2. 显示 AI 建站宣传内容
 * 3. 右上角显示用户套餐和剩余积分
 * 4. 提供 AJAX 接口获取账户状态（调用 /api/account/status）
 * 
 * @package PufferGo
 * @since 1.0.0
 */

class PufferGo_Dashboard {
    
    public function __construct() {
        // 主菜单与回调由 PufferGo_Admin_Menu 注册
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));

        // 在 WordPress 默认后台首页顶部展示 PufferGo 入口 Banner
        add_action('admin_notices', array($this, 'render_wp_dashboard_banner_mount'));
        
        // 注册 AJAX 处理器（获取账户状态）
        add_action('wp_ajax_puffergo_get_account_status', array($this, 'handle_get_account_status'));
    }
    
    /**
     * 渲染 Dashboard 页面（主菜单的回调，由 PufferGo_Admin_Menu 注册）
     */
    public static function render_page() {
        ?>
        <div class="wrap">
            <div id="puffergo-dashboard-root"></div>
        </div>
        <?php
    }
    
    /**
     * 加载前端资源（仅在 Dashboard 页面）
     */
    public function enqueue_scripts($hook) {
        if ($hook === 'index.php') {
            $this->enqueue_wp_dashboard_banner_assets();
        }

        // 只在 PufferGo 主页面加载
        if ($hook !== 'toplevel_page_puffergo') {
            return;
        }
        
        $plugin_url = plugin_dir_url(dirname(__FILE__));
        $asset_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/dashboard-app/index.asset.php';
        
        // 如果 asset 文件存在，使用其中的依赖和版本信息
        if (file_exists($asset_file)) {
            $asset = include $asset_file;
            $dependencies = $asset['dependencies'];
            $version = $asset['version'];
        } else {
            $dependencies = array(
                'wp-element',
                'wp-components',
                'wp-api-fetch',
                'wp-data'
            );
            $version = time();
        }
        
        // 加载 JavaScript
        wp_enqueue_script(
            'puffergo-dashboard',
            $plugin_url . 'build/blocks/dashboard-app/index.js',
            $dependencies,
            $version,
            true
        );
        
        // 加载 CSS - 组件样式（Tailwind 已在全局统一加载）
        $style_css_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/dashboard-app/style-index.css';
        if (file_exists($style_css_file)) {
            wp_enqueue_style(
                'puffergo-dashboard-styles',
                $plugin_url . 'build/blocks/dashboard-app/style-index.css',
                array('puffergo-admin-tailwind', 'wp-components'), // 依赖全局 Tailwind
                $version
            );
        }

        // 反馈页面 URL（跳转管理后台收集反馈）
        $feedback_url = class_exists( 'PufferGo_Telemetry' ) ? PufferGo_Telemetry::get_feedback_url() : '';
        
        // 传递配置到前端
        wp_localize_script('puffergo-dashboard', 'puffergoDashboard', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('puffergo_dashboard'),
            'verifyNonce' => wp_create_nonce('puffergo_verify_key'), // 用于验证 API Key
            'disconnectNonce' => wp_create_nonce('puffergo_disconnect_account'), // 用于断开连接
            'connectBaseUrl' => PUFFERGO_BASE_URL,
            'siteName' => get_bloginfo('name'),
            'locale' => str_replace( '_', '-', function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale() ),
            'settingsUrl' => admin_url('admin.php?page=puffergo-settings'),
            'aiSiteBuilderUrl' => admin_url('admin.php?page=puffergo-ai-site-builder'),
            'proUrl' => PUFFERGO_BASE_URL . '/dashboard/billing',
            'templatesUrl' => PUFFERGO_BASE_URL . '/wp/templates',
            'docsUrl' => PUFFERGO_BASE_URL . '/docs/why-puffergo/',
            'learnUrl' => PUFFERGO_BASE_URL . '/wp',
            'dashboardUrl' => PUFFERGO_BASE_URL . '/dashboard',
            'connectUrl' => PUFFERGO_BASE_URL . '/dashboard/connect',
            'apiKeysUrl' => PUFFERGO_BASE_URL . '/dashboard/api-keys',
            'feedbackUrl' => $feedback_url,
            'strings' => array(
                'quickStartSteps' => array(
                    __('Connect pufferGo account (30s)', 'puffergo'),
                    __('Enter brand information, AI automatically generates website', 'puffergo'),
                    __('Publish your high-conversion international site', 'puffergo')
                    )
            )
            )
        );
        
        // 显式加载 WordPress 组件样式
        wp_enqueue_style('wp-components');
    }

    /**
     * 加载 WordPress 默认后台首页 Banner 资源
     */
    private function enqueue_wp_dashboard_banner_assets() {
        if ( ! current_user_can( 'edit_posts' ) ) {
            return;
        }
        $plugin_url      = plugin_dir_url( dirname( __FILE__ ) );
        $asset_file      = plugin_dir_path( dirname( __FILE__ ) ) . 'build/admin/wp-dashboard-banner/index.asset.php';
        $style_css_file  = plugin_dir_path( dirname( __FILE__ ) ) . 'build/admin/wp-dashboard-banner/style-index.css';

        if ( file_exists( $asset_file ) ) {
            $asset        = include $asset_file;
            $dependencies = $asset['dependencies'];
            $version      = $asset['version'];
        } else {
            $dependencies = array( 'wp-element', 'wp-i18n' );
            $version      = time();
        }

        wp_enqueue_script(
            'puffergo-wp-dashboard-banner',
            $plugin_url . 'build/admin/wp-dashboard-banner/index.js',
            $dependencies,
            $version,
            true
        );

        if ( file_exists( $style_css_file ) ) {
            wp_enqueue_style(
                'puffergo-wp-dashboard-banner',
                $plugin_url . 'build/admin/wp-dashboard-banner/style-index.css',
                array(),
                $version
            );
        }

        wp_localize_script(
            'puffergo-wp-dashboard-banner',
            'puffergoWpDashboardBanner',
            array(
                'dashboardUrl' => admin_url( 'admin.php?page=puffergo' ),
                'learnUrl'     => trailingslashit( PUFFERGO_BASE_URL ) . 'docs/why-puffergo/',
            )
        );
    }

    /**
     * 在 WordPress 默认后台首页输出 React 挂载点
     */
    public function render_wp_dashboard_banner_mount() {
        if ( ! current_user_can( 'edit_posts' ) ) {
            return;
        }

        $screen = get_current_screen();
        if ( ! $screen || 'dashboard' !== $screen->base ) {
            return;
        }

        echo '<div id="puffergo-wp-dashboard-banner-root"></div>';
    }
    
    /**
     * 处理获取账户状态 AJAX 请求
     * 
     * 工作流程：
     * 1. 验证 nonce 安全
     * 2. 使用 PufferGo_API_Client 调用 key-checkin 接口（queryOnly: true）
     * 3. 返回账户状态（套餐信息、剩余积分等）
     */
    public function handle_get_account_status() {
        // 第一步：验证 nonce，防止 CSRF 攻击
        check_ajax_referer('puffergo_dashboard', '_ajax_nonce');
        
        puffergo_log('PufferGo Dashboard: 开始获取账户状态...');
        
        try {
            // 使用 PufferGo_API_Client 调用 key-checkin 接口（只查询，不更新）
            $api_client = PufferGo_API_Client::get_instance();
            
            $result = $api_client->post(
                '/api/account/key-checkin',
                array(
                    'queryOnly' => true  // 只查询，不更新域名和IP
                ),
                array(
                    'timeout' => 30,
                    'log_prefix' => 'PufferGo Dashboard'
                )
            );
            
            puffergo_log('PufferGo Dashboard: 获取账户状态成功！');
            
            // 返回成功响应
            wp_send_json_success($result);
            
        } catch (Exception $e) {
            puffergo_log('PufferGo Dashboard: 获取账户状态失败 - ' . $e->getMessage());
            
            // 返回错误响应
            wp_send_json_error(array(
                'message' => $e->getMessage()
            ), 500);
        }
    }
}

// 实例化类
new PufferGo_Dashboard();
