<?php
/**
 * Security Dashboard - System Admin only
 * Monitor security threats, blocked IPs, failed logins
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/security.php';
require_once __DIR__ . '/../../includes/settings.php';
requireAuth();
requireSystemAdmin();

$pageTitle = 'Security Dashboard';
$currentPage = 'system';

// Get security statistics
$stats = [];

// Failed login attempts (last 24 hours)
try {
    $stmt = $pdo->query("
        SELECT COUNT(*) as count, ip_address, COUNT(DISTINCT username) as usernames
        FROM activity_logs
        WHERE action = 'login_failed'
          AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        GROUP BY ip_address
        ORDER BY count DESC
        LIMIT 10
    ");
    $stats['failed_logins'] = $stmt->fetchAll();
    
    $stmt = $pdo->query("
        SELECT COUNT(*) as total
        FROM activity_logs
        WHERE action = 'login_failed'
          AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    $stats['total_failed_24h'] = (int)$stmt->fetchColumn();
    
    // Currently blocked IPs
    $maxAttempts = (int)getSetting('max_login_attempts', '5');
    $lockoutDuration = (int)getSetting('lockout_duration_minutes', '15');
    
    $stmt = $pdo->prepare("
        SELECT ip_address, COUNT(*) as attempts, MAX(created_at) as last_attempt
        FROM activity_logs
        WHERE action = 'login_failed'
          AND created_at >= DATE_SUB(NOW(), INTERVAL ? MINUTE)
        GROUP BY ip_address
        HAVING attempts >= ?
        ORDER BY last_attempt DESC
    ");
    $stmt->execute([$lockoutDuration, $maxAttempts]);
    $stats['blocked_ips'] = $stmt->fetchAll();
    
    // Recent successful logins
    $stmt = $pdo->query("
        SELECT al.*, u.full_name
        FROM activity_logs al
        LEFT JOIN users u ON al.user_id = u.id
        WHERE al.action = 'login_success'
        ORDER BY al.created_at DESC
        LIMIT 20
    ");
    $stats['recent_logins'] = $stmt->fetchAll();
    
} catch (PDOException $e) {
    $stats = [
        'failed_logins' => [],
        'total_failed_24h' => 0,
        'blocked_ips' => [],
        'recent_logins' => [],
    ];
}

// Get IP lists
$whitelist = getSetting('ip_whitelist', '');
$blacklist = getSetting('ip_blacklist', '');
$whitelistIps = !empty($whitelist) ? array_map('trim', explode(',', $whitelist)) : [];
$blacklistIps = !empty($blacklist) ? array_map('trim', explode(',', $blacklist)) : [];

// Current user's IP
$currentIp = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';

require_once __DIR__ . '/../../includes/system-header.php';
?>

<div class="header">
    <h1>Security Dashboard</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system" class="link-muted">← Dashboard</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<!-- Security Overview -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
    <div class="card" style="background: <?= $stats['total_failed_24h'] > 10 ? '#fef2f2' : '#f8fafc' ?>; border: <?= $stats['total_failed_24h'] > 10 ? '1px solid #fecaca' : 'none' ?>;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Failed Logins (24h)</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: <?= $stats['total_failed_24h'] > 10 ? '#991b1b' : '#1e293b' ?>;"><?= number_format($stats['total_failed_24h']) ?></div>
        <?php if ($stats['total_failed_24h'] > 10): ?>
        <div style="font-size: 0.75rem; color: #991b1b; margin-top: 0.25rem;">⚠️ High activity</div>
        <?php endif; ?>
    </div>
    <div class="card" style="background: <?= count($stats['blocked_ips']) > 0 ? '#fef2f2' : '#f8fafc' ?>; border: <?= count($stats['blocked_ips']) > 0 ? '1px solid #fecaca' : 'none' ?>;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Blocked IPs</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: <?= count($stats['blocked_ips']) > 0 ? '#991b1b' : '#1e293b' ?>;"><?= count($stats['blocked_ips']) ?></div>
        <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.25rem;">Currently locked out</div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Whitelisted IPs</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= count($whitelistIps) ?></div>
    </div>
    <div class="card" style="background: #f8fafc;">
        <div style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">Blacklisted IPs</div>
        <div style="font-size: 1.75rem; font-weight: 600; color: #1e293b;"><?= count($blacklistIps) ?></div>
    </div>
</div>

<!-- Failed Login Attempts by IP -->
<div class="card">
    <?php if (!empty($stats['failed_logins'])): ?>
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Failed Login Attempts (Last 24 Hours)</h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>IP Address</th>
                    <th style="text-align: right;">Attempts</th>
                    <th style="text-align: right;">Usernames Tried</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($stats['failed_logins'] as $attempt): ?>
                <?php 
                $isBlocked = isIpBlocked($attempt['ip_address']);
                $isWhitelisted = isIpWhitelisted($attempt['ip_address']);
                $isBlacklisted = isIpBlacklisted($attempt['ip_address']);
                ?>
                <tr style="<?= $isBlocked || $isBlacklisted ? 'background: #fef2f2;' : '' ?>">
                    <td style="font-family: monospace; font-weight: 500;">
                        <?= htmlspecialchars($attempt['ip_address']) ?>
                        <?php if ($attempt['ip_address'] === $currentIp): ?>
                        <span style="color: #64748b; font-size: 0.75rem;">(You)</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align: right; font-weight: 500;"><?= number_format($attempt['count']) ?></td>
                    <td style="text-align: right;"><?= number_format($attempt['usernames']) ?></td>
                    <td>
                        <?php if ($isBlacklisted): ?>
                        <span style="color: #991b1b; font-weight: 500;">🔴 Blacklisted</span>
                        <?php elseif ($isWhitelisted): ?>
                        <span style="color: #10b981; font-weight: 500;">✓ Whitelisted</span>
                        <?php elseif ($isBlocked): ?>
                        <span style="color: #f59e0b; font-weight: 500;">⚠️ Blocked</span>
                        <?php else: ?>
                        <span style="color: #64748b;">—</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <p class="text-muted">No failed login attempts in the last 24 hours.</p>
    <?php endif; ?>
</div>

<!-- Currently Blocked IPs -->
<?php if (!empty($stats['blocked_ips'])): ?>
<div class="card" style="border: 1px solid #fecaca; background: #fef2f2;">
    <h2 style="margin-top: 0; margin-bottom: 1rem; color: #991b1b;">⚠️ Currently Blocked IP Addresses</h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>IP Address</th>
                    <th style="text-align: right;">Failed Attempts</th>
                    <th>Last Attempt</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($stats['blocked_ips'] as $blocked): ?>
                <tr>
                    <td style="font-family: monospace; font-weight: 500;"><?= htmlspecialchars($blocked['ip_address']) ?></td>
                    <td style="text-align: right; font-weight: 500;"><?= number_format($blocked['attempts']) ?></td>
                    <td style="color: #64748b;"><?= date('Y-m-d H:i:s', strtotime($blocked['last_attempt'])) ?></td>
                    <td>
                        <?php if (!isIpWhitelisted($blocked['ip_address'])): ?>
                        <a href="<?= BASE_PATH ?>/system/settings?tab=security&add_whitelist=<?= urlencode($blocked['ip_address']) ?>" class="btn btn-sm btn-outline" style="font-size: 0.75rem;">Add to Whitelist</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Recent Successful Logins -->
<?php if (!empty($stats['recent_logins'])): ?>
<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Recent Successful Logins</h2>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Timestamp</th>
                    <th>User</th>
                    <th>IP Address</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($stats['recent_logins'] as $login): ?>
                <tr>
                    <td style="color: #64748b; font-size: 0.875rem;"><?= date('Y-m-d H:i:s', strtotime($login['created_at'])) ?></td>
                    <td>
                        <strong><?= htmlspecialchars($login['username']) ?></strong>
                        <?php if ($login['full_name']): ?>
                        <br><span style="font-size: 0.75rem; color: #64748b;"><?= htmlspecialchars($login['full_name']) ?></span>
                        <?php endif; ?>
                    </td>
                    <td style="font-family: monospace; font-size: 0.875rem; color: #64748b;">
                        <?= htmlspecialchars($login['ip_address'] ?? '—') ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- IP Lists -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
    <div class="card">
        <h2 style="margin-top: 0; margin-bottom: 1rem;">IP Whitelist</h2>
        <?php if (empty($whitelistIps)): ?>
        <p class="text-muted">No IPs whitelisted.</p>
        <?php else: ?>
        <div style="background: #f0fdf4; padding: 1rem; border-radius: 6px; font-family: monospace; font-size: 0.875rem;">
            <?php foreach ($whitelistIps as $ip): ?>
            <div style="padding: 0.25rem 0;"><?= htmlspecialchars($ip) ?></div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <p style="margin-top: 1rem;">
            <a href="<?= BASE_PATH ?>/system/settings?tab=security" class="btn btn-sm btn-outline">Manage Whitelist</a>
        </p>
    </div>
    
    <div class="card">
        <h2 style="margin-top: 0; margin-bottom: 1rem;">IP Blacklist</h2>
        <?php if (empty($blacklistIps)): ?>
        <p class="text-muted">No IPs blacklisted.</p>
        <?php else: ?>
        <div style="background: #fef2f2; padding: 1rem; border-radius: 6px; font-family: monospace; font-size: 0.875rem;">
            <?php foreach ($blacklistIps as $ip): ?>
            <div style="padding: 0.25rem 0;"><?= htmlspecialchars($ip) ?></div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <p style="margin-top: 1rem;">
            <a href="<?= BASE_PATH ?>/system/settings?tab=security" class="btn btn-sm btn-outline">Manage Blacklist</a>
        </p>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/system-footer.php'; ?>
