<?php
// Root-only page: enforced by the page-permission whitelist in
// libs/permission_manager.php AND this defensive in-file gate (pages must
// never trust that they were reached through index.php alone). Delegated
// sub-users of root also carry AUTH_USER === 'root', so a real system
// session is required too.
if (!defined('AUTH_USER') || AUTH_USER !== 'root'
    || ($_SESSION['user_type'] ?? '') !== 'system') {
    echo '<div class="alert alert-danger">Root access required.</div>';
    return;
}

require_once('/docker/whp/web/libs/security_manager.php');
require_once('/docker/whp/web/libs/log_monitor_manager.php');
require_once('/docker/whp/web/libs/security_management_actions.php');
$SecManager = new security_manager();
$LogMonitor = new log_monitor_manager();

$message = '';
$message_type = '';

// Handle form submissions (non-JS fallback; the async path posts the same
// actions to api/security-management-ajax.php via the shared handler).
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!validate_csrf_token()) {
        $message = 'Invalid or expired CSRF token. Please refresh the page and try again.';
        $message_type = 'danger';
    } else {
        $result = whp_security_management_handle_action($SecManager, $LogMonitor);
        $message = $result['message'];
        $message_type = $result['type'];
    }
}

// Get data
$blocked_ips = $SecManager->get_blocked_ips();
$exemption_ips = $SecManager->get_exemption_ips();
$security_stats = $SecManager->get_security_stats();
$recent_logins = $SecManager->get_all_recent_logins(10);

// Get log monitoring data
$log_config = $LogMonitor->get_all_config();
$service_stats = $LogMonitor->get_service_stats();

// Combine service blocked IPs and security manager blocked IPs
$service_blocked_ips = $LogMonitor->get_unique_blocked_ips();
$security_blocked_ips = $SecManager->get_blocked_ips();

// Add security manager blocks to the service blocks array with proper formatting
foreach ($security_blocked_ips as $security_block) {
    // Check if this IP is already in service blocks
    $found_in_service = false;
    foreach ($service_blocked_ips as &$service_block) {
        if ($service_block['ip_address'] === $security_block['ip_address']) {
            $found_in_service = true;
            // If security manager block is newer or permanent, update the display
            if ($security_block['block_time'] > $service_block['block_time'] || $security_block['unblock_time'] == -1) {
                $service_block['reason'] = $security_block['reason'];
                $service_block['blocking_service'] = 'security_manager';
                $service_block['block_time'] = $security_block['block_time'];
                $service_block['unblock_time'] = $security_block['unblock_time'];
                $service_block['failed_attempts'] = $security_block['failed_attempts'];
            }
            break;
        }
    }
    
    // If not found in service blocks, add it
    if (!$found_in_service) {
        // Determine the service based on the reason
        $service = 'whp'; // Default to WHP for security manager blocks
        if (stripos($security_block['reason'], 'manual') !== false) {
            $service = 'manual';
        } elseif (stripos($security_block['reason'], 'failed login') !== false) {
            $service = 'whp';
        }
        
        $service_blocked_ips[] = [
            'ip_address' => $security_block['ip_address'],
            'service_type' => 'security_manager',
            'service' => $service, // Add the service field
            'blocking_service' => 'security_manager',
            'reason' => $security_block['reason'],
            'block_time' => $security_block['block_time'],
            'unblock_time' => $security_block['unblock_time'],
            'failed_attempts' => $security_block['failed_attempts']
        ];
    }
}

// Get access statistics
require_once('/docker/whp/web/libs/permission_manager.php');
$PermManager = new permission_manager();
$access_stats = $PermManager->get_system_access_stats(30);
?>
<?php if (!empty($message)): ?>
<div class="row">
    <div class="col-sm-12">
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible" role="alert">
            <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <?php echo htmlspecialchars($message); ?>
        </div>
    </div>
</div>
<?php endif; ?>
<!-- Security Statistics -->
<div class="row g-4 mb-4">
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Failed Attempts (24h)</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-warning"><?php echo $security_stats['failed_attempts_24h']; ?></h2>
                <p class="mb-0">Failed login attempts in last 24 hours</p>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Exempt IPs</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-success"><?php echo $security_stats['exemption_ips']; ?></h2>
                <p class="mb-0">IP addresses in exemption list</p>
            </div>
        </div>
    </div>
</div>

<!-- Service Monitoring Statistics -->
<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Total Blocked IPs</h5>
            </div>
            <div class="card-body text-center">
                <?php 
                // Count unique blocked IPs (each IP only counted once)
                $total_blocked = count($service_blocked_ips);
                ?>
                <h2 class="text-danger"><?php echo $total_blocked; ?></h2>
                <p class="mb-0">Currently blocked across all services</p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">SSH Failed Attempts (24h)</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-warning"><?php echo $service_stats['ssh']['failed_attempts_24h']; ?></h2>
                <p class="mb-0">SSH login failures</p>
                <?php if (!$service_stats['ssh']['monitoring_enabled']): ?>
                <small class="text-muted">(Monitoring disabled)</small>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">FTP Failed Attempts (24h)</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-warning"><?php echo $service_stats['ftp']['failed_attempts_24h']; ?></h2>
                <p class="mb-0">FTP login failures</p>
                <?php if (!$service_stats['ftp']['monitoring_enabled']): ?>
                <small class="text-muted">(Monitoring disabled)</small>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Access Statistics -->
<div class="row g-4 mb-4">
    <div class="col-md-3">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Total Access Attempts (30d)</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-info"><?php echo $access_stats['total_attempts']; ?></h2>
                <p class="mb-0">Total page/API access attempts</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Denied Access (30d)</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-danger"><?php echo $access_stats['denied_attempts']; ?></h2>
                <p class="mb-0">Permission denied attempts</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Success Rate (30d)</h5>
            </div>
            <div class="card-body text-center">
                <h2 class="text-success"><?php echo $access_stats['success_rate']; ?>%</h2>
                <p class="mb-0">Successful access rate</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">Top Denied Page</h5>
            </div>
            <div class="card-body text-center">
                <?php if (!empty($access_stats['top_denied_pages'])): ?>
                <h2 class="text-warning"><?php echo htmlspecialchars($access_stats['top_denied_pages'][0]['page']); ?></h2>
                <p class="mb-0"><?php echo $access_stats['top_denied_pages'][0]['count']; ?> denials</p>
                <?php else: ?>
                <h2 class="text-muted">-</h2>
                <p class="mb-0">No denials</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Log Monitoring Configuration -->
<div class="row g-4 mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">SSH/FTP Log Monitoring Configuration</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="" data-whp-async data-whp-action="/api/security-management-ajax.php">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="action" value="update_log_monitoring">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="mb-3">SSH Monitoring</h6>
                            
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="config_ssh_monitoring_enabled" name="config_ssh_monitoring_enabled" value="1"
                                           <?php echo ($LogMonitor->get_config('ssh_monitoring_enabled') == '1') ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="config_ssh_monitoring_enabled">Enable SSH monitoring</label>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label" for="config_max_ssh_attempts">Max SSH attempts before block</label>
                                <input type="number" class="form-control" id="config_max_ssh_attempts" name="config_max_ssh_attempts"
                                       value="<?php echo htmlspecialchars($LogMonitor->get_config('max_ssh_attempts', '5')); ?>" min="1" max="50">
                            </div>

                            <div class="mb-3">
                                <label class="form-label" for="config_ssh_block_duration">SSH block duration (seconds)</label>
                                <select class="form-select" id="config_ssh_block_duration" name="config_ssh_block_duration">
                                    <?php 
                                    $ssh_duration = $LogMonitor->get_config('ssh_block_duration', '3600');
                                    $durations = [
                                        '300' => '5 minutes',
                                        '600' => '10 minutes',
                                        '1800' => '30 minutes',
                                        '3600' => '1 hour',
                                        '7200' => '2 hours',
                                        '86400' => '24 hours'
                                    ];
                                    foreach ($durations as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($ssh_duration == $value) ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label" for="config_ssh_log_file">SSH log file path</label>
                                <input type="text" class="form-control" id="config_ssh_log_file" name="config_ssh_log_file"
                                       value="<?php echo htmlspecialchars($LogMonitor->get_config('ssh_log_file', '/var/log/auth.log')); ?>">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="mb-3">FTP Monitoring</h6>
                            
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="config_ftp_monitoring_enabled" name="config_ftp_monitoring_enabled" value="1"
                                           <?php echo ($LogMonitor->get_config('ftp_monitoring_enabled') == '1') ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="config_ftp_monitoring_enabled">Enable FTP monitoring</label>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label" for="config_max_ftp_attempts">Max FTP attempts before block</label>
                                <input type="number" class="form-control" id="config_max_ftp_attempts" name="config_max_ftp_attempts"
                                       value="<?php echo htmlspecialchars($LogMonitor->get_config('max_ftp_attempts', '5')); ?>" min="1" max="50">
                            </div>

                            <div class="mb-3">
                                <label class="form-label" for="config_ftp_block_duration">FTP block duration (seconds)</label>
                                <select class="form-select" id="config_ftp_block_duration" name="config_ftp_block_duration">
                                    <?php 
                                    $ftp_duration = $LogMonitor->get_config('ftp_block_duration', '3600');
                                    foreach ($durations as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($ftp_duration == $value) ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label" for="config_ftp_log_file">FTP log file path</label>
                                <input type="text" class="form-control" id="config_ftp_log_file" name="config_ftp_log_file"
                                       value="<?php echo htmlspecialchars($LogMonitor->get_config('ftp_log_file', '/var/log/proftpd/proftpd.log')); ?>">
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="mb-3">General Settings</h6>
                            
                            <div class="mb-3">
                                <label class="form-label" for="config_log_check_interval">Log check interval (seconds)</label>
                                <select class="form-select" id="config_log_check_interval" name="config_log_check_interval">
                                    <?php 
                                    $check_interval = $LogMonitor->get_config('log_check_interval', '300');
                                    $intervals = [
                                        '60' => '1 minute',
                                        '300' => '5 minutes',
                                        '600' => '10 minutes',
                                        '1800' => '30 minutes'
                                    ];
                                    foreach ($intervals as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($check_interval == $value) ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="mb-3">Advanced Options</h6>
                            
                            <div class="mb-3">
                                <label class="form-label" for="config_blocking_method">IP Blocking Method</label>
                                <select class="form-select" id="config_blocking_method" name="config_blocking_method">
                                    <?php 
                                    $blocking_method = $LogMonitor->get_config('blocking_method', 'service');
                                    $methods = [
                                        'service' => 'Service-Level Blocking (Recommended)',
                                        'iptables' => 'Firewall-Level Blocking (iptables)'
                                    ];
                                    foreach ($methods as $value => $label): ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($blocking_method == $value) ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="form-text text-muted">Service-level blocking uses configuration files and graceful service reloads (safer for Docker)</small>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="config_docker_network_preserve" name="config_docker_network_preserve" value="1"
                                           <?php echo ($LogMonitor->get_config('docker_network_preserve') == '1') ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="config_docker_network_preserve">Preserve Docker networking</label>
                                    <small class="form-text text-muted">When using iptables: block only specific services instead of all traffic from IP</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Update Configuration</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <!-- Block IP Panel -->
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-ban me-2"></i> Block IP Address or CIDR Range
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" action="" data-whp-async data-whp-action="/api/security-management-ajax.php">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="action" value="block_ip">
                    <div class="mb-3">
                        <label for="block_ip" class="form-label">IP Address or CIDR</label>
                        <input type="text" class="form-control" id="block_ip" name="ip_address"
                               placeholder="192.168.1.100 or 192.168.1.0/24"
                               pattern="^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/(?:3[0-2]|[12]?[0-9]))?$"
                               title="Enter a valid IP address (e.g., 192.168.1.100) or CIDR range (e.g., 192.168.1.0/24)"
                               aria-describedby="block_ip_help"
                               required>
                        <small id="block_ip_help" class="form-text text-muted">
                            Single IP or CIDR notation. Common masks: /32 (single IP), /24 (256 IPs), /16 (65,536 IPs)
                        </small>
                    </div>
                    <div class="mb-3">
                        <label for="block_reason" class="form-label">Reason (optional)</label>
                        <input type="text" class="form-control" id="block_reason" name="reason" placeholder="Manual block">
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="permanent_block" name="permanent" value="1">
                            <label class="form-check-label" for="permanent_block">
                                Block permanently
                            </label>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-danger">Block IP/CIDR</button>
                </form>
            </div>
        </div>
    </div>
    <!-- Unblock IP Panel -->
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-unlock me-2"></i> Unblock IP Address or CIDR Range
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" action="" data-whp-async data-whp-action="/api/security-management-ajax.php">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="action" value="unblock_ip">
                    <div class="mb-3">
                        <label for="unblock_ip" class="form-label">IP Address or CIDR</label>
                        <input type="text" class="form-control" id="unblock_ip" name="ip_address"
                               placeholder="192.168.1.100 or 192.168.1.0/24"
                               pattern="^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/(?:3[0-2]|[12]?[0-9]))?$"
                               title="Enter a valid IP address (e.g., 192.168.1.100) or CIDR range (e.g., 192.168.1.0/24)"
                               aria-describedby="unblock_ip_help"
                               required>
                        <small id="unblock_ip_help" class="form-text text-muted">
                            Single IP or CIDR notation. Common masks: /32 (single IP), /24 (256 IPs), /16 (65,536 IPs)
                        </small>
                    </div>
                    <button type="submit" class="btn btn-warning">Unblock IP/CIDR</button>
                </form>
            </div>
        </div>
    </div>
    <!-- Add Exemption Panel -->
    <div class="col-md-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-check-circle me-2"></i> Add Exemption
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" action="" data-whp-async data-whp-action="/api/security-management-ajax.php">
                    <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                    <input type="hidden" name="action" value="add_exemption">
                    <div class="mb-3">
                        <label for="exemption_ip" class="form-label">IP Address or CIDR</label>
                        <input type="text" class="form-control" id="exemption_ip" name="ip_address"
                               placeholder="192.168.1.100 or 192.168.1.0/24"
                               pattern="^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/(?:3[0-2]|[12]?[0-9]))?$"
                               title="Enter a valid IP address (e.g., 192.168.1.100) or CIDR range (e.g., 192.168.1.0/24)"
                               aria-describedby="exemption_ip_help"
                               required>
                        <small id="exemption_ip_help" class="form-text text-muted">
                            Exempt from all blocking (IP or CIDR). Common: /32 (single), /24 (local network), /8 (private range)
                        </small>
                    </div>
                    <div class="mb-3">
                        <label for="exemption_description" class="form-label">Description (optional)</label>
                        <input type="text" class="form-control" id="exemption_description" name="description" placeholder="Office, Home, etc.">
                    </div>
                    <button type="submit" class="btn btn-success">Add Exemption</button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Exemption List Table -->
<div class="row g-4 mb-5">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Exempt IPs and CIDR Ranges</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr><th>IP Address / CIDR</th><th>Description</th><th width="120">Action</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($exemption_ips)): ?>
                            <tr>
                                <td colspan="3" class="text-center text-muted">No exempt IPs configured</td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($exemption_ips as $ip): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($ip['ip_address']); ?></td>
                                <td><?php echo htmlspecialchars($ip['description']); ?></td>
                                <td>
                                    <form method="POST" action="" style="display:inline;" data-whp-async data-whp-action="/api/security-management-ajax.php" data-whp-remove-row data-whp-confirm="Remove <?php echo htmlspecialchars($ip['ip_address']); ?> from the exemption list?">
                                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                        <input type="hidden" name="action" value="remove_exemption">
                                        <input type="hidden" name="ip_address" value="<?php echo htmlspecialchars($ip['ip_address']); ?>">
                                        <button type="submit" class="btn btn-danger btn-sm">Remove</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Service Blocked IPs -->
<?php 
// Pagination setup  
$page = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$per_page = 25;

// Sort IPs by IP address first
usort($service_blocked_ips, function($a, $b) {
    return strcmp($a['ip_address'], $b['ip_address']);
});

// Filter IPs based on search
$filtered_ips = $service_blocked_ips;
if (!empty($search)) {
    $filtered_ips = array_filter($service_blocked_ips, function($ip) use ($search) {
        return stripos($ip['ip_address'], $search) !== false;
    });
}

$total_ips = count($filtered_ips);
$total_pages = ceil($total_ips / $per_page);
$page = min($page, $total_pages ?: 1);
$offset = ($page - 1) * $per_page;

// Get current page items
$current_page_ips = array_slice($filtered_ips, $offset, $per_page);

if (!empty($service_blocked_ips)): ?>
<div class="row g-4 mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Blocked IPs</h5>
                <div class="d-flex align-items-center gap-2">
                    <!-- Sync Button -->
                    <form method="POST" action="" class="d-inline" data-whp-async data-whp-action="/api/security-management-ajax.php">
                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                        <input type="hidden" name="action" value="sync_blocked_ips">
                        <button type="submit" class="btn btn-sm btn-info" title="Sync blocked IPs across all services">
                            <i class="fa fa-sync"></i> Sync
                        </button>
                    </form>
                    <!-- Search Form -->
                    <form method="GET" action="" class="d-flex">
                        <input type="hidden" name="page" value="security-management">
                        <label for="blocked_ip_search" class="visually-hidden">Search blocked IPs</label>
                        <input type="text" class="form-control form-control-sm me-2" id="blocked_ip_search" name="search"
                               placeholder="Search IP..." value="<?php echo htmlspecialchars($search); ?>" style="width: 200px;">
                        <button type="submit" class="btn btn-sm btn-primary">Search</button>
                        <?php if (!empty($search)): ?>
                        <a href="?page=security-management" class="btn btn-sm btn-secondary ms-2">Clear</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover whp-table-fixed">
                        <thead class="table-dark">
                            <tr>
                                <th style="width:7rem">Service</th>
                                <th style="width:13rem">IP Address</th>
                                <th style="width:8rem">Blocked Time</th>
                                <th style="width:9rem">Unblock Time</th>
                                <th style="width:7rem">Failed Attempts</th>
                                <th>Reason</th>
                                <th style="width:7rem">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($current_page_ips)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <?php echo !empty($search) ? 'No IPs found matching your search' : 'No blocked IPs'; ?>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($current_page_ips as $blocked): ?>
                            <tr>
                                <td>
                                    <?php 
                                    // Get the service that blocked the IP
                                    $blocking_service = '';
                                    $service_display = 'UNKNOWN';
                                    $badge_class = 'secondary';
                                    
                                    // Get the reason first as it's most reliable for determining source
                                    $reason = $blocked['reason'] ?? '';
                                    
                                    // Check the actual service field if available
                                    $blocking_service = '';
                                    if (!empty($blocked['service'])) {
                                        $blocking_service = $blocked['service'];
                                    } elseif (!empty($blocked['blocking_service'])) {
                                        $blocking_service = $blocked['blocking_service'];
                                    } elseif (!empty($blocked['service_type'])) {
                                        $blocking_service = $blocked['service_type'];
                                    }
                                    
                                    // Determine display based on reason first, then service
                                    // Priority: Manual blocks, then specific service mentions in reason, then service field
                                    if (stripos($reason, 'manual') !== false) {
                                        $badge_class = 'warning';
                                        $service_display = 'MANUAL';
                                    } elseif (stripos($reason, 'failed login') !== false || stripos($reason, 'too many failed login attempts') !== false) {
                                        $badge_class = 'success';
                                        $service_display = 'WHP';
                                    } elseif (stripos($reason, 'failed ssh') !== false || (stripos($reason, 'ssh') !== false && stripos($reason, 'failed') !== false)) {
                                        $badge_class = 'primary';
                                        $service_display = 'SSH';
                                    } elseif (stripos($reason, 'failed ftp') !== false || (stripos($reason, 'ftp') !== false && stripos($reason, 'failed') !== false)) {
                                        $badge_class = 'info';
                                        $service_display = 'FTP';
                                    } elseif (stripos($reason, 'haproxy') !== false) {
                                        $badge_class = 'danger';
                                        $service_display = 'HAProxy';
                                    } elseif ($blocking_service == 'security_manager') {
                                        // For security_manager with no specific reason, default to WHP
                                        $badge_class = 'success';
                                        $service_display = 'WHP';
                                    } elseif ($blocking_service == 'ssh') {
                                        $badge_class = 'primary';
                                        $service_display = 'SSH';
                                    } elseif ($blocking_service == 'ftp') {
                                        $badge_class = 'info';
                                        $service_display = 'FTP';
                                    } elseif ($blocking_service == 'whp') {
                                        $badge_class = 'success';
                                        $service_display = 'WHP';
                                    } elseif ($blocking_service == 'haproxy') {
                                        $badge_class = 'danger';
                                        $service_display = 'HAProxy';
                                    } elseif (!empty($blocking_service)) {
                                        $badge_class = 'secondary';
                                        $service_display = strtoupper($blocking_service);
                                    } else {
                                        // Default fallback
                                        $badge_class = 'secondary';
                                        $service_display = 'UNKNOWN';
                                    }
                                    ?>
                                    <span class="badge bg-<?php echo $badge_class; ?>"><?php echo $service_display; ?></span>
                                </td>
                                <td class="whp-cell-truncate" title="<?php echo htmlspecialchars($blocked['ip_address']); ?>">
                                    <code><?php echo htmlspecialchars($blocked['ip_address']); ?></code>
                                    <?php if (strpos($blocked['ip_address'], '/') !== false): ?>
                                        <span class="badge bg-info ms-1" title="CIDR Range">RANGE</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small<?php echo whp_local_time_title_attrs($blocked['block_time']); ?>>
                                        <?php 
                                        $time_ago = time() - $blocked['block_time'];
                                        if ($time_ago < 60) {
                                            echo 'Just now';
                                        } elseif ($time_ago < 3600) {
                                            echo floor($time_ago / 60) . 'm ago';
                                        } elseif ($time_ago < 86400) {
                                            echo floor($time_ago / 3600) . 'h ago';
                                        } else {
                                            echo floor($time_ago / 86400) . 'd ago';
                                        }
                                        ?>
                                    </small>
                                </td>
                                <td>
                                    <?php 
                                    // Check if this is a permanent block
                                    if ($blocked['unblock_time'] == -1 || $blocked['unblock_time'] == 4102444799) {
                                        // Permanent block (-1 or year 2099)
                                        echo '<small class="text-danger"><strong>Permanent</strong></small>';
                                    } else {
                                        $time_left = $blocked['unblock_time'] - time();
                                        $unblockAttrs = whp_local_time_title_attrs($blocked['unblock_time']);
                                        if ($time_left <= 0) {
                                            echo '<small class="text-success">Expired</small>';
                                        } elseif ($time_left > 86400) {
                                            echo '<small' . $unblockAttrs . '>';
                                            echo floor($time_left / 86400) . 'd ' . floor(($time_left % 86400) / 3600) . 'h';
                                            echo '</small>';
                                        } elseif ($time_left > 3600) {
                                            echo '<small' . $unblockAttrs . '>';
                                            echo floor($time_left / 3600) . 'h ' . floor(($time_left % 3600) / 60) . 'm';
                                            echo '</small>';
                                        } elseif ($time_left > 60) {
                                            echo '<small' . $unblockAttrs . '>';
                                            echo floor($time_left / 60) . 'm';
                                            echo '</small>';
                                        } else {
                                            echo '<small' . $unblockAttrs . '>Soon</small>';
                                        }
                                    }
                                    ?>
                                </td>
                                <td><span class="badge bg-warning"><?php echo $blocked['failed_attempts']; ?></span></td>
                                <td class="whp-cell-truncate" title="<?php echo htmlspecialchars($blocked['reason']); ?>">
                                    <?php echo htmlspecialchars($blocked['reason']); ?>
                                </td>
                                <td>
                                    <form method="POST" action="" style="display:inline;" data-whp-async data-whp-action="/api/security-management-ajax.php" data-whp-remove-row data-whp-confirm="Unblock <?php echo htmlspecialchars($blocked['ip_address']); ?> from all services?">
                                        <input type="hidden" name="csrf_token" value="<?php echo get_csrf_token(); ?>">
                                        <input type="hidden" name="action" value="unblock_service_ip">
                                        <input type="hidden" name="ip_address" value="<?php echo htmlspecialchars($blocked['ip_address']); ?>">
                                        <button type="submit" class="btn btn-warning btn-sm">Unblock</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if ($total_pages > 1): ?>
                <!-- Pagination -->
                <nav aria-label="Blocked IPs pagination">
                    <ul class="pagination justify-content-center mb-0">
                        <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=security-management&p=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>">Previous</a>
                        </li>
                        <?php endif; ?>
                        
                        <?php
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);
                        
                        if ($start_page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=security-management&p=1&search=<?php echo urlencode($search); ?>">1</a>
                        </li>
                        <?php if ($start_page > 2): ?>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>
                        <?php endif; ?>
                        
                        <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=security-management&p=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                        </li>
                        <?php endfor; ?>
                        
                        <?php if ($end_page < $total_pages): ?>
                        <?php if ($end_page < $total_pages - 1): ?>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=security-management&p=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>"><?php echo $total_pages; ?></a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=security-management&p=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>">Next</a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </nav>
                <?php endif; ?>
                
                <?php if (!empty($search)): ?>
                <div class="text-center mt-2">
                    <small class="text-muted">Showing <?php echo $total_ips; ?> result(s) for "<?php echo htmlspecialchars($search); ?>"</small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Recent Successful Logins -->
<div class="row g-4 mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Recent Successful Logins</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover whp-table-fixed">
                        <thead class="table-dark">
                            <tr>
                                <th style="width:14rem">Username</th>
                                <th style="width:12rem">IP Address</th>
                                <th style="width:11rem">Login Time</th>
                                <th>User Agent</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recent_logins)): ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted">No recent logins found</td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($recent_logins as $login): ?>
                            <tr>
                                <td class="whp-cell-primary whp-cell-truncate" title="<?php echo htmlspecialchars($login['username']); ?>"><strong><?php echo htmlspecialchars($login['username']); ?></strong></td>
                                <td class="whp-cell-truncate" title="<?php echo htmlspecialchars($login['ip_address']); ?>">
                                    <code><?php echo htmlspecialchars($login['ip_address']); ?></code>
                                </td>
                                <td>
                                    <span<?php echo whp_local_time_title_attrs($login['login_time']); ?>>
                                        <?php 
                                        $time_ago = time() - $login['login_time'];
                                        if ($time_ago < 60) {
                                            echo 'Just now';
                                        } elseif ($time_ago < 3600) {
                                            echo floor($time_ago / 60) . ' minutes ago';
                                        } elseif ($time_ago < 86400) {
                                            echo floor($time_ago / 3600) . ' hours ago';
                                        } else {
                                            echo floor($time_ago / 86400) . ' days ago';
                                        }
                                        ?>
                                    </span>
                                </td>
                                <td class="whp-cell-truncate" title="<?php echo htmlspecialchars($login['user_agent'], ENT_QUOTES, 'UTF-8'); ?>">
                                    <?php echo htmlspecialchars($login['user_agent'], ENT_QUOTES, 'UTF-8'); ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/js/whp-async-forms.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>
<script>
// Real-time CIDR/IP validation for all IP input fields
document.addEventListener('DOMContentLoaded', function() {
    const ipInputs = document.querySelectorAll('#block_ip, #unblock_ip, #exemption_ip');
    const ipv4Pattern = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\/(?:3[0-2]|[12]?[0-9]))?$/;

    ipInputs.forEach(input => {
        input.addEventListener('input', function() {
            if (this.value.trim() === '') {
                this.classList.remove('is-valid', 'is-invalid');
            } else if (ipv4Pattern.test(this.value.trim())) {
                this.classList.remove('is-invalid');
                this.classList.add('is-valid');
            } else {
                this.classList.remove('is-valid');
                this.classList.add('is-invalid');
            }
        });
    });
});
</script>