{% extends 'base.html' %}

{% block title %}AVS Migration Risks Analysis{% endblock %}

{% block content %}
<div class="container">
<h1 class="text-center">AVS Migration Risks Analysis</h1>
<p class="text-center lead">This page will display potential migration risks for the uploaded file: <code>{{ filename }}</code></p>

{% if risk_results and risk_results.risks %}
<!-- Summary Cards Section -->
<div class="d-flex flex-wrap justify-content-start" id="summary-cards">
    {% set risk_order = ['emergency', 'blocking', 'danger', 'warning', 'info'] %}
    {% for risk_level in risk_order %}
        {% for risk_name, risk_data in risk_results.risks.items() %}
            {% if risk_data.count > 0 and risk_data.risk_level == risk_level %}
                <a href="#{{ risk_name }}-card" class="card m-2 text-decoration-none" style="width: 18rem;" title="Click to view more details about {{ risk_data.function_name }}">
                    <div class="card-body">
                        <h5 class="card-title">{{ risk_name.replace('detect_', '').replace('_', ' ').title() }}</h5>
                        <p class="card-text">Count: {{ risk_data.count }}</p>
                    </div>
                    <div class="card-footer">
                        <span class="badge rounded-pill {{ get_risk_badge_class(risk_data.risk_level) }}">
                            Sev: {{ get_risk_display_name(risk_data.risk_level) }}
                        </span>
                    </div>
                </a>
            {% endif %}
        {% endfor %}
    {% endfor %}
</div>

<!-- Filter Buttons -->
<div class="d-flex justify-content-end mb-3">
    <div class="btn-group" role="group" aria-label="Filter Severity">
        <button type="button" class="btn btn-outline-primary" onclick="filterCards('all')">All</button>
        <button type="button" class="btn btn-outline-dark filter-outline-dark" onclick="filterCards('emergency')">Emergency</button>
        <button type="button" class="btn btn-outline-danger" onclick="filterCards('blocking')">Blocking</button>
        <button type="button" class="btn btn-outline-warning" onclick="filterCards('warning')">Warning</button>
        <button type="button" class="btn btn-outline-info" onclick="filterCards('info')">Info</button>
    </div>
</div>

<!-- Risk Detail Cards -->
{% set risk_order = ['emergency', 'blocking', 'danger', 'warning', 'info'] %}
{% for risk_level in risk_order %}
    {% for risk_name, risk_data in risk_results.risks.items() %}
        {% if risk_data.count > 0 and risk_data.risk_level == risk_level %}
            <div class="card mb-4" id="{{ risk_name }}-card" data-risk-level="{{ risk_data.risk_level }}">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h2>{{ risk_name.replace('detect_', '').replace('_', ' ').title() }}</h2>
                    <button class="btn btn-primary" data-id="{{ risk_name }}-table" onclick="downloadTableAsCSV(this)">
                        <i class="fas fa-download"></i> Download CSV
                    </button>
                </div>
            <div class="card-body">
                {% if risk_data.risk_info %}
                    <p>{{ risk_data.risk_info.description }}</p>

                    {% if risk_data.risk_info.alert_message %}
                    <div class="alert alert-primary" role="alert">
                        <i class="fa-solid fa-circle-info"></i>
                        {{ risk_data.risk_info.alert_message | safe }}
                    </div>
                    {% endif %}
                {% endif %}                <!-- Generic table for all risk types -->
                {% if risk_data.data %}
                    <table class="table table-striped resizable-table" id="{{ risk_name }}-table">
                        <thead>
                            <tr>
                                {% if risk_data.data is mapping %}
                                    <!-- Handle dictionary data (like ESX versions) -->
                                    <th>Item</th>
                                    <th>Count</th>
                                    {% if risk_name == 'detect_esx_versions' and risk_data.details and risk_data.details.version_risks %}
                                        <th>Risk Level</th>
                                    {% endif %}
                                {% else %}
                                    <!-- Handle list of dictionaries -->
                                    {% for key in risk_data.data[0].keys() %}
                                        <th>{{ key }}</th>
                                    {% endfor %}
                                {% endif %}
                            </tr>
                        </thead>
                        <tbody>
                            {% if risk_data.data is mapping %}
                                <!-- Render dictionary as key-value pairs -->
                                {% for key, value in risk_data.data.items() %}
                                    <tr>
                                        <td>{{ key }}</td>
                                        <td>{{ value }}</td>
                                        {% if risk_name == 'detect_esx_versions' and risk_data.details and risk_data.details.version_risks %}
                                            <td>
                                                {% set version_risk = risk_data.details.version_risks.get(key, 'info') %}
                                                <span class="badge rounded-pill {{ get_risk_badge_class(version_risk) }}">
                                                    {{ get_risk_display_name(version_risk) }}
                                                </span>
                                            </td>
                                        {% endif %}
                                    </tr>
                                {% endfor %}
                            {% else %}
                                <!-- Render list of dictionaries -->
                                {% for item in risk_data.data %}
                                    <tr>
                                        {% for key, value in item.items() %}
                                            <td class="wrap">
                                                {% if key == 'Risk Level' %}
                                                <span class="badge rounded-pill {{ get_risk_badge_class(value) }}">
                                                    {{ get_risk_display_name(value) }}
                                                </span>
                                                {% elif value is sameas true or value|string|lower in ['true', 'yes', '1'] %}
                                                    <span class="text-success"><strong>✓</strong></span>
                                                {% elif value is sameas false or value|string|lower in ['false', 'no', '0'] %}
                                                    <span class="text-danger">✘</span>
                                                {% elif 'MiB' in key and value|string|length > 0 %}
                                                    {{ value | convert_mib_to_human_readable }}
                                                {% else %}
                                                    {{ value }}
                                                {% endif %}
                                            </td>
                                        {% endfor %}
                                    </tr>
                                {% endfor %}
                            {% endif %}
                        </tbody>
                    </table>
                {% endif %}
            </div>
            <div class="card-footer">
                <span class="badge rounded-pill {{ get_risk_badge_class(risk_data.risk_level) }}">
                    Sev: {{ get_risk_display_name(risk_data.risk_level) }}
                </span>
            </div>
        </div>
        {% endif %}
    {% endfor %}
{% endfor %}

{% else %}
<div class="alert alert-info" role="alert">
    <i class="fa-solid fa-circle-info"></i>
    No risks detected in the uploaded file, or the file could not be processed.
</div>
{% endif %}
</div>

<!-- JavaScript for filtering and CSV download -->
<style>
    /* Resizable table styles */
    .resizable-table {
        table-layout: fixed;
        width: 100%;
    }

    .resizable-table th {
        position: relative;
        padding-right: 20px;
    }

    .resizable-table th:not(:last-child)::after {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 6px;
        height: 100%;
        cursor: col-resize;
        background: transparent;
        border-right: 2px solid transparent;
        transition: border-color 0.2s;
    }

    .resizable-table th:not(:last-child):hover::after {
        border-right-color: #007bff;
    }

    .resizable-table th.resizing::after {
        border-right-color: #007bff;
    }

    .resizable-table td {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .resizable-table td.wrap {
        white-space: normal;
        word-break: break-word;
    }
</style>

<script>
    function downloadTableAsCSV(button) {
        const tableId = button.getAttribute('data-id');
        const table = document.getElementById(tableId);
        if (!table) {
            alert('Table not found.');
            return;
        }

        const rows = Array.from(table.querySelectorAll('tr'));
        const csvContent = rows.map(row => {
            const cells = Array.from(row.querySelectorAll('th, td'));
            return cells.map(cell => `"${cell.textContent.trim()}"`).join(',');
        }).join('\n');

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${tableId}.csv`;
        link.click();
    }

    function filterCards(severity) {
        const cards = document.querySelectorAll('.card[data-risk-level]');
        const summaryCards = document.querySelectorAll('#summary-cards .card');

        cards.forEach(card => {
            const riskLevel = card.getAttribute('data-risk-level');
            if (severity === 'all' || riskLevel === severity ||
                (severity === 'blocking' && (riskLevel === 'danger' || riskLevel === 'blocking')) ||
                (severity === 'emergency' && riskLevel === 'emergency')) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });

        summaryCards.forEach(card => {
            const badge = card.querySelector('.badge');
            const badgeText = badge ? badge.textContent.toLowerCase() : '';
            if (severity === 'all' || badgeText.includes(severity) ||
                (severity === 'blocking' && badgeText.includes('blocking')) ||
                (severity === 'emergency' && badgeText.includes('emergency'))) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });
    }

    // Resizable columns functionality
    function makeTablesResizable() {
        const tables = document.querySelectorAll('.resizable-table');

        tables.forEach(table => {
            const headers = table.querySelectorAll('th');

            headers.forEach((header, index) => {
                if (index < headers.length - 1) { // Don't add resizer to last column
                    let isResizing = false;
                    let startX = 0;
                    let startWidth = 0;

                    const onMouseDown = (e) => {
                        // Check if click is on the resize area (right edge of header)
                        const rect = header.getBoundingClientRect();
                        if (e.clientX >= rect.right - 10) {
                            isResizing = true;
                            startX = e.clientX;
                            startWidth = header.offsetWidth;
                            header.classList.add('resizing');

                            document.addEventListener('mousemove', onMouseMove);
                            document.addEventListener('mouseup', onMouseUp);
                            e.preventDefault();
                        }
                    };

                    const onMouseMove = (e) => {
                        if (!isResizing) return;

                        const diff = e.clientX - startX;
                        const newWidth = Math.max(50, startWidth + diff); // Minimum width of 50px
                        header.style.width = newWidth + 'px';
                    };

                    const onMouseUp = () => {
                        if (isResizing) {
                            isResizing = false;
                            header.classList.remove('resizing');
                            document.removeEventListener('mousemove', onMouseMove);
                            document.removeEventListener('mouseup', onMouseUp);
                        }
                    };

                    header.addEventListener('mousedown', onMouseDown);
                }
            });
        });
    }

    // Initialize resizable tables when DOM is loaded
    document.addEventListener('DOMContentLoaded', function() {
        makeTablesResizable();

        // Check for emergency risks and show warning popup
        checkForEmergencyRisks();
    });

    function checkForEmergencyRisks() {
        const emergencyCards = document.querySelectorAll('.card[data-risk-level="emergency"]');
        if (emergencyCards.length > 0) {
            // Create and show emergency warning modal
            showEmergencyWarning();
        }
    }

    function showEmergencyWarning() {
        // Create modal HTML
        const modalHTML = `
            <div class="modal fade" id="emergencyWarningModal" tabindex="-1" aria-labelledby="emergencyWarningModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content border-danger">
                        <div class="modal-header bg-danger text-white">
                            <h5 class="modal-title" id="emergencyWarningModalLabel">
                                <i class="fas fa-exclamation-triangle"></i> CRITICAL SECURITY ALERT
                            </h5>
                        </div>
                        <div class="modal-body">
                            <div class="alert alert-danger" role="alert">
                                <h4 class="alert-heading"><i class="fas fa-shield-alt"></i> Password Exposure Detected!</h4>
                                <p><strong>Clear text passwords have been found in your VMware environment.</strong></p>
                                <hr>
                                <p class="mb-0">
                                    <strong>IMMEDIATE ACTION REQUIRED:</strong>
                                    <ul class="mt-2">
                                        <li>Review the detected items below</li>
                                        <li>Remove all clear text passwords from VM annotations and snapshot descriptions</li>
                                        <li>Rotate any exposed passwords immediately</li>
                                        <li>Implement secure password management practices</li>
                                    </ul>
                                </p>
                            </div>
                            <div class="alert alert-info" role="alert">
                                <strong><i class="fas fa-info-circle"></i> Privacy Notice:</strong>
                                This RVTools file was analyzed in memory only and has NOT been stored on our server.
                                However, the security risk remains in your VMware environment and in the file that was submitted.
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">
                                <i class="fas fa-check"></i> I Understand - Show Analysis
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Add modal to page
        document.body.insertAdjacentHTML('beforeend', modalHTML);

        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('emergencyWarningModal'));
        modal.show();

        // Clean up modal after it's hidden
        document.getElementById('emergencyWarningModal').addEventListener('hidden.bs.modal', function () {
            this.remove();
        });
    }
</script>

{% endblock %}
