{% extends "base.html" %}
{% block title %}Windows Defense - AUTARCH{% endblock %}

{% block content %}
<div class="page-header" style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap">
    <div>
        <h1>Windows Defense</h1>
        <p style="margin:0;font-size:0.85rem;color:var(--text-secondary)">
            Windows-native security hardening, firewall management, and event log analysis.
        </p>
    </div>
    <a href="{{ url_for('defense.index') }}" class="btn btn-sm" style="margin-left:auto">&larr; Defense</a>
</div>

<!-- Tab Bar -->
<div class="tab-bar">
    <button class="tab active" data-tab-group="windef" data-tab="audit" onclick="showTab('windef','audit')">Security Audit</button>
    <button class="tab" data-tab-group="windef" data-tab="checks" onclick="showTab('windef','checks')">Quick Checks</button>
    <button class="tab" data-tab-group="windef" data-tab="firewall" onclick="showTab('windef','firewall')">Firewall Manager</button>
    <button class="tab" data-tab-group="windef" data-tab="logs" onclick="showTab('windef','logs')">Event Log Analysis</button>
</div>

<!-- AUDIT TAB -->
<div class="tab-content active" data-tab-group="windef" data-tab="audit">
<div class="section">
    <h2>Security Audit</h2>
    <div class="tool-actions">
        <button id="btn-win-audit" class="btn btn-primary" onclick="winRunAudit()">Run Full Audit</button>
    </div>
    <div style="display:flex;gap:24px;align-items:flex-start;flex-wrap:wrap">
        <div class="score-display">
            <div class="score-value" id="win-audit-score">--</div>
            <div class="score-label">Security Score</div>
        </div>
        <div style="flex:1;min-width:300px">
            <table class="data-table">
                <thead><tr><th>Check</th><th>Status</th><th>Details</th></tr></thead>
                <tbody id="win-audit-results">
                    <tr><td colspan="3" class="empty-state">Run an audit to see results.</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<!-- QUICK CHECKS TAB -->
<div class="tab-content" data-tab-group="windef" data-tab="checks">
<div class="section">
    <h2>Quick Checks</h2>
    <div class="tool-grid">
        <div class="tool-card">
            <h4>Windows Firewall</h4>
            <p>Check firewall profile states</p>
            <button class="btn btn-small" onclick="winRunCheck('firewall')">Run</button>
            <pre class="output-panel tool-result" id="win-check-firewall"></pre>
        </div>
        <div class="tool-card">
            <h4>SSH Config</h4>
            <p>Check OpenSSH server settings</p>
            <button class="btn btn-small" onclick="winRunCheck('ssh')">Run</button>
            <pre class="output-panel tool-result" id="win-check-ssh"></pre>
        </div>
        <div class="tool-card">
            <h4>Open Ports</h4>
            <p>Scan for high-risk listening ports</p>
            <button class="btn btn-small" onclick="winRunCheck('ports')">Run</button>
            <pre class="output-panel tool-result" id="win-check-ports"></pre>
        </div>
        <div class="tool-card">
            <h4>Updates</h4>
            <p>Check installed Windows hotfixes</p>
            <button class="btn btn-small" onclick="winRunCheck('updates')">Run</button>
            <pre class="output-panel tool-result" id="win-check-updates"></pre>
        </div>
        <div class="tool-card">
            <h4>Users</h4>
            <p>Check admin accounts and guest status</p>
            <button class="btn btn-small" onclick="winRunCheck('users')">Run</button>
            <pre class="output-panel tool-result" id="win-check-users"></pre>
        </div>
        <div class="tool-card">
            <h4>Permissions</h4>
            <p>Check critical file/folder ACLs</p>
            <button class="btn btn-small" onclick="winRunCheck('permissions')">Run</button>
            <pre class="output-panel tool-result" id="win-check-permissions"></pre>
        </div>
        <div class="tool-card">
            <h4>Services</h4>
            <p>Check for risky Windows services</p>
            <button class="btn btn-small" onclick="winRunCheck('services')">Run</button>
            <pre class="output-panel tool-result" id="win-check-services"></pre>
        </div>
        <div class="tool-card">
            <h4>Windows Defender</h4>
            <p>AV status and real-time protection</p>
            <button class="btn btn-small" onclick="winRunCheck('defender')">Run</button>
            <pre class="output-panel tool-result" id="win-check-defender"></pre>
        </div>
        <div class="tool-card">
            <h4>UAC Status</h4>
            <p>User Account Control settings</p>
            <button class="btn btn-small" onclick="winRunCheck('uac')">Run</button>
            <pre class="output-panel tool-result" id="win-check-uac"></pre>
        </div>
    </div>
</div>
</div>

<!-- FIREWALL TAB -->
<div class="tab-content" data-tab-group="windef" data-tab="firewall">
<div class="section">
    <h2>Windows Firewall Manager</h2>
    <div class="tool-actions">
        <button class="btn btn-small" onclick="winLoadFwRules()">Refresh Rules</button>
    </div>
    <pre class="output-panel scrollable" id="win-fw-rules">Click "Refresh Rules" to load current Windows Firewall rules.</pre>
    <div style="margin-top:12px">
        <div class="input-row">
            <input type="text" id="win-block-ip" placeholder="IP address to block">
            <button class="btn btn-danger btn-small" onclick="winBlockIP()">Block IP</button>
            <button class="btn btn-small" onclick="winUnblockIP()">Unblock IP</button>
        </div>
        <pre class="output-panel" id="win-fw-result" style="min-height:0"></pre>
    </div>
</div>
</div>

<!-- EVENT LOG TAB -->
<div class="tab-content" data-tab-group="windef" data-tab="logs">
<div class="section">
    <h2>Event Log Analysis</h2>
    <p style="font-size:0.8rem;color:var(--text-muted);margin-bottom:8px">
        Analyze Windows Security and System event logs for failed logins, errors, and threats.
    </p>
    <div class="tool-actions">
        <button id="btn-win-logs" class="btn btn-primary" onclick="winAnalyzeLogs()">Analyze Event Logs</button>
    </div>
    <pre class="output-panel scrollable" id="win-log-output">Click "Analyze Event Logs" to parse Windows event logs.</pre>
</div>
</div>

<script>
/* ── Windows Defense ── */
function winRunAudit() {
    var btn = document.getElementById('btn-win-audit');
    setLoading(btn, true);
    postJSON('/defense/windows/audit', {}).then(function(data) {
        setLoading(btn, false);
        if (data.error) { renderOutput('win-audit-results', 'Error: ' + data.error); return; }
        var scoreEl = document.getElementById('win-audit-score');
        if (scoreEl) {
            scoreEl.textContent = data.score + '%';
            scoreEl.style.color = data.score >= 80 ? 'var(--success)' : data.score >= 50 ? 'var(--warning)' : 'var(--danger)';
        }
        var html = '';
        (data.checks || []).forEach(function(c) {
            html += '<tr><td>' + escapeHtml(c.name) + '</td><td><span class="badge ' + (c.passed ? 'badge-pass' : 'badge-fail') + '">'
                + (c.passed ? 'PASS' : 'FAIL') + '</span></td><td>' + escapeHtml(c.details || '') + '</td></tr>';
        });
        document.getElementById('win-audit-results').innerHTML = html || '<tr><td colspan="3">No results</td></tr>';
    }).catch(function() { setLoading(btn, false); });
}

function winRunCheck(name) {
    var el = document.getElementById('win-check-' + name);
    if (el) { el.textContent = 'Running...'; el.style.display = 'block'; }
    postJSON('/defense/windows/check/' + name, {}).then(function(data) {
        if (data.error) { if (el) el.textContent = 'Error: ' + data.error; return; }
        var lines = (data.checks || []).map(function(c) {
            return (c.passed ? '[PASS] ' : '[FAIL] ') + c.name + (c.details ? ' — ' + c.details : '');
        });
        if (el) el.textContent = lines.join('\n') || 'No results';
    }).catch(function() { if (el) el.textContent = 'Request failed'; });
}

function winLoadFwRules() {
    fetchJSON('/defense/windows/firewall/rules').then(function(data) {
        renderOutput('win-fw-rules', data.rules || 'Could not load rules');
    });
}

function winBlockIP() {
    var ip = document.getElementById('win-block-ip').value.trim();
    if (!ip) return;
    postJSON('/defense/windows/firewall/block', {ip: ip}).then(function(data) {
        renderOutput('win-fw-result', data.message || data.error);
        if (data.success) { document.getElementById('win-block-ip').value = ''; winLoadFwRules(); }
    });
}

function winUnblockIP() {
    var ip = document.getElementById('win-block-ip').value.trim();
    if (!ip) return;
    postJSON('/defense/windows/firewall/unblock', {ip: ip}).then(function(data) {
        renderOutput('win-fw-result', data.message || data.error);
        if (data.success) winLoadFwRules();
    });
}

function winAnalyzeLogs() {
    var btn = document.getElementById('btn-win-logs');
    setLoading(btn, true);
    postJSON('/defense/windows/logs/analyze', {}).then(function(data) {
        setLoading(btn, false);
        if (data.error) { renderOutput('win-log-output', 'Error: ' + data.error); return; }
        var lines = [];
        if (data.auth_results && data.auth_results.length) {
            lines.push('=== Failed Login Attempts (Event ID 4625) ===');
            data.auth_results.forEach(function(r) {
                lines.push(r.ip + ': ' + r.count + ' failures (' + (r.usernames || []).join(', ') + ')');
            });
        } else { lines.push('No failed login attempts found in Security log.'); }
        if (data.system_results && data.system_results.length) {
            lines.push('\n=== System Log Warnings & Errors ===');
            data.system_results.forEach(function(r) {
                lines.push('[' + r.severity + '] Event ' + r.id + ' (' + r.type + '): ' + (r.detail || '').substring(0, 120));
            });
        }
        renderOutput('win-log-output', lines.join('\n') || 'No findings.');
    }).catch(function() { setLoading(btn, false); renderOutput('win-log-output', 'Request failed'); });
}
</script>
{% endblock %}
