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

<script type="text/javascript">

(function() {
    'use strict';

    const REFRESH_INTERVAL = 30000; // 30 seconds
    let autoRefreshTimer = null;

    /**
     * Initialize dashboard on page load
     */
    jQuery(document).ready(function($) {
        console.log('Dashboard Frontend: Initializing...');
        
        // Fetch initial statistics
        updateBruteForceStatistics();
        updateBotProtectionStatistics();
        
        // Set up auto-refresh every 30 seconds
        autoRefreshTimer = setInterval(function() {
            updateBruteForceStatistics();
            updateBotProtectionStatistics();
        }, REFRESH_INTERVAL);
        
        console.log('Dashboard Frontend: Auto-refresh enabled (every ' + (REFRESH_INTERVAL / 1000) + 's)');
    });

    /**
     * Fetch and update Brute-Force Protection Statistics
     */
    function updateBruteForceStatistics() {
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-get-bruteforce-stats',
                _wpnonce: '<?php echo $nonce; ?>'
            },
            timeout: 10000,
            success: function(response) {
                if (response.success && response.data) {
                    // Update status
                    const statusElement = document.getElementById('dashboard-bf-status');
                    if (statusElement) {
                        statusElement.textContent = response.data.status;
                        // Add visual indicator
                        statusElement.className = response.data.status === 'Enabled' 
                            ? 'badge bg-success' 
                            : 'badge bg-danger';
                    }
                    
                    // Update blocked IPs and whitelisted IPs count (combined display)
                    const blockedElement = document.getElementById('dashboard-bf-blocked');
                    const whitelistElement = document.getElementById('dashboard-bf-whitelist');
                    
                    if (blockedElement) {
                        blockedElement.textContent = response.data.blocked_ips;
                        // Add visual indicator if IPs are blocked
                        if (response.data.blocked_ips > 0) {
                            blockedElement.style.color = '#dc3545'; // Red
                        } else {
                            blockedElement.style.color = '#17a2b8'; // Teal
                        }
                    }
                    
                    if (whitelistElement) {
                        whitelistElement.textContent = response.data.whitelist_ips || 0;
                        // Add visual indicator for whitelisted count
                        if (response.data.whitelist_ips > 0) {
                            whitelistElement.style.color = '#28a745'; // Green
                        } else {
                            whitelistElement.style.color = '#17a2b8'; // Teal
                        }
                    }
                    
                    // Note: expiring_soon removed as it's no longer displayed in the combined view
                    console.log('Brute-Force stats updated:', response.data);
                }
            },
            error: function(jqXHR, textStatus) {
                console.error('Failed to fetch brute-force statistics:', textStatus);
            }
        });
    }

    /**
     * Fetch and update Bot Protection Statistics
     */
    function updateBotProtectionStatistics() {
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-get-botprotection-stats',
                _wpnonce: '<?php echo $nonce; ?>'
            },
            timeout: 10000,
            success: function(response) {
                if (response.success && response.data) {
                    // Update status
                    const statusElement = document.getElementById('dashboard-bp-status');
                    if (statusElement) {
                        statusElement.textContent = response.data.status;
                        // Add visual indicator
                        statusElement.className = response.data.status === 'Enabled' 
                            ? 'badge bg-success' 
                            : 'badge bg-danger';
                    }
                    
                    // Update blocked clients count (blocked addresses)
                    const blockedElement = document.getElementById('dashboard-bp-blocked');
                    if (blockedElement) {
                        blockedElement.textContent = response.data.blocked_clients;
                        // Add visual indicator if clients are blocked
                        if (response.data.blocked_clients > 0) {
                            blockedElement.style.color = '#dc3545'; // Red
                        } else {
                            blockedElement.style.color = '#17a2b8'; // Green
                        }
                    }
                    
                    // Update critical risk count
                    const criticalElement = document.getElementById('dashboard-bp-critical');
                    if (criticalElement) {
                        criticalElement.textContent = response.data.critical_risk;
                        // Add visual indicator if critical risks exist
                        if (response.data.critical_risk > 0) {
                            criticalElement.style.color = '#dc3545'; // Red
                        } else {
                            criticalElement.style.color = '#17a2b8'; // Green
                        }
                    }
                    
                    // Update expiring soon count
                    const expiringElement = document.getElementById('dashboard-bp-expiring');
                    if (expiringElement) {
                        expiringElement.textContent = response.data.expiring_soon;
                        // Add visual indicator if any are expiring soon
                        if (response.data.expiring_soon > 0) {
                            expiringElement.style.color = '#fd7e14'; // Orange
                        } else {
                            expiringElement.style.color = '#17a2b8'; // Teal
                        }
                    }
                    
                    console.log('Bot Protection stats updated:', response.data);
                }
            },
            error: function(jqXHR, textStatus) {
                console.error('Failed to fetch bot protection statistics:', textStatus);
            }
        });
    }

    /**
     * Manual refresh function (can be called by button)
     */
    window.refreshProtectionStats = function() {
        console.log('Manual refresh triggered');
        updateBruteForceStatistics();
        updateBotProtectionStatistics();
    };

    /**
     * Stop auto-refresh (cleanup on page unload)
     */
    window.addEventListener('beforeunload', function() {
        if (autoRefreshTimer) {
            clearInterval(autoRefreshTimer);
        }
    });

    /**
     * Populate alarm details modal with data
     * @param {Object} alarm - The alarm data object
     */
    window.populateAlarmModal = function(alarm) {
        // Store alarm ID for acknowledgment action
        window.currentAlarmId = alarm.id || null;
        
        // Populate basic fields and update modal title
        document.getElementById('alarmDetailsLabel').textContent = 'Alarm ' + (alarm.id || '-') + ' Details';
        document.getElementById('modal-alarm-severity').innerHTML = '<span class="q-sev ' + 
            (alarm.severity === 'critical' ? 'q-sev-critical' : alarm.severity === 'error' ? 'q-sev-high' : 'q-sev-medium') + 
            '">' + (alarm.severity || '-').toUpperCase() + '</span>';
        document.getElementById('modal-alarm-status').textContent = alarm.status || '-';
        document.getElementById('modal-alarm-type').textContent = alarm.id || '-';
        document.getElementById('modal-alarm-created').textContent = alarm.created_at || '-';
        document.getElementById('modal-alarm-time').textContent = alarm.time || '-';
        document.getElementById('modal-alarm-target').textContent = alarm.target || '-';
        
        // Show/hide acknowledged info
        if (alarm.status === 'Acknowledged') {
            document.getElementById('modal-ack-by-row').style.display = 'table-row';
            document.getElementById('modal-ack-at-row').style.display = 'table-row';
            document.getElementById('modal-alarm-ack-by').textContent = alarm.ack_by || '-';
            document.getElementById('modal-alarm-ack-at').textContent = alarm.ack_at || '-';
            document.getElementById('modal-btn-acknowledge').style.display = 'none';
        } else {
            document.getElementById('modal-ack-by-row').style.display = 'none';
            document.getElementById('modal-ack-at-row').style.display = 'none';
            document.getElementById('modal-btn-acknowledge').style.display = 'block';
        }
    };

    /**
     * Fetch and update alarms list via AJAX
     */
    function updateAlarmsList() {
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-get-alarms',
                _wpnonce: '<?php echo $nonce; ?>'
            },
            success: function(response) {
                if (response.success && response.data) {
                    const tbody = document.querySelector('#alarms-table tbody');
                    if (!tbody) {
                        console.warn('Alarms table body not found');
                        return;
                    }
                    
                    // Clear existing rows
                    tbody.innerHTML = '';
                    
                    // If no alarms, show empty message
                    if (!response.data || response.data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="6" class="text-center q-muted">No alarms</td></tr>';
                        return;
                    }
                    
                    // Rebuild table with updated alarms
                    response.data.forEach(function(alarm) {
                        console.log('Alarm object:', alarm);
                        
                        const sev = (alarm.severity || 'info').toLowerCase();
                        let sevClass = 'q-sev-info';
                        if (sev === 'critical') sevClass = 'q-sev-critical';
                        if (sev === 'warning') sevClass = 'q-sev-medium';                        
                        if (sev === 'high' || sev === 'error') sevClass = 'q-sev-high';

                        const row = document.createElement('tr');
                        row.id = 'alarm-table-row-' + alarm.id;
                        row.innerHTML = `
                            <td><span class="q-sev ${sevClass}">${sev.charAt(0).toUpperCase() + sev.slice(1)}</span></td>
                            <td><b>${alarm.id || '-'}</b></td>
                            <td class="q-muted" title="${alarm.target || ''}">${alarm.target || '-'}</td>
                            <td class="q-muted">${alarm.time || '-'}</td>
                            <td>${alarm.status || '-'}</td>
                            <td>
                                <button class="btn btn-sm bg-white text-info fw-bold m-3 ms-auto rounded-3" style="border-color:#00BFFF;" data-bs-toggle="modal" data-bs-target="#alarmDetailsModal" onclick="populateAlarmModal(${JSON.stringify(alarm).replace(/"/g, '&quot;')});">Details</button>
                                <button class="btn btn-sm text-white fw-bold rounded-3" style="background-color:#00BFFF" onclick="acknowledgeAlarm(${alarm.id});">Resolve</button>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                    
                    console.log('Alarms list updated:', response.data.length + ' alarms');
                }
            },
            error: function(jqXHR, textStatus) {
                console.error('Failed to fetch alarms list:', textStatus);
            }
        });
    }

    /**
     * Acknowledge/Resolve an alarm via AJAX
     * @param {number} alarmId - The alarm ID to acknowledge
     */
    window.acknowledgeAlarm = function(alarmId) {
        if (!alarmId) {
            alert('Invalid alarm ID');
            return;
        }

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'scanner-acknowledge_alarm',
                alarm_id: alarmId,
                _wpnonce: '<?php echo $nonce; ?>'
            },
            success: function(response) {
                if (response.success) {
                    // Hide the row if in table view
                    const rowElement = document.getElementById('alarm-table-row-' + alarmId);
                    if (rowElement) {
                        rowElement.style.display = 'none';
                    }
                    
                    // Close modal if open
                    const modal = document.getElementById('alarmDetailsModal');
                    if (modal) {
                        const bootstrapModal = bootstrap.Modal.getInstance(modal);
                        if (bootstrapModal) {
                            bootstrapModal.hide();
                        }
                    }
                                        
                    // Refresh the alarms list without changing tabs
                    updateAlarmsList();
                } else {
                    alert('Error: ' + (response.data?.message || 'Failed to acknowledge alarm'));
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('AJAX Error:', textStatus, errorThrown);
                alert('Error: ' + textStatus);
            }
        });
    };

})();

</script>
