<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

call_user_func(
    static function () {
        $mitigation_manager = Vulnity_Mitigation_Manager::get_instance();
        $stats = $mitigation_manager->get_statistics();
        $blocked_ips = $mitigation_manager->get_blocked_ips();
        $whitelist = $mitigation_manager->get_whitelist();
        $rules = $mitigation_manager->get_mitigation_rules();
        $sync_info = $mitigation_manager->get_last_sync_info();
        ?>


<div class="vulnity-mitigation-wrap">
    
    <div class="vulnity-mitigation-tabs">
        <button type="button" class="vulnity-mitigation-tab active" data-tab="mitigation-overview">Overview</button>
        <button type="button" class="vulnity-mitigation-tab" data-tab="mitigation-synchronization">Synchronization</button>
        <button type="button" class="vulnity-mitigation-tab" data-tab="mitigation-blocked">Blocked IPs</button>
        <button type="button" class="vulnity-mitigation-tab" data-tab="mitigation-rules">Mitigation Rules</button>
        <button type="button" class="vulnity-mitigation-tab" data-tab="mitigation-whitelist">Whitelist</button>
    </div>
    
    <div class="vulnity-mitigation-content active" id="mitigation-tab-mitigation-overview">
        <div class="vulnity-stats-grid">
            <div class="vulnity-stat-card">
                <div class="vulnity-stat-value"><?php echo esc_html( $stats['total_blocked'] ); ?></div>
                <div class="vulnity-stat-label">Blocked IPs</div>
            </div>
            <div class="vulnity-stat-card">
                <div class="vulnity-stat-value"><?php echo esc_html( $stats['blocks_by_source']['auto_block'] ?? 0 ); ?></div>
                <div class="vulnity-stat-label">Auto-blocked</div>
            </div>
            <div class="vulnity-stat-card">
                <div class="vulnity-stat-value"><?php echo esc_html( $stats['whitelisted'] ); ?></div>
                <div class="vulnity-stat-label">Whitelisted</div>
            </div>
            <div class="vulnity-stat-card">
                <div class="vulnity-stat-value"><?php echo esc_html( $stats['active_rules'] ); ?></div>
                <div class="vulnity-stat-label">Active Rules</div>
            </div>
        </div>
        
        <div class="vulnity-card">
            <h2>Mitigation Status</h2>
            <table class="vulnity-table">
                <tbody>
                    <tr>
                        <td><strong>Blocking Method:</strong></td>
                        <td>
                            <span class="vulnity-status vulnity-status-active">
                                <span class="vulnity-status-dot"></span>
                                PHP-based blocking (Universal compatibility)
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Blocking Status:</strong></td>
                        <td>
                            <?php if ($stats['php_blocking_active']): ?>
                                <span class="vulnity-badge vulnity-badge-success">Active and Operational</span>
                            <?php else: ?>
                                <span class="vulnity-badge vulnity-badge-danger">Inactive</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Last Synchronization:</strong></td>
                        <td>
                            <?php if ($sync_info['status'] === 'never'): ?>
                                <span style="color: #ff9800;">Never synchronized</span>
                            <?php else: ?>
                                <?php echo esc_html( human_time_diff( strtotime( $sync_info['timestamp'] ), current_time( 'timestamp' ) ) ); ?> ago
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Automatic Sync:</strong></td>
                        <td>Every 24 hours (automatic)</td>
                    </tr>
                    <tr>
                        <td><strong>Block Page:</strong></td>
                        <td>Professional branded page with block details</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <div class="vulnity-card">
            <h2>Block Statistics by Source</h2>
            <table class="vulnity-table">
                <thead>
                    <tr>
                        <th>Source</th>
                        <th>Count</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Auto-blocked</strong></td>
                        <td><span class="vulnity-badge vulnity-badge-info"><?php echo esc_html( $stats['blocks_by_source']['auto_block'] ?? 0 ); ?></span></td>
                        <td>IPs automatically blocked by mitigation rules when thresholds are exceeded</td>
                    </tr>
                    <tr>
                        <td><strong>Manual blocks</strong></td>
                        <td><span class="vulnity-badge vulnity-badge-warning"><?php echo esc_html( $stats['blocks_by_source']['manual_block'] ?? 0 ); ?></span></td>
                        <td>IPs manually blocked by administrators through the dashboard</td>
                    </tr>
                    <tr>
                        <td><strong>SIEM Sync</strong></td>
                        <td><span class="vulnity-badge vulnity-badge-info"><?php echo esc_html( $stats['blocks_by_source']['siem_sync'] ?? 0 ); ?></span></td>
                        <td>IPs blocked from SIEM configuration sync</td>
                    </tr>
                    <tr>
                        <td><strong>Vulnity Blacklist</strong></td>
                        <td><span class="vulnity-badge vulnity-badge-danger"><?php echo esc_html( $stats['blocks_by_source']['vulnity_blacklist'] ?? 0 ); ?></span></td>
                        <td>IPs from Vulnity global threat intelligence blacklist</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
        <div class="vulnity-mitigation-content" id="mitigation-tab-mitigation-synchronization" style="display: none;">
            <?php
            $sync_status = $sync_info['status'] ?? 'never';
            $sync_status_label = 'Never synced';
            $sync_status_class = 'is-warning';

            if ( 'success' === $sync_status ) {
                $sync_status_label = 'Synchronized';
                $sync_status_class = 'is-success';
            } elseif ( 'failed' === $sync_status ) {
                $sync_status_label = 'Last sync failed';
                $sync_status_class = 'is-danger';
            }
            ?>

            <div class="vulnity-mitigation-sync-shell">
                <div class="vulnity-mitigation-sync-header">
                    <div>
                        <h2>SIEM Configuration Synchronization</h2>
                        <p>Keep mitigation rules, whitelist entries, and blocked IPs aligned with your SIEM dashboard.</p>
                    </div>
                    <span class="vulnity-mitigation-sync-pill <?php echo esc_attr( $sync_status_class ); ?>">
                        <?php echo esc_html( $sync_status_label ); ?>
                    </span>
                </div>

                <div class="vulnity-mitigation-sync-panel">
                    <h3>Synchronization Status</h3>
                    <div class="vulnity-mitigation-sync-rows">
                        <div class="vulnity-mitigation-sync-row">
                            <span class="sync-label">Last sync</span>
                            <div class="sync-value">
                                <?php if ( 'never' === $sync_status ) : ?>
                                    <strong>Never synchronized</strong>
                                    <small>Use the button below to run your first synchronization.</small>
                                <?php else : ?>
                                    <?php
                                    $sync_timestamp = strtotime( $sync_info['timestamp'] );
                                    if ( false === $sync_timestamp ) {
                                        $sync_timestamp = 0;
                                    }
                                    ?>
                                    <strong><?php echo esc_html( human_time_diff( $sync_timestamp, current_time( 'timestamp' ) ) ); ?> ago</strong>
                                    <?php if ( 'success' === $sync_status ) : ?>
                                        <span class="vulnity-mitigation-sync-inline-badge is-success">Success</span>
                                    <?php else : ?>
                                        <span class="vulnity-mitigation-sync-inline-badge is-danger">Failed</span>
                                    <?php endif; ?>
                                    <small><?php echo esc_html( wp_date( 'F j, Y g:i A', $sync_timestamp ) ); ?></small>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="vulnity-mitigation-sync-row">
                            <span class="sync-label">Next auto sync</span>
                            <div class="sync-value">
                                <?php
                                $next_sync = wp_next_scheduled( 'vulnity_sync_mitigation_config' );
                                if ( $next_sync ) :
                                    ?>
                                    <strong>In <?php echo esc_html( human_time_diff( current_time( 'timestamp' ), $next_sync ) ); ?></strong>
                                    <small><?php echo esc_html( wp_date( 'F j, Y g:i A', $next_sync ) ); ?></small>
                                <?php else : ?>
                                    <strong>Not scheduled</strong>
                                    <small>Check your cron configuration and run a manual sync.</small>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="vulnity-mitigation-sync-row">
                            <span class="sync-label">Sync frequency</span>
                            <div class="sync-value">
                                <strong>Every 24 hours</strong>
                                <small>Manual synchronization is available at any time.</small>
                            </div>
                        </div>

                        <?php if ( ! empty( $sync_info['last_updated'] ) ) : ?>
                            <div class="vulnity-mitigation-sync-row">
                                <span class="sync-label">SIEM updated</span>
                                <div class="sync-value">
                                    <strong><?php echo esc_html( $sync_info['last_updated'] ); ?></strong>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="vulnity-mitigation-sync-action">
                        <button type="button" class="button button-sync-primary" id="sync-mitigation-btn" onclick="vulnitySyncMitigationConfig()">
                            Sync Configuration Now
                        </button>
                        <div id="sync-mitigation-result" class="vulnity-mitigation-sync-result"></div>
                    </div>
                </div>

                <div class="vulnity-mitigation-sync-grid">
                    <div class="vulnity-mitigation-sync-note">
                        <h3>What gets synchronized</h3>
                        <ul class="vulnity-mitigation-sync-list">
                            <li><strong>Mitigation rules:</strong> Automatic block thresholds and conditions.</li>
                            <li><strong>Whitelist:</strong> IPs that are exempt from automatic blocking.</li>
                            <li><strong>Blocked IPs:</strong> Centrally managed blocked addresses.</li>
                            <li><strong>Security policies:</strong> Configuration metadata distributed from SIEM.</li>
                        </ul>
                    </div>

                    <div class="vulnity-mitigation-sync-note">
                        <h3>Security note</h3>
                        <p>Configuration is managed centrally in the SIEM to keep all connected sites consistent.</p>
                        <p>Local blocks created manually in WordPress are preserved during synchronization.</p>
                        <p>Synchronization uses authenticated API communication between this site and the SIEM backend.</p>
                    </div>
                </div>
            </div>
    </div>

    <div class="vulnity-mitigation-content" id="mitigation-tab-mitigation-blocked" style="display: none;">
        <div class="vulnity-card">
            <h2>Manual IP Blocking</h2>
            <form id="manual-block-form" class="vulnity-form-inline">
                <input type="hidden" name="nonce" value="<?php echo esc_attr( wp_create_nonce( 'vulnity_nonce' ) ); ?>" />
                <input type="text" id="block-ip" placeholder="IP Address (e.g., 192.168.1.1)" />
                <input type="text" id="block-reason" placeholder="Reason for blocking" />
                <select id="block-duration">
                    <option value="15m">15 Minutes</option>
                    <option value="30m">30 Minutes</option>
                    <option value="1h">1 Hour</option>
                    <option value="6h">6 Hours</option>
                    <option value="24h">24 Hours</option>
                    <option value="7d">7 Days</option>
                    <option value="30d">30 Days</option>
                    <option value="permanent">Permanent</option>
                </select>
                <button type="submit" class="button button-primary">Block IP</button>
            </form>
        </div>
        
        <div class="vulnity-card">
            <h2>Currently Blocked IP Addresses (<?php echo esc_html( number_format_i18n( count( $blocked_ips ) ) ); ?>)</h2>
            
            <?php if (empty($blocked_ips)): ?>
                <div class="vulnity-empty-state">
                    
                    <div class="vulnity-empty-state-title">No Blocked IPs</div>
                    <div class="vulnity-empty-state-text">No IP addresses are currently blocked. IPs will appear here when they are blocked manually or by mitigation rules.</div>
                </div>
            <?php else: ?>
                <div class="vulnity-blocked-bulk-toolbar">
                    <div class="vulnity-bulk-actions">
                        <button type="button" id="bulk-unblock-btn" class="button button-secondary" disabled>Unblock Selected</button>
                        <span id="bulk-selection-count">0 IPs selected</span>
                    </div>
                    <div class="vulnity-bulk-hint">Select multiple addresses to unblock them in a single action.</div>
                </div>
                <table class="vulnity-table">
                    <thead>
                        <tr>
                            <th class="vulnity-col-select"><input type="checkbox" id="blocked-select-all" /></th>
                            <th>IP Address</th>
                            <th>Reason</th>
                            <th>Blocked Since</th>
                            <th>Expires</th>
                            <th>Source</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($blocked_ips as $ip => $data): ?>
                            <tr>
                                <td class="vulnity-col-select">
                                    <input type="checkbox" class="blocked-select" value="<?php echo esc_attr($ip); ?>" />
                                </td>
                                <td>
                                    <strong style="font-size: 14px;"><?php echo esc_html($ip); ?></strong>
                                </td>
                                <td>
                                    <?php echo esc_html(ucwords(str_replace('_', ' ', $data['reason']))); ?>
                                </td>
                                <td>
                                    <?php
                                    $blocked_timestamp = strtotime( $data['blocked_at'] );
                                    if ( false === $blocked_timestamp ) {
                                        $blocked_timestamp = 0;
                                    }
                                    echo esc_html( wp_date( 'M j, Y g:i A', $blocked_timestamp ) );
                                    ?>
                                </td>
                                <td>
                                    <?php if (isset($data['permanent']) && $data['permanent']): ?>
                                        <span class="vulnity-badge vulnity-badge-permanent">Permanent</span>
                                    <?php elseif (isset($data['blocked_until'])): ?>
                                        <?php 
                                        $expires_timestamp = strtotime($data['blocked_until']);
                                        if ($expires_timestamp > time()): ?>
                                            <span title="<?php echo esc_attr( wp_date( 'M j, Y g:i A', $expires_timestamp ) ); ?>">
                                                In <?php echo esc_html( human_time_diff( time(), $expires_timestamp ) ); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="vulnity-badge">Expired</span>
                                        <?php endif; ?>
                                    <?php elseif (isset($data['expires_at'])): ?>
                                        <?php
                                        $expires_at_timestamp = strtotime( $data['expires_at'] );
                                        if ( false === $expires_at_timestamp ) {
                                            $expires_at_timestamp = 0;
                                        }
                                        echo esc_html( wp_date( 'M j, Y g:i A', $expires_at_timestamp ) );
                                        ?>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php 
                                    $source_badges = array(
                                        'auto_block' => array('label' => 'Auto', 'class' => 'info'),
                                        'manual_block' => array('label' => 'Manual', 'class' => 'warning'),
                                        'siem_blacklist' => array('label' => 'SIEM', 'class' => 'info'),
                                        'vulnity_blacklist' => array('label' => 'Vulnity', 'class' => 'danger'),
                                        'siem_sync' => array('label' => 'Sync', 'class' => 'info')
                                    );
                                    $source = isset($data['source']) ? $data['source'] : 'unknown';
                                    $badge_info = isset($source_badges[$source]) ? $source_badges[$source] : array('label' => $source, 'class' => 'info');
                                    ?>
                                    <span class="vulnity-badge vulnity-badge-<?php echo esc_attr( $badge_info['class'] ); ?>">
                                        <?php echo esc_html( $badge_info['label'] ); ?>
                                    </span>
                                </td>
                                <td>
                                    <button type="button" 
                                            class="vulnity-action-btn vulnity-action-btn-danger"
                                            onclick="vulnityUnblockIP('<?php echo esc_js($ip); ?>')">
                                        Unblock
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="vulnity-mitigation-content" id="mitigation-tab-mitigation-rules" style="display: none;">
        <div class="vulnity-card">
            <h2>Automated Mitigation Rules</h2>
            <p style="margin-bottom: 20px;">These rules automatically block IP addresses when specific thresholds are exceeded. Rules are managed from the SIEM dashboard and synced to your site.</p>
            
            <?php if (empty($rules)): ?>
                <div class="vulnity-alert vulnity-alert-warning">
                    <strong>No mitigation rules configured yet.</strong><br>
                    Go to the Synchronization tab and click "Sync Configuration Now" to fetch the latest rules from your SIEM dashboard.
                </div>
            <?php else: ?>
                <table class="vulnity-table">
                    <thead>
                        <tr>
                            <th style="width: 20%;">Alert Type</th>
                            <th style="width: 12%;">Status</th>
                            <th style="width: 12%;">Threshold</th>
                            <th style="width: 12%;">Time Window</th>
                            <th style="width: 12%;">Min Severity</th>
                            <th style="width: 32%;">Rule Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rules as $rule): ?>
                            <?php 
                            $alert_type = isset($rule['alertType']) ? $rule['alertType'] : (isset($rule['alert_type']) ? $rule['alert_type'] : 'unknown');
                            $min_severity = isset($rule['minSeverity']) ? $rule['minSeverity'] : (isset($rule['min_severity']) ? $rule['min_severity'] : 'low');
                            
                            $display_type = ucwords(str_replace('_', ' ', $alert_type));
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo esc_html($display_type); ?></strong>
                                </td>
                                <td>
                                    <?php if ($rule['enabled']): ?>
                                        <span class="vulnity-status vulnity-status-active">
                                            <span class="vulnity-status-dot"></span>
                                            Enabled
                                        </span>
                                    <?php else: ?>
                                        <span class="vulnity-status vulnity-status-inactive">
                                            <span class="vulnity-status-dot"></span>
                                            Disabled
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo esc_html($rule['threshold']); ?></strong> alerts
                                </td>
                                <td>
                                    <?php 
                                    $duration = $rule['duration'];
                                    $duration_display = str_replace(
                                        array('1h', '6h', '24h', '7d', '30d'),
                                        array('1 hour', '6 hours', '24 hours', '7 days', '30 days'),
                                        $duration
                                    );
                                    echo esc_html($duration_display);
                                    ?>
                                </td>
                                <td>
                                    <span class="vulnity-severity vulnity-severity-<?php echo esc_attr( $min_severity ); ?>">
                                        <?php echo esc_html( ucfirst( $min_severity ) ); ?>
                                    </span>
                                </td>
                                <td>
                                    Automatically block IP after detecting 
                                    <strong><?php echo esc_html( $rule['threshold'] ); ?></strong>
                                    <?php echo esc_html( strtolower( $display_type ) ); ?> alerts
                                    of severity <strong><?php echo esc_html( $min_severity ); ?></strong> or higher
                                    within <strong><?php echo esc_html( $duration_display ); ?></strong>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <div class="vulnity-alert vulnity-alert-info" style="margin-top: 25px;">
                    <strong>How it works:</strong> Mitigation rules are configured in your SIEM dashboard and automatically synced every 24 hours. 
                    When an IP address triggers a rule threshold, it's automatically blocked for the specified duration. 
                    Changes made in the SIEM will be reflected here after the next sync.
                </div>
            <?php endif; ?>
        </div>
    </div>
    
        <div class="vulnity-mitigation-content" id="mitigation-tab-mitigation-whitelist" style="display: none;">
        <div class="vulnity-card">
            <h2>IP Address Whitelist</h2>
            <div class="vulnity-whitelist-banner">
                <div>
                    <strong>Whitelist managed from SIEM</strong>
                    <p>For security reasons, allowed addresses are managed only from SIEM. Use the SIEM dashboard to add or remove trusted IPs, then synchronize to keep this list updated.</p>
                </div>
            </div>
            <p style="margin-bottom: 20px;">Whitelisted IP addresses are protected from automatic blocking. These IPs are never blocked regardless of alert activity or mitigation rules.</p>

            <div style="display:flex; align-items:center; gap:12px; margin-bottom:20px;">
                <label class="vulnity-switch" for="suppress_whitelist_alerts">
                    <input type="checkbox" id="suppress_whitelist_alerts" <?php checked(get_option('vulnity_suppress_blocked_alerts', true)); ?> />
                    <span class="vulnity-slider"></span>
                </label>
                <div>
                    <label class="vulnity-toggle-title" for="suppress_whitelist_alerts" style="cursor:pointer;"><b>Suppress alerts for whitelisted IPs</b></label>
                    <p style="margin:2px 0 0; color:#666; font-size:13px;">When enabled, security events originating from whitelisted IPs do not create alerts.</p>
                </div>
            </div>
            <script>
            (function() {
                var toggle = document.getElementById('suppress_whitelist_alerts');
                if (!toggle) return;
                toggle.addEventListener('change', function() {
                    var fd = new FormData();
                    fd.append('action', 'vulnity_save_suppress_blocked_alerts');
                    fd.append('enabled', this.checked ? '1' : '0');
                    fd.append('nonce', '<?php echo esc_js(wp_create_nonce('vulnity_nonce')); ?>');
                    fetch(ajaxurl, { method: 'POST', body: fd });
                });
            })();
            </script>

            <?php if (empty($whitelist)): ?>
                <div class="vulnity-empty-state">
                    <div class="vulnity-empty-state-title">No Whitelisted IPs</div>
                    <div class="vulnity-empty-state-text">
                        No IP addresses are currently whitelisted.<br>
                        Add trusted IPs from your SIEM dashboard and sync to update.
                    </div>
                    <button type="button" class="button button-primary" onclick="document.querySelector('[data-tab=mitigation-synchronization]').click()">
                        Go to Synchronization
                    </button>
                </div>
            <?php else: ?>
                <table class="vulnity-table">
                    <thead>
                        <tr>
                            <th style="width: 30%;">IP Address</th>
                            <th style="width: 20%;">Status</th>
                            <th style="width: 50%;">Protection Level</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($whitelist as $index => $ip): ?>
                            <tr>
                                <td>
                                    <strong style="font-size: 15px;"><?php echo esc_html($ip); ?></strong>
                                </td>
                                <td>
                                    <span class="vulnity-badge vulnity-badge-success">Whitelisted</span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                                        <span class="vulnity-badge">Auto-block Immune</span>
                                        <span class="vulnity-badge">Manual Block Protected</span>
                                        <span class="vulnity-badge">Always Allowed</span>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

            <?php endif; ?>
        </div>
    </div>

</div>
<?php
    }
);
