<?php

namespace HaoZiTeam\AIPost\Service\Settings\Traits;

defined('ABSPATH') || exit;

trait TraitCronTokenPanel
{
    // 渲染：通信令牌（Cron/REST）说明与操作（系统调试与日志面板专用）
    public function render_cron_token_panel(): void
    {
        $cron_token = (string) \get_option('ai_post_cron_token', '');
        $cron_masked = $cron_token !== ''
            ? ((strlen($cron_token) > 8) ? (substr($cron_token, 0, 4) . str_repeat('*', max(0, strlen($cron_token) - 8)) . substr($cron_token, -4)) : $cron_token)
            : '（未生成）';
        $cron_nonce = \wp_create_nonce('aipost_cron_token_nonce');
        $adminAjax = \admin_url('admin-ajax.php');
        ?>
        <div class="notice" style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:12px;margin:8px 0 14px;">
            <h2 style="margin:0 0 8px;">通信令牌（Cron/REST）</h2>
            <p style="margin:4px 0 6px;color:#064e3b;">用于外部触发任务执行（REST 优先）。令牌仅站点级存储，可随时刷新或清空禁用。</p>
            <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
                <div><strong>当前状态：</strong> <span id="aipost-cron-token" style="font-family:monospace;"><?php echo esc_html($cron_masked); ?></span></div>
                <div style="display:flex;gap:8px;">
                    <button type="button" class="button button-primary" id="aipost-cron-generate">生成/刷新</button>
                    <button type="button" class="button" id="aipost-cron-show">复制明文</button>
                    <button type="button" class="button" id="aipost-cron-clear">清空禁用</button>
                    <button type="button" class="button" id="aipost-cron-ping">REST 连通性测试</button>
                </div>
            </div>
            <div style="margin-top:6px;color:#065f46;font-size:12px;">
                REST 调用：POST <code>/wp-json/aipost/v1/cron</code>，Body：<code>token=YOUR_TOKEN</code>
            </div>
            <div id="aipost-cron-msg" style="margin-top:8px;color:#065f46;"></div>
            <div style="margin:8px 0 0; padding:10px; background:#ecfdf5; border:1px dashed #86efac; border-radius:6px; color:#065f46;">
                <div style="font-weight:600; margin-bottom:6px;">任务长时间未运行？（重要）</div>
                <div style="line-height:1.6;">若在 <code>debug.log</code> 中多次出现“<code>AI Post Cron: 任务 X 检测到长时间未跑，已补发一次执行（5s 后）</code>”，建议使用基于通信令牌（token）的外部计划任务触发，确保按时执行。</div>
                <div style="margin-top:6px;"><strong>推荐（POST，REST 端点）：</strong>
                    <div>URL（二选一）：<code>/wp-json/aipost/v1/cron</code> 或 <code>/index.php?rest_route=/aipost/v1/cron</code></div>
                    <div>方法：<code>POST</code>；Body：<code>token=YOUR_TOKEN</code></div>
                    <pre style="white-space:pre-wrap;background:#e6fffa;border:1px solid #86efac;padding:6px;border-radius:4px;margin:6px 0 0;">PowerShell（Windows 计划任务）:
$uri = "https://example.com/index.php?rest_route=/aipost/v1/cron"
$body = @{ token = "YOUR_TOKEN" }
Invoke-WebRequest -Uri $uri -Method POST -Body $body -ContentType "application/x-www-form-urlencoded" | Out-Null</pre>
                </div>
                <div style="margin-top:6px;"><strong>仅支持 GET 的平台（需 MU 插件）：</strong>
                    <div>URL：<code>/?aipost_run=all&token=YOUR_TOKEN</code>（请在 CDN/WAF 中为 <code>aipost_run</code> 查询串设置“跳过缓存”）</div>
                </div>
            </div>
        </div>
        <script>
        (function(){
            function setCronMsg(s, ok){var el=document.getElementById('aipost-cron-msg'); if(!el) return; el.style.color = ok ? '#065f46' : '#991b1b'; el.textContent = s;}
            function maskToken(t){if(!t) return '（未生成）'; return (t.length>8)?(t.slice(0,4)+'****'+t.slice(-4)):t;}
            var nonce = <?php echo json_encode($cron_nonce); ?>;
            function postAjax(action){var fd=new FormData(); fd.append('action', action); fd.append('nonce', nonce); return fetch(<?php echo json_encode($adminAjax); ?>,{method:'POST',credentials:'same-origin',body:fd}).then(function(r){return r.json();});}
            var outTok=document.getElementById('aipost-cron-token');
            var btnGen=document.getElementById('aipost-cron-generate');
            var btnShow=document.getElementById('aipost-cron-show');
            var btnClr=document.getElementById('aipost-cron-clear');
            var btnPing=document.getElementById('aipost-cron-ping');
            if(btnGen) btnGen.addEventListener('click', function(){btnGen.disabled=true; btnGen.textContent='处理中...'; postAjax('aipost_generate_cron_token').then(function(res){ if(res&&res.success){ outTok.textContent = maskToken(res.data&&res.data.token?String(res.data.token):''); setCronMsg('已生成/刷新通信令牌', true);} else { setCronMsg((res&&res.data&&res.data.message)?res.data.message:'操作失败', false);} }).catch(function(e){ setCronMsg('网络错误：' + (e&&e.message?e.message:String(e)), false); }).finally(function(){ btnGen.disabled=false; btnGen.textContent='生成/刷新'; });});
            if(btnShow) btnShow.addEventListener('click', function(){
                btnShow.disabled=true; btnShow.textContent='处理中...';
                postAjax('aipost_get_cron_token')
                .then(function(res){
                    if(!(res&&res.success)){
                        setCronMsg((res&&res.data&&res.data.message)?res.data.message:'操作失败', false); return;
                    }
                    var tok=(res.data&&res.data.token)?String(res.data.token):'';
                    if(!tok){ setCronMsg('尚未生成令牌', false); return; }
                    var doCopy = function(text){
                        try {
                            if (navigator && navigator.clipboard && typeof navigator.clipboard.writeText === 'function'){
                                return navigator.clipboard.writeText(text).then(function(){ return true; });
                            }
                        } catch(_) {}
                        return new Promise(function(resolve){
                            var ta = document.createElement('textarea');
                            ta.style.position='fixed'; ta.style.opacity='0'; ta.value = text;
                            document.body.appendChild(ta); ta.focus(); ta.select();
                            try { var ok = document.execCommand('copy'); resolve(!!ok); }
                            catch(e){ resolve(false); }
                            finally { document.body.removeChild(ta); }
                        });
                    };
                    return doCopy(tok).then(function(ok){
                        if(ok){ setCronMsg('已复制到剪贴板（明文仅短暂存在，请妥善保存）', true); }
                        else { setCronMsg('复制失败：浏览器不支持剪贴板，请手动复制', false); }
                    });
                })
                .catch(function(e){ setCronMsg('网络错误：' + (e&&e.message?e.message:String(e)), false); })
                .finally(function(){ btnShow.disabled=false; btnShow.textContent='复制明文'; });
            });
            if(btnClr) btnClr.addEventListener('click', function(){ if(!confirm('确定要清空并禁用通信令牌吗？外部触发将不可用。')) return; btnClr.disabled=true; btnClr.textContent='处理中...'; postAjax('aipost_clear_cron_token').then(function(res){ if(res&&res.success){ outTok.textContent='（未生成）'; setCronMsg('已清空通信令牌', true);} else { setCronMsg((res&&res.data&&res.data.message)?res.data.message:'操作失败', false);} }).catch(function(e){ setCronMsg('网络错误：' + (e&&e.message?e.message:String(e)), false); }).finally(function(){ btnClr.disabled=false; btnClr.textContent='清空禁用'; });});
            if(btnPing) btnPing.addEventListener('click', function(){
                btnPing.disabled=true; btnPing.textContent='测试中...';
                postAjax('aipost_get_cron_token')
                .then(function(res){
                    if(!(res&&res.success&&res.data&&res.data.token)){
                        throw new Error((res&&res.data&&res.data.message)?res.data.message:'尚未生成令牌');
                    }
                    var tok=String(res.data.token);
                    var restRoot=(window.AIPostSecureConfig&&AIPostSecureConfig.restBase)?String(AIPostSecureConfig.restBase):'/wp-json/';
                    // restRoot 通常为 https://example.com/wp-json/（根），这里需要追加命名空间 aipost/v1
                    var url=restRoot.replace(/\/$/, '')+'/aipost/v1/cron/ping';
                    var fd=new FormData(); fd.append('token', tok);
                    return fetch(url,{method:'POST',credentials:'same-origin',body:fd})
                        .then(function(resp){
                            var status=resp.status;
                            return resp.text().then(function(txt){ return {status:status, text:txt}; });
                        })
                        .then(function(payload){
                            try {
                                var data = JSON.parse(payload.text);
                                if(data&&data.ok){ setCronMsg('REST 连通性正常：' + (data.site||'') + ' @ ' + (data.time||''), true); return; }
                                setCronMsg('REST 测试失败：' + (data&&data.error?data.error:('HTTP '+payload.status)), false);
                            } catch(_){
                                var origin = (window.location.origin||'');
                                var fallback = origin + '/index.php?rest_route=/aipost/v1/cron/ping';
                                var fd2=new FormData(); fd2.append('token', tok);
                                return fetch(fallback,{method:'POST',credentials:'same-origin',body:fd2})
                                    .then(function(r2){
                                        var s2=r2.status; return r2.text().then(function(t2){ return {status:s2,text:t2}; });
                                    })
                                    .then(function(p2){
                                        try {
                                            var d2 = JSON.parse(p2.text);
                                            if(d2&&d2.ok){ setCronMsg('REST 连通性正常：' + (d2.site||'') + ' @ ' + (d2.time||''), true); return; }
                                            setCronMsg('REST 测试失败：' + (d2&&d2.error?d2.error:('HTTP '+p2.status)), false);
                                        } catch(e2){
                                            setCronMsg('REST 测试失败：非JSON响应（HTTP '+p2.status+'）', false);
                                        }
                                    });
                            }
                        });
                })
                .catch(function(e){ setCronMsg('REST 连通性异常：' + (e&&e.message?e.message:String(e)), false); })
                .finally(function(){ btnPing.disabled=false; btnPing.textContent='REST 连通性测试'; });
            });
        })();
        </script>
        <?php
    }

    public function ajax_generate_cron_token(): void
    {
        $ok = \check_ajax_referer('aipost_cron_token_nonce', 'nonce', false);
        if (!$ok) {
            \wp_send_json_error(['message' => 'nonce 校验失败（请刷新页面重试）'], 400);
        }
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => '权限不足'], 403);
        }

        $token = '';
        if (function_exists('wp_generate_password')) {
            $token = (string) \wp_generate_password(40, false, false);
        }
        if ($token === '') {
            $token = (string) (time() . '_' . \wp_rand(100000, 999999) . '_' . md5((string) \wp_rand()));
        }

        \update_option('ai_post_cron_token', $token, false);
        \wp_send_json_success(['token' => $token]);
    }

    public function ajax_get_cron_token(): void
    {
        $ok = \check_ajax_referer('aipost_cron_token_nonce', 'nonce', false);
        if (!$ok) {
            \wp_send_json_error(['message' => 'nonce 校验失败（请刷新页面重试）'], 400);
        }
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => '权限不足'], 403);
        }

        $token = (string) \get_option('ai_post_cron_token', '');
        if ($token === '') {
            \wp_send_json_error(['message' => '尚未生成令牌'], 404);
        }

        \wp_send_json_success(['token' => $token]);
    }

    public function ajax_clear_cron_token(): void
    {
        $ok = \check_ajax_referer('aipost_cron_token_nonce', 'nonce', false);
        if (!$ok) {
            \wp_send_json_error(['message' => 'nonce 校验失败（请刷新页面重试）'], 400);
        }
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => '权限不足'], 403);
        }

        \delete_option('ai_post_cron_token');
        \wp_send_json_success(['ok' => true]);
    }
}
