<?php
if (! defined('ABSPATH')) {
    exit;
} function puffergo_checkin_feature_enabled()
{
    if (defined('PUFFERGO_DISABLE_CHECKIN') && PUFFERGO_DISABLE_CHECKIN) {
        return false;
    }

return (bool) apply_filters('puffergo_checkin_enabled', true);
} class PufferGo_Dashboard
{
    public function __construct()
    {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('admin_notices', array($this, 'render_wp_dashboard_banner_mount'));
        add_action('wp_ajax_puffergo_get_account_status', array($this, 'handle_get_account_status'));
        add_action('wp_ajax_puffergo_checkin_status', array($this, 'handle_checkin_status'));
        add_action('wp_ajax_puffergo_daily_checkin', array($this, 'handle_daily_checkin'));
    }

    public static function render_page()
    { ?>
        <div class="wrap">
            <div id="puffergo-dashboard-root"></div>
        </div>
        <?php
    }

    public function enqueue_scripts($hook)
    {
        if ($hook === 'index.php') {
            $this->enqueue_wp_dashboard_banner_assets();
        }

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';

        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();
        } wp_enqueue_script('puffergo-dashboard', $plugin_url . 'build/blocks/dashboard-app/index.js', $dependencies, $version, true);
        $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'), $version);
        } $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'), '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, 'isBlockTheme' => function_exists('wp_is_block_theme') ? wp_is_block_theme() : (bool) file_exists(get_template_directory() . '/theme.json'), 'installGeneratePressUrl' => admin_url('theme-install.php?search=GeneratePress'), 'fseDocsUrl' => class_exists('PufferGo_Fse_Theme_Notice') ? PufferGo_Fse_Theme_Notice::DOCS_URL : '', 'homepageIssue' => class_exists('PufferGo_Homepage_Guard') ? PufferGo_Homepage_Guard::get_dashboard_banner_data() : null, 'restUrl' => rest_url('puffergo/v1'), 'restNonce' => wp_create_nonce('wp_rest'), 'adminUrl' => admin_url(), 'userCanManageOptions' => current_user_can('manage_options'), 'checkinEnabled' => puffergo_checkin_feature_enabled(), ));
        wp_enqueue_style('wp-components');
    }

    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);
        } $banner_config = array('dashboardUrl' => admin_url('admin.php?page=puffergo'), 'learnUrl' => trailingslashit(PUFFERGO_BASE_URL) . 'docs/why-puffergo/', );
        $banner_config = apply_filters('puffergo_wp_dashboard_banner_config', $banner_config);
        wp_localize_script('puffergo-wp-dashboard-banner', 'puffergoWpDashboardBanner', $banner_config);
    }

    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>';
    }

    private function verify_ajax_request($require_checkin_enabled = false)
    {
        check_ajax_referer('puffergo_dashboard', '_ajax_nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Insufficient permissions', 'puffergo')), 403);
        }

if ($require_checkin_enabled && !puffergo_checkin_feature_enabled()) {
            wp_send_json_error(array('message' => __('Daily check-in is disabled', 'puffergo')), 403);
        }
    }

    public function handle_get_account_status()
    {
        $this->verify_ajax_request();
        puffergo_log('PufferGo Dashboard: 开始获取账户状态...');

        try {
            $api_client = PufferGo_API_Client::get_instance();
            $result = $api_client->post('/api/account/key-checkin', array('queryOnly' => true), 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);
        }
    }

    public function handle_checkin_status()
    {
        $this->verify_ajax_request(true);

        try {
            $api_client = PufferGo_API_Client::get_instance();
            $result = $api_client->get('/api/account/checkin-status', array(), array('timeout' => 30, 'log_prefix' => 'PufferGo Checkin Status'));
            wp_send_json_success($result);
        } catch (Exception $e) {
            puffergo_log('PufferGo Checkin Status: 获取签到状态失败 - ' . $e->getMessage());
            wp_send_json_error(array('message' => $e->getMessage()), 500);
        }
    }

    public function handle_daily_checkin()
    {
        $this->verify_ajax_request(true);

        try {
            $api_client = PufferGo_API_Client::get_instance();
            $result = $api_client->post('/api/account/daily-checkin', array(), array('timeout' => 30, 'log_prefix' => 'PufferGo Daily Checkin', 'return_body_on_client_error' => true, ));

            if (is_array($result) && isset($result['code']) && 'PLUGIN_UPGRADE_REQUIRED' === $result['code']) {
                wp_clean_plugins_cache();
            } wp_send_json_success($result);
        } catch (Exception $e) {
            puffergo_log('PufferGo Daily Checkin: 签到失败 - ' . $e->getMessage());
            wp_send_json_error(array('message' => $e->getMessage()), 500);
        }
    }
} new PufferGo_Dashboard();
