<?php

namespace HaoZiTeam\AIPost\Service\Settings\Traits;

defined('ABSPATH') || exit;

trait TraitLicense
{
    // 渲染：授权操作（即时校验）
    public function render_license_block(): void
    {
        $nonce = \wp_create_nonce('ai_post_check_license');
        $adminAjax = \admin_url('admin-ajax.php');
        // 初始渲染：预填当前授权状态（如可用）
        $initialHtml = '';
        if (function_exists('auth_info')) {
            ob_start();
            try { auth_info(); } catch (\Throwable $e) { echo '授权检查异常：' . esc_html($e->getMessage()); }
            $initialHtml = ob_get_clean();
        }
        ?>
        <div class="ai-post-license-panel" style="background:#f8f9fa;border:1px solid #e5e7eb;border-radius:6px;padding:12px;">
            <div style="display:flex;gap:8px;align-items:center;margin-bottom:8px;">
                <button type="button" class="button button-primary" id="ai-post-validate-license">立即校验授权</button>
                <span style="color:#666;">无需刷新页面，保存并校验当前输入的卡号/卡密</span>
            </div>
            <div id="ai-post-live-auth" style="padding:8px;border-radius:4px;background:#fff;border:1px solid #e5e7eb;"><?php echo $initialHtml; ?></div>
        </div>
        <script>
        (function($){
            $('#ai-post-validate-license').on('click', function(){
                var $btn = $(this);
                var num = $('input[name="ai-post[cardNum]"]').val() || '';
                var pwd = $('input[name="ai-post[cardPwd]"]').val() || '';
                $btn.prop('disabled', true).text('正在校验...');
                $.post('<?php echo esc_js($adminAjax); ?>', {
                    action: 'ai_post_check_license',
                    _wpnonce: '<?php echo esc_js($nonce); ?>',
                    cardNum: num,
                    cardPwd: pwd
                }).done(function(res){
                    var $live = $('#ai-post-live-auth');
                    if(res && res.success){
                        $live.html(res.data && res.data.html ? res.data.html : '已保存并校验');
                    } else {
                        $live.html((res && res.data && res.data.message) ? res.data.message : '校验失败');
                    }
                    $live.show();
                }).fail(function(){
                    alert('请求失败');
                }).always(function(){
                    $btn.prop('disabled', false).text('立即校验授权');
                });
            });
        })(jQuery);
        </script>
        <?php
    }

    // AJAX：保存并即时校验授权
    public function ajax_check_license(): void
    {
        \check_ajax_referer('ai_post_check_license');
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => '权限不足'], 403);
        }
        $cardNum = isset($_POST['cardNum']) ? trim((string) $_POST['cardNum']) : '';
        $cardPwd = isset($_POST['cardPwd']) ? trim((string) $_POST['cardPwd']) : '';

        // 合并保存到 ai-post 选项
        $opts = \get_option('ai-post', []);
        if (!is_array($opts)) { $opts = []; }
        $opts['cardNum'] = $cardNum;
        $opts['cardPwd'] = $cardPwd;
        \update_option('ai-post', $opts);

        // 复用现有授权状态渲染（如存在）
        $html = '';
        if (function_exists('auth_info')) {
            ob_start();
            try { auth_info(); } catch (\Throwable $e) { echo '授权检查异常：' . esc_html($e->getMessage()); }
            $html = ob_get_clean();
        } else {
            $html = '<div class="notice notice-info"><p>已保存卡号与卡密，如未显示详细授权信息，请刷新页面。</p></div>';
        }
        \wp_send_json_success(['html' => $html]);
    }
}
