<?php
/**
 * WAF Rules Admin View
 *
 * @package VMPFence
 * @since 2.0.0
 * @since 2.2.1 Updated text-domain to vmpfence-security
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Handle install default rules
if (isset($_POST['install_defaults']) && check_admin_referer('vmpfence_waf_install_defaults')) {
    $installed = VMPFence_WAF_Rule::install_default_rules();
    echo '<div class="notice notice-success"><p>' . sprintf(__('%d default rules installed successfully.', 'vmpfence-security'), $installed) . '</p></div>';
}

// Enqueue toast notification system
wp_enqueue_style('vmpfence-toast-notifications', plugins_url('assets/css/toast-notifications.css', dirname(__FILE__)), array(), '1.0.3');
wp_enqueue_script('vmpfence-toast-notifications', plugins_url('assets/js/toast-notifications.js', dirname(__FILE__)), array('jquery'), '1.0.3', true);

// Get all rules
$rules = VMPFence_WAF_Rule::get_all();

// Get unique categories from actual rules
global $wpdb;
$categories_raw = $wpdb->get_col("SELECT DISTINCT category FROM {$wpdb->prefix}vmpfence_waf_rules ORDER BY category");
$categories = !empty($categories_raw) ? $categories_raw : array();

$actions = array('block', 'log');

// Filter
$filter_category = isset($_GET['category']) ? sanitize_text_field($_GET['category']) : '';
$filter_action = isset($_GET['action_filter']) ? sanitize_text_field($_GET['action_filter']) : '';

if ($filter_category) {
    $rules = array_filter($rules, function($rule) use ($filter_category) {
        return $rule['category'] === $filter_category;
    });
}

if ($filter_action) {
    $rules = array_filter($rules, function($rule) use ($filter_action) {
        return $rule['action'] === $filter_action;
    });
}
?>

<!-- Toast Notification Container -->
<?php require_once plugin_dir_path(__FILE__) . 'partials/toast-notification-container.php'; ?>

<div class="wrap">
    <h1><?php _e('WAF Rules Management', 'vmpfence-security'); ?></h1>

    <div class="card" style="max-width: none;">
        <h2><?php _e('Web Application Firewall Rules', 'vmpfence-security'); ?></h2>
        <p><?php _e('Manage firewall rules to protect your website against common attacks like XSS, SQL Injection, RFI, LFI, and RCE.', 'vmpfence-security'); ?></p>

        <?php if (empty($rules)): ?>
        <div class="notice notice-warning inline">
            <p><?php _e('No WAF rules found. Install default rules to get started.', 'vmpfence-security'); ?></p>
        </div>

        <form method="post" style="margin-top: 20px;">
            <?php wp_nonce_field('vmpfence_waf_install_defaults'); ?>
            <button type="submit" name="install_defaults" class="button button-primary">
                <?php _e('Install Default Rules', 'vmpfence-security'); ?>
            </button>
        </form>
        <?php else: ?>

        <!-- Filters -->
        <div style="margin: 20px 0; padding: 15px; background: #f9f9f9; border-radius: 4px;">
            <form method="get" style="display: flex; gap: 10px; align-items: center;">
                <input type="hidden" name="page" value="<?php echo esc_attr($_GET['page'] ?? ''); ?>" />
                <input type="hidden" name="view" value="<?php echo esc_attr($_GET['view'] ?? ''); ?>" />
                
                <label for="category"><?php _e('Category:', 'vmpfence-security'); ?></label>
                <select name="category" id="category">
                    <option value=""><?php _e('All Categories', 'vmpfence-security'); ?></option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo esc_attr($cat); ?>" <?php selected($filter_category, $cat); ?>>
                        <?php echo esc_html($cat); ?>
                    </option>
                    <?php endforeach; ?>
                </select>

                <label for="action_filter"><?php _e('Action:', 'vmpfence-security'); ?></label>
                <select name="action_filter" id="action_filter">
                    <option value=""><?php _e('All Actions', 'vmpfence-security'); ?></option>
                    <?php foreach ($actions as $act): ?>
                    <option value="<?php echo esc_attr($act); ?>" <?php selected($filter_action, $act); ?>>
                        <?php echo esc_html(ucfirst($act)); ?>
                    </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit" class="button"><?php _e('Filter', 'vmpfence-security'); ?></button>
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . ($_GET['page'] ?? '') . '&view=' . ($_GET['view'] ?? ''))); ?>" class="button">
                    <?php _e('Clear', 'vmpfence-security'); ?>
                </a>
                
                <?php
                // Check if API integration is available
                $has_api = class_exists('VMPFence_API_Client') && 
                           class_exists('VMPFence_Config') && 
                           !empty(VMPFence_Config::get('central_api_key', ''));
                $license_tier = class_exists('VMPFence_License') ? VMPFence_License::get_license_type() : 'free';
                $is_premium = ($license_tier === 'premium');
                ?>
                
                <?php if ($has_api): ?>
                <button type="button" id="vmpfence-sync-waf-rules" class="button button-primary" 
                        data-nonce="<?php echo wp_create_nonce('vmpfence_sync_waf_rules'); ?>"
                        style="margin-left: 10px;">
                    🔄 <?php _e('Sync Rules from API', 'vmpfence-security'); ?>
                </button>
                <span id="vmpfence-sync-status" style="margin-left: 10px;"></span>
                <?php else: ?>
                <span style="margin-left: 10px; color: #dc3545;">
                    ⚠️ <?php _e('API key required to sync rules', 'vmpfence-security'); ?>
                </span>
                <?php endif; ?>
            </form>
        </div>

        <!-- Rules Table -->
        <table class="wp-list-table widefat fixed striped" style="table-layout: fixed;">
            <thead>
                <tr>
                    <th style="width: 140px;"><?php _e('Rule ID', 'vmpfence-security'); ?></th>
                    <th style="width: 150px;"><?php _e('Category', 'vmpfence-security'); ?></th>
                    <th><?php _e('Description', 'vmpfence-security'); ?></th>
                    <th style="width: 70px;"><?php _e('Severity', 'vmpfence-security'); ?></th>
                    <th style="width: 60px;"><?php _e('Score', 'vmpfence-security'); ?></th>
                    <th style="width: 70px;"><?php _e('Action', 'vmpfence-security'); ?></th>
                    <th style="width: 80px;"><?php _e('Whitelist', 'vmpfence-security'); ?></th>
                    <th style="width: 70px;"><?php _e('Version', 'vmpfence-security'); ?></th>
                    <th style="width: 90px;"><?php _e('Status', 'vmpfence-security'); ?></th>
                    <th style="width: 90px;"><?php _e('Actions', 'vmpfence-security'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rules as $rule): ?>
                <tr>
                    <td style="word-wrap: break-word;"><code><?php echo esc_html($rule['rule_id']); ?></code></td>
                    <td style="word-wrap: break-word;">
                        <span class="badge badge-<?php echo esc_attr(strtolower($rule['category'])); ?>">
                            <?php echo esc_html($rule['category']); ?>
                        </span>
                    </td>
                    <td style="word-wrap: break-word;"><?php echo esc_html($rule['description']); ?></td>
                    <td><?php echo esc_html($rule['severity']); ?></td>
                    <td><strong><?php echo esc_html($rule['score']); ?></strong></td>
                    <td>
                        <span class="action-<?php echo esc_attr($rule['action']); ?>">
                            <?php echo esc_html(ucfirst($rule['action'])); ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($rule['whitelist'] == 1): ?>
                        <span style="color: #46b450;">✓ Yes</span>
                        <?php else: ?>
                        <span style="color: #999;">✗ No</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo esc_html($rule['version']); ?></td>
                    <td>
                        <span class="rule-status" data-rule-id="<?php echo esc_attr($rule['id']); ?>">
                            <?php if ($rule['enabled'] == 1): ?>
                            <span style="color: #46b450;">● Enabled</span>
                            <?php else: ?>
                            <span style="color: #dc3232;">● Disabled</span>
                            <?php endif; ?>
                        </span>
                    </td>
                    <td>
                        <button type="button" class="button button-small toggle-rule" 
                                data-rule-id="<?php echo esc_attr($rule['id']); ?>"
                                data-nonce="<?php echo wp_create_nonce('toggle_waf_rule_' . $rule['id']); ?>">
                            <?php echo $rule['enabled'] == 1 ? __('Disable', 'vmpfence-security') : __('Enable', 'vmpfence-security'); ?>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <style>
            .badge {
                display: inline-block;
                padding: 4px 8px;
                border-radius: 3px;
                font-size: 10px;
                font-weight: 600;
                text-transform: uppercase;
                white-space: normal;
                word-wrap: break-word;
                max-width: 100%;
                line-height: 1.3;
            }
            .badge-xss { background: #ffebee; color: #c62828; }
            .badge-sqli, .badge-sql_injection { background: #fff3e0; color: #e65100; }
            .badge-rfi, .badge-remote_file_inclusion { background: #fce4ec; color: #880e4f; }
            .badge-lfi, .badge-local_file_inclusion { background: #f3e5f5; color: #6a1b9a; }
            .badge-rce { background: #ffcdd2; color: #b71c1c; }
            .badge-command_injection { background: #ffe0b2; color: #e65100; }
            .badge-file_upload { background: #e1bee7; color: #7b1fa2; }
            .badge-ldap_injection { background: #c5e1a5; color: #558b2f; }
            .badge-null_byte { background: #cfd8dc; color: #37474f; }
            .badge-protocol { background: #b3e5fc; color: #0277bd; }
            .badge-scanner { background: #d7ccc8; color: #4e342e; }
            .badge-wordpress { background: #b2dfdb; color: #00695c; }
            .badge-malware { background: #ef9a9a; color: #c62828; }
            .badge-spam { background: #f8bbd0; color: #ad1457; }
            .badge-server_misconfig { background: #ffccbc; color: #d84315; }
            .action-block { color: #dc3232; font-weight: 600; }
            .action-log { color: #00a0d2; font-weight: 600; }
        </style>

        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Toggle rule enable/disable
            $('.toggle-rule').on('click', function() {
                var button = $(this);
                var ruleId = button.data('rule-id');
                var nonce = button.data('nonce');

                button.prop('disabled', true).text('<?php _e('Processing...', 'vmpfence-security'); ?>');

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_toggle_waf_rule',
                        rule_id: ruleId,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reload page to reflect changes
                            location.reload();
                        } else {
                            VMPFenceNotifications.showError('<?php _e('Error toggling rule', 'vmpfence-security'); ?>: ' + response.data);
                            button.prop('disabled', false);
                        }
                    },
                    error: function() {
                        VMPFenceNotifications.showError('<?php _e('AJAX error occurred', 'vmpfence-security'); ?>');
                        button.prop('disabled', false);
                    }
                });
            });
            
            // Sync WAF rules from API
            $('#vmpfence-sync-waf-rules').on('click', function() {
                var $button = $(this);
                var $status = $('#vmpfence-sync-status');
                var nonce = $button.data('nonce');
                
                VMPFenceNotifications.showConfirmModal({
                    title: 'Sync WAF Rules',
                    message: '<?php _e('Sync WAF rules from API? This will fetch the latest firewall rules.', 'vmpfence-security'); ?>',
                    confirmText: 'Yes, Sync',
                    cancelText: 'Cancel'
                }).then(function(confirmed) {
                    if (!confirmed) return;
                    
                    $button.prop('disabled', true).text('🔄 <?php _e('Syncing...', 'vmpfence-security'); ?>');
                    $status.html('<em style="color: #666;"><?php _e('Please wait...', 'vmpfence-security'); ?></em>');
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'vmpfence_sync_waf_rules',
                            nonce: nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                $status.html('<strong style="color: #00a32a;">✅ ' + response.data.message + '</strong>');
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                $status.html('<strong style="color: #dc3232;">❌ ' + response.data + '</strong>');
                                $button.prop('disabled', false).text('🔄 <?php _e('Sync Rules from API', 'vmpfence-security'); ?>');
                            }
                        },
                        error: function() {
                            $status.html('<strong style="color: #dc3232;">❌ <?php _e('AJAX error occurred', 'vmpfence-security'); ?></strong>');
                            $button.prop('disabled', false).text('🔄 <?php _e('Sync Rules from API', 'vmpfence-security'); ?>');
                        }
                    });
                });
        });
        </script>

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