<?php

namespace Blazemedia\Affiliation\Providers\Trait;

use Blazemedia\Affiliation\Rendering\RenderResponse;

trait HasDebugInspector
{
    /**
     * Enqueue the debug inspector UI for the user "techteam" only.
     */
    protected function enqueueDebugInspector(RenderResponse $renderResponse): void
    {
        if (!function_exists('wp_get_current_user')) return;

        if (!is_user_logged_in()) return;

        $user = wp_get_current_user();
        if (!$user || $user->user_login !== 'techteam') return;

        // Only enqueue if we actually have replacements to debug
        $replacements = $renderResponse->getReplacements();
        if (empty($replacements)) return;

        add_action('wp_enqueue_scripts', function () use ($replacements) {
            $handle = 'blz-affiliation-debug-inspector';

            wp_enqueue_script(
                $handle,
                BLAZE_AFFILIATION_URI . 'js/DebugInspector.js',
                [ 'jquery' ],
                '1.0.0',
                true
            );

            // Get meta values from the current post (parent and child)
            $metaReplacements = [];
            $metaSignature = '';
            $metaChildReplacements = [];
            $metaChildSignature = '';
            if (function_exists('get_post') && isset($GLOBALS['post']) && $GLOBALS['post'] instanceof \WP_Post) {
                $post = $GLOBALS['post'];
                // Parent
                $raw = get_post_meta($post->ID, '_blz_affiliation_formats', true);
                $decoded = @unserialize($raw);
                if (is_array($decoded) && isset($decoded['replacements']) && is_array($decoded['replacements'])) {
                    $metaReplacements = $decoded['replacements'];
                }
                $metaSignature = (string) get_post_meta($post->ID, '_blz_affiliation_formats_signature', true);
                // Child
                $rawChild = get_post_meta($post->ID, '_blz_affiliation_formats_child', true);
                $decodedChild = @unserialize($rawChild);
                if (is_array($decodedChild) && isset($decodedChild['replacements']) && is_array($decodedChild['replacements'])) {
                    $metaChildReplacements = $decodedChild['replacements'];
                }
                $metaChildSignature = (string) get_post_meta($post->ID, '_blz_affiliation_formats_signature_child', true);
            }

            wp_localize_script($handle, 'BlazeAffiliationDebug', [
                'replacements' => $replacements,
                // Keep backward-compatible parent meta
                'meta' => [
                    'signature' => $metaSignature,
                    'replacements' => $metaReplacements,
                ],
                // New child meta payload
                'meta_child' => [
                    'signature' => $metaChildSignature,
                    'replacements' => $metaChildReplacements,
                ],
            ]);
        });

        add_action('wp_footer', function () {
            echo '<button id="blz-aff-debug-btn" type="button" aria-label="Affiliation Debug"></button>';

            // Additional button to show meta values of replacements stored in post meta
            $btnStyle = 'position:fixed;right:68px;bottom:16px;z-index:2147483647;display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;padding:0;border-radius:50%;border:1px solid rgba(0,0,0,.18);color:#fff;background:linear-gradient(135deg,#334155,#0f172a);cursor:pointer;box-shadow:0 10px 20px rgba(0,0,0,.18), 0 2px 6px rgba(0,0,0,.12);';
            $panelStyle = 'position:fixed;left:0;top:0;right:0;bottom:0;width:100vw;height:100vh;overflow:auto;z-index:2147483647;background:#ffffff;color:#1e293b;border:0;border-radius:0;box-shadow:none;display:none;';
            $headerStyle = 'position:sticky;top:0;z-index:1;display:flex;align-items:center;justify-content:space-between;padding:10px 12px;border-bottom:1px solid #e2e8f0;background:linear-gradient(180deg,#f8fafc,#ffffff);font:700 13px system-ui;';
            $metaTitle = 'font:700 12px system-ui;color:#0f172a;margin:12px;';
            $preStyle = 'white-space:pre-wrap;background:#f8fafc;color:#0f172a;margin:0 12px 12px;padding:12px;border-radius:8px;border:1px solid #e2e8f0;overflow:auto;';

            echo '<button id="blz-aff-meta-btn" type="button" aria-label="Meta replacements" style="' . $btnStyle . '"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="3" y="11" width="18" height="10" rx="2" stroke="currentColor" stroke-width="2"/><path d="M7 11V8a5 5 0 0110 0v3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/></svg></button>';
            echo '<div id="blz-aff-meta-panel" style="' . $panelStyle . '"><div style="' . $headerStyle . '">Meta replacements <button type="button" id="blz-aff-meta-close" style="background:#ffffff;color:#0f172a;border:1px solid #cbd5e1;padding:4px 8px;border-radius:8px;cursor:pointer;">Chiudi</button></div>'
                . '<div><div style="' . $metaTitle . '">Signature (parent)</div><pre id="blz-aff-meta-signature" style="' . $preStyle . '"></pre></div>'
                . '<div><div style="' . $metaTitle . '">Replacements (parent)</div><pre id="blz-aff-meta-replacements" style="' . $preStyle . '"></pre></div>'
                . '<div><div style="' . $metaTitle . '">Signature (child)</div><pre id="blz-aff-meta-signature-child" style="' . $preStyle . '"></pre></div>'
                . '<div><div style="' . $metaTitle . '">Replacements (child)</div><pre id="blz-aff-meta-replacements-child" style="' . $preStyle . '"></pre></div>'
                . '</div>';
            echo '<script>(function(){var b=document.getElementById("blz-aff-meta-btn");var p=document.getElementById("blz-aff-meta-panel");var c=document.getElementById("blz-aff-meta-close");var sig=document.getElementById("blz-aff-meta-signature");var rep=document.getElementById("blz-aff-meta-replacements");var sigc=document.getElementById("blz-aff-meta-signature-child");var repc=document.getElementById("blz-aff-meta-replacements-child");function fill(){try{var d=window.BlazeAffiliationDebug||{};var m=d.meta||{};var mc=d.meta_child||{};sig.textContent=(m.signature||"");sigc.textContent=(mc.signature||"");try{rep.textContent=JSON.stringify((m.replacements||[]),null,2);}catch(e){rep.textContent=String(m.replacements||"");}try{repc.textContent=JSON.stringify((mc.replacements||[]),null,2);}catch(e){repc.textContent=String(mc.replacements||"");}}catch(_){}}function toggle(){if(!p)return;var ds=p.style.display;if(ds==="none"||ds===""){fill();p.style.display="block";}else{p.style.display="none";}}if(b){b.addEventListener("click",toggle);}if(c){c.addEventListener("click",toggle);}})();</script>';
        }, 5);
    }
}


