<?php $nonce = wp_create_nonce( 'quttera' ); ?>

<script type="text/javascript">

    var bot_refresh_counter = 0;

    jQuery(document).ready(function($) {
        // Initialize bot protection blocked IPs display on page load
        renderBotProtectionBlockedList();

        // Auto-refresh blocked IPs every 30 seconds
        setInterval(renderBotProtectionBlockedList, 30000);
    });

    /**
     * Render the bot protection blocked clients list
     * Fetches current blocked clients from server via AJAX
     */
    function renderBotProtectionBlockedList() {
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-get-bot-protection-blocked-ips',
                _wpnonce: '<?php echo $nonce; ?>',
            },
            timeout: 30000,
            error: function(jqXHR, textStatus) {
                console.log('Failed to fetch bot protection blocked IPs:', textStatus);
            },
            success: function(response) {
                if (!response.success) {
                    console.log('Server error:', response.data?.message);
                    return;
                }
                
                if (response.data && response.data.blocked_clients) {
                    updateBotProtectionBlockedDisplay(response.data.blocked_clients);
                }
            }
        });
    }

    /**
     * Get severity level based on risk score
     * @param {number} risk - Risk score
     * @return {string} Severity level
     */
    function getRiskSeverity(risk) {
        const riskNum = parseInt(risk) || 0;
        if (riskNum >= 18) {
            return 'Critical';
        } else if (riskNum >= 12) {
            return 'High';
        } else if (riskNum >= 8) {
            return 'Medium';
        }
        return 'Low';
    }

    /**
     * Convert reason codes to human-readable descriptions
     * Matches the backend reason map in qtrBotProtection.php::get_reason_explanations()
     * @param {string} reasonCode - The reason code from server
     * @return {string} Human-readable description
     */
    function getReasonDescription(reasonCode) {
        const reasonMap = {
            // Heuristic reasons (from qtrBotProtection.php compute_heuristics)
            'H1_MISSING_USER_AGENT':     'Missing User-Agent header',
            'H2_MISSING_ACCEPT':         'Missing Accept header',
            'H3_MISSING_COOKIES':        'Missing cookies',
            'H4_PROBE_PATH':             'Vulnerability probe detected',
            'H5_PATH_SWEEP':             'Path enumeration sweep',
            'H6_BAD_UA_SIGNATURE':       'Suspicious User-Agent signature',
            'H7_ENDPOINT_MAPPING':       'Endpoint mapping probe',
            
            // Rate limiting reasons (from qtrBotProtection.php apply_rate_limits)
            'RL_GLOBAL_EXHAUSTED':       'Global rate limit exceeded',
            'RL_REST_EXHAUSTED':         'REST API rate limit exceeded',
            'RL_XMLRPC_EXHAUSTED':       'XML-RPC rate limit exceeded',
            'RL_CHECKOUT_EXHAUSTED':     'Checkout rate limit exceeded',
            'RL_CART_EXHAUSTED':         'Cart rate limit exceeded',
            
            // Block status
            'blocked_active':            'Previously blocked IP',
            'good_bot':                  'Recognized good bot',
            'good_bot_allowed':          'Good bot with elevated limits',
            
            // Legacy/fallback mappings
            'login_bypass':              'Login bypass (no protection)',
            'allowlist_match':           'Allowlist match (allowed)',
            'active_block':              'Previously blocked client',
        };
        
        return reasonMap[reasonCode] || reasonCode;
    }

    /**
     * Update the display of blocked clients
     * @param {Array} blockedClients - Array of blocked client objects
     */
    function updateBotProtectionBlockedDisplay(blockedClients) {
        const container = document.getElementById('bot_blocked_ips_list');
        const emptyMsg = document.getElementById('bot_blocked_empty_msg');
        const clearBtn = document.getElementById('bot_clear_blocked_btn');

        // If elements don't exist, skip rendering
        if (!container || !emptyMsg) {
            return;
        }

        container.innerHTML = '';

        // Filter out expired blocks - only show active ones
        const activeBlocks = blockedClients.filter(block => block.status === 'active');

        if (activeBlocks.length === 0) {
            emptyMsg.style.display = 'block';
            if (clearBtn) clearBtn.style.display = 'none';
        } else {
            emptyMsg.style.display = 'none';
            if (clearBtn) clearBtn.style.display = 'inline-block';

            activeBlocks.forEach(function(clientData) {
                const div = document.createElement('div');
                div.className = 'bot-block-item';
                
                // Determine risk badge class
                let riskClass = 'risk-badge-low';
                const risk = parseInt(clientData.risk) || 0;
                const riskSeverity = getRiskSeverity(risk);
                if (risk >= 18) {
                    riskClass = 'risk-badge-critical';
                } else if (risk >= 12) {
                    riskClass = 'risk-badge-high';
                } else if (risk >= 8) {
                    riskClass = 'risk-badge-medium';
                }
                
                // Escape HTML to prevent XSS
                const ip = escapeHtml(clientData.ip || 'Unknown');
                const clientKey = escapeHtml(clientData.client_key || '');
                const blockedAt = escapeHtml(clientData.blocked_at || '--');
                const expiresAt = escapeHtml(clientData.expires_at || '--');
                const expiryRelative = escapeHtml(clientData.expiry_relative || '--');
                const ttl = escapeHtml(clientData.ttl || '--');
                // Convert reason codes to descriptions
                const reasons = Array.isArray(clientData.reasons) ? 
                    clientData.reasons.map(r => getReasonDescription(r)).join(', ') : 
                    'Unknown';
                
                div.innerHTML = `
                    <div class="d-flex justify-content-between align-items-start">
                        <div style="flex-grow: 1;">
                            <div class="bot-block-ip">
                                🔒 ${ip}
                                <span class="badge ${riskClass}" style="margin-left: 8px;">Risk: ${riskSeverity} (${risk})</span>
                            </div>
                            <div class="bot-block-details">
                                <div><strong>Blocked at:</strong> ${blockedAt}</div>
                                <div><strong>Expires at:</strong> ${expiresAt} (${expiryRelative})</div>
                                <div><strong>TTL:</strong> ${ttl}s</div>
                                <div><strong>Reasons:</strong> ${reasons}</div>
                                <div><strong>Status:</strong> ${escapeHtml(clientData.status || 'active')}</div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-secondary ms-2" onclick="removeBotProtectionBlockedIP('${clientKey}')">
                            Remove
                        </button>
                    </div>
                `;
                container.appendChild(div);
            });
        }
    }

    /**
     * Remove a specific bot protection blocked IP
     * @param {string} clientKey - The client key to remove
     */
    function removeBotProtectionBlockedIP(clientKey) {
        if (!confirm(`Remove bot protection block for client: ${clientKey}?`)) return;
        
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-remove-bot-protection-blocked-ip',
                client_key: clientKey,
                _wpnonce: '<?php echo $nonce; ?>',
            },
            timeout: 30000,
            error: function(jqXHR, textStatus) {
                console.log('Failed to remove bot protection block:', textStatus);
                alert('Failed to remove bot protection block');
            },
            success: function(response) {
                if (!response.success) {
                    console.log('Server error:', response.data?.message);
                    alert(response.data?.message || 'Failed to remove bot protection block');
                    return;
                }
                
                // Refresh the list
                renderBotProtectionBlockedList();
                alert('Bot protection block removed successfully');
            }
        });
    }

    /**
     * Clear all bot protection blocked IPs
     * Called via onclick handler on the clear button
     */
    function clearAllBotProtectionBlockedIPs() {
        if (!confirm('Clear all bot protection blocks? This will immediately unblock all currently blocked clients.')) {
            return;
        }

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-clear-all-bot-protection-blocked-ips',
                _wpnonce: '<?php echo $nonce; ?>',
            },
            timeout: 30000,
            error: function(jqXHR, textStatus) {
                console.log('Failed to clear all bot protection blocks:', textStatus);
                alert('Failed to clear all bot protection blocks');
            },
            success: function(response) {
                if (!response.success) {
                    console.log('Server error:', response.data?.message);
                    alert(response.data?.message || 'Failed to clear all bot protection blocks');
                    return;
                }
                
                // Refresh the list
                renderBotProtectionBlockedList();
                alert('All bot protection blocks cleared successfully');
            }
        });
    }

    /**
     * Escape HTML to prevent XSS vulnerabilities
     * @param {string|number|any} text - Text to escape
     * @return {string} Escaped text
     */
    function escapeHtml(text) {
        // Convert to string first in case it's a number or other type
        const str = String(text || '');
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return str.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

</script>
