{% extends "base.html" %}

{% block title %}Dashboard - Server Monitoring{% endblock %}

{% block page_title %}Dashboard{% endblock %}

{% block extra_css %}
<style>
        .table-container {
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .table {
            margin-bottom: 0;
            table-layout: fixed; /* Ensures consistent column widths */
            width: 100%; /* Makes the table take up the full container width */
        }
        .table th, .table td {
            text-align: center;
            word-wrap: break-word; /* Ensures long text wraps within the cell */
        }
        .table th:nth-child(1), .table td:nth-child(1) {
            width: 20%; /* Hostname column */
        }
        .table th:nth-child(2), .table td:nth-child(2) {
            width: 20%; /* Device IP column */
        }
        .table th:nth-child(3), .table td:nth-child(3) {
            width: 20%; /* Nume Masa column */
        }
        .table th:nth-child(4), .table td:nth-child(4) {
            width: 20%; /* Timestamp column */
        }
        .table th:nth-child(5), .table td:nth-child(5) {
            width: 20%; /* Event Description column */
        }
        .refresh-timer {
            text-align: center;
            margin-bottom: 10px;
            font-size: 1.2rem;
            color: #343a40;
        }
    </style>
    <script>
        // Countdown timer for refresh
        let countdown = 30; // 30 seconds
        function updateTimer() {
            document.getElementById('refresh-timer').innerText = countdown;
            countdown--;
            if (countdown < 0) {
                location.reload(); // Refresh the page
            }
        }
        setInterval(updateTimer, 1000); // Update every second

        // Database reset functionality
        async function resetDatabase(event) {
            try {
                // First, get database statistics
                const statsResponse = await fetch('/database_stats');
                const stats = await statsResponse.json();
                
                if (!stats.success) {
                    alert('❌ Error getting database statistics:\n' + stats.error);
                    return;
                }
                
                const totalLogs = stats.total_logs;
                const uniqueDevices = stats.unique_devices;
                
                if (totalLogs <= 1) { // Only reset log exists
                    alert('ℹ️ Database is already empty!\nNo user logs to delete.');
                    return;
                }
                
                // Show confirmation dialog with detailed statistics
                const confirmed = confirm(
                    `⚠️ WARNING: Database Reset Operation ⚠️\n\n` +
                    `This will permanently delete:\n` +
                    `• ${totalLogs} log entries\n` +
                    `• Data from ${uniqueDevices} unique devices\n` +
                    `• Date range: ${stats.earliest_log || 'N/A'} to ${stats.latest_log || 'N/A'}\n\n` +
                    `⚠️ ALL DEVICE HISTORY WILL BE LOST ⚠️\n\n` +
                    `This action cannot be undone!\n\n` +
                    `Are you absolutely sure you want to proceed?`
                );
                
                if (!confirmed) {
                    return;
                }
                
                // Second confirmation for safety
                const doubleConfirmed = confirm(
                    `🚨 FINAL CONFIRMATION 🚨\n\n` +
                    `You are about to permanently DELETE:\n` +
                    `✗ ${totalLogs} log entries\n` +
                    `✗ ${uniqueDevices} device histories\n\n` +
                    `This is your LAST CHANCE to cancel!\n\n` +
                    `Click OK to proceed with deletion.`
                );
                
                if (!doubleConfirmed) {
                    return;
                }
                
                // Show loading indicator
                const button = event ? event.target : document.querySelector('button[onclick*="resetDatabase"]');
                const originalText = button ? button.innerHTML : '';
                if (button) {
                    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Clearing Database...';
                    button.disabled = true;
                }
                
                // Send reset request
                const resetResponse = await fetch('/reset_database', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await resetResponse.json();
                
                if (result.success) {
                    alert(
                        `✅ Database Reset Completed Successfully!\n\n` +
                        `Operation Summary:\n` +
                        `• ${result.deleted_count} log entries deleted\n` +
                        `• Database schema reinitialized\n` +
                        `• Reset timestamp: ${result.timestamp}\n\n` +
                        `The dashboard will refresh to show the clean database.`
                    );
                    location.reload(); // Refresh to show empty database
                } else {
                    alert('❌ Database Reset Failed:\n' + result.error);
                    if (button) {
                        button.innerHTML = originalText;
                        button.disabled = false;
                    }
                }
                
            } catch (error) {
                alert('❌ Network Error:\n' + error.message);
                // Restore button if it was changed
                try {
                    const button = event ? event.target : document.querySelector('button[onclick*="resetDatabase"]');
                    if (button) {
                        button.innerHTML = '<i class="fas fa-trash-alt"></i> Clear Database';
    </script>
</style>
{% endblock %}

{% block extra_js %}
<script>
        // Countdown timer for refresh
        let countdown = 30; // 30 seconds
        function updateTimer() {
            const timerElement = document.getElementById('refresh-timer');
            if (timerElement) {
                timerElement.innerText = countdown;
            }
            countdown--;
            if (countdown < 0) {
                location.reload(); // Refresh the page
            }
        }
        setInterval(updateTimer, 1000); // Update every second

        // Database reset functionality
        async function resetDatabase(event) {
            try {
                // First, get database statistics
                const statsResponse = await fetch('/database_stats');
                const stats = await statsResponse.json();
                
                if (!stats.success) {
                    alert('❌ Error getting database statistics:\n' + stats.error);
                    return;
                }
                
                const totalLogs = stats.total_logs;
                const uniqueDevices = stats.unique_devices;
                
                if (totalLogs <= 1) { // Only reset log exists
                    alert('ℹ️ Database is already empty!\nNo user logs to delete.');
                    return;
                }
                
                // Show confirmation dialog with detailed statistics
                const confirmed = confirm(
                    `⚠️ WARNING: Database Reset Operation ⚠️\n\n` +
                    `This will permanently delete:\n` +
                    `• ${totalLogs} log entries\n` +
                    `• Data from ${uniqueDevices} unique devices\n` +
                    `• Date range: ${stats.earliest_log || 'N/A'} to ${stats.latest_log || 'N/A'}\n\n` +
                    `⚠️ ALL DEVICE HISTORY WILL BE LOST ⚠️\n\n` +
                    `This action cannot be undone!\n\n` +
                    `Are you absolutely sure you want to proceed?`
                );
                
                if (!confirmed) {
                    return;
                }
                
                // Second confirmation for safety
                const doubleConfirmed = confirm(
                    `🚨 FINAL CONFIRMATION 🚨\n\n` +
                    `You are about to permanently DELETE:\n` +
                    `✗ ${totalLogs} log entries\n` +
                    `✗ ${uniqueDevices} device histories\n\n` +
                    `This is your LAST CHANCE to cancel!\n\n` +
                    `Click OK to proceed with deletion.`
                );
                
                if (!doubleConfirmed) {
                    return;
                }
                
                // Show loading indicator
                const button = event ? event.target : document.querySelector('button[onclick*="resetDatabase"]');
                const originalText = button ? button.innerHTML : '';
                if (button) {
                    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Clearing Database...';
                    button.disabled = true;
                }
                
                // Send reset request
                const resetResponse = await fetch('/reset_database', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await resetResponse.json();
                
                if (result.success) {
                    alert(
                        `✅ Database Reset Completed Successfully!\n\n` +
                        `Operation Summary:\n` +
                        `• ${result.deleted_count} log entries deleted\n` +
                        `• Database schema reinitialized\n` +
                        `• Reset timestamp: ${result.timestamp}\n\n` +
                        `The dashboard will refresh to show the clean database.`
                    );
                    location.reload(); // Refresh to show empty database
                } else {
                    alert('❌ Database Reset Failed:\n' + result.error);
                    if (button) {
                        button.innerHTML = originalText;
                        button.disabled = false;
                    }
                }
                
            } catch (error) {
                alert('❌ Network Error:\n' + error.message);
                // Restore button if it was changed
                try {
                    const button = event ? event.target : document.querySelector('button[onclick*="resetDatabase"]');
                    if (button) {
                        button.innerHTML = '<i class="fas fa-trash-alt"></i> Clear Database';