{include file="sections/header.tpl"}
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="card card-hovered mb20 card-primary">
                            <div class="card-header">
                                <h3 class="card-title">{Lang::T('Routers')}</h3>
                            </div>
                            <div class="card-body">
                                <div class="md-whiteframe-z1 mb20 text-center">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <form id="site-search" method="post" action="{$_url}routers/list/">
                                                <div class="input-group">
                                                    <div class="input-group-text">
                                                        <span class="fa fa-search"></span>
                                                    </div>
                                                    <input type="text" name="name" class="form-control"
                                                        placeholder="{Lang::T('Search by Name')}...">
                                                    <button class="btn btn-success input-group-btn" type="submit">{Lang::T('Search')}</button>
                                                    <!-- <div class="input-group-btn">
                                                    </div> -->
                                                </div>
                                            </form>
                                        </div>
                                        <div class="col-md-4">
                                            <a href="{$_url}routers/add" class="btn btn-primary btn-block"><i
                                                    class="fa fa-add"> </i> {Lang::T('New Router')}</a>
                                        </div>&nbsp;
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped table-condensed">
                                        <thead>
                                            <tr>
                                                <th>{Lang::T('Router Name')}</th>
                                                <th>{Lang::T('IP Address')}</th>
                                                <th>{Lang::T('Status')}</th>
                                                <th>{Lang::T('Uptime')}</th>
                                                <th>{Lang::T('Free Memory')}</th>
                                                <th>{Lang::T('CPU Load')}</th>
                                                <th>{Lang::T('Manage')}</th>
                                                <th>ID</th>
                                                <th>{Lang::T('Download')}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {foreach $d as $ds}
                                                <tr {if $ds['enabled'] != 1}class="danger" title="disabled" {/if}>
                                                    <td>{$ds['name']}</td>
                                                    <td>{$ds['ip_address']}</td>
                                                    <td class="router-status" data-router-id="{$ds['id']}"><span class="loading-spinner"></span><span class="loader">Loading...</span></td>
                                                    <td class="router-uptime text-success" data-router-id="{$ds['id']}"><span class="loading-spinner"></span><span class="loader">Loading...</span></td>
                                                    <td class="router-used-memory  text-warning" data-router-id="{$ds['id']}"><span class="loading-spinner"></span><span class="loader">Loading...</span></td>
                                                    <td class="router-cpu-load text-primary" data-router-id="{$ds['id']}"><span class="loading-spinner"></span><span class="loader">Loading...</span></td>
                                                    <td>
                                                        <a href="{$_url}routers/edit/{$ds['id']}" class="btn btn-info btn-xs">{Lang::T('Edit')}</a>
                                                        <a href="{$_url}routers/delete/{$ds['id']}" id="{$ds['id']}"
                                                            onclick="return confirm('{Lang::T('Delete')}?')"
                                                            class="btn btn-danger btn-xs"><i class="fa fa-trash"></i></a>
                                                        <button class="btn btn-warning btn-xs btn-reboot" data-router-id="{$ds['id']}"><i class="fa fa-refresh"></i> {Lang::T('Reboot')}</button>
                                                    </td>
                                                    <td>{$ds['id']}</td>
                                                    <td>
                                                        <form action="{$_url}routers/download" method="post" style="display:inline;">
                                                            <input type="hidden" name="router_id" value="{$ds['id']}">
                                                            <input type="hidden" name="router_name" value="{$ds['name']}">
                                                            <button type="submit" class="btn btn-success btn-xs">
                                                                <i class="fa fa-download"></i> {Lang::T('Download')}
                                                            </button>
                                                        </form>
                                                    </td>
                                                </tr>
                                            {/foreach}
                                        </tbody>
                                    </table>
                                </div>
                                {include file="pagination.tpl"}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
{include file="sections/footer.tpl"}

<style>
    .loader {
        display: inline-block;
        animation: loading 1.5s infinite;
        margin: 0;
        color: #6c757d;
        font-style: italic;
        font-size: 0.9em;
    }

    @keyframes loading {
        0% {
            opacity: 1;
        }
        50% {
            opacity: 0.5;
        }
        100% {
            opacity: 1;
        }
    }

    .loading-spinner {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid #f3f3f3;
        border-top: 2px solid #007bff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-right: 8px;
        vertical-align: middle;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .status.timeout {
        background-color: #ffc107;
        color: #000;
    }

    .status.error {
        background-color: #dc3545;
        color: white;
    }

    .text-warning {
        color: #ffc107 !important;
        font-weight: bold;
    }

    .loading-container {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .router-uptime {
        color: #28a745; /* Green for uptime */
	    font-weight: bold;
    }

    .router-used-memory {
        color: #fd7e14; /* Orange for memory */
	    font-weight: bold;
    }

    .router-cpu-load {
        color: #d63384; /* Pink for CPU load */
	    font-weight: bold;
    }

    .router-status {
        font-weight: bold;
    }

    .router-status .status {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
    }

    .router-status .online {
        background-color: #28a745;
        color: white;
    }

    .router-status .offline {
        background-color: #dc3545;
        color: white;
    }
</style>

<script>
$(document).ready(function() {
    // Get all router IDs
    var routerIds = [];
    $('.router-uptime, .router-used-memory, .router-total-memory, .router-cpu-load, .router-status').each(function() {
        var routerId = $(this).data('router-id');
        if (routerId && routerIds.indexOf(routerId) === -1) {
            routerIds.push(routerId);
        }
    });

    // Option 1: Load all router data in parallel with individual timeouts (current implementation)
    var loadPromises = routerIds.map(function(routerId) {
        return new Promise(function(resolve, reject) {
            $.ajax({
                url: '{$_url}routers/get_resources',
                data: { router_id: routerId },
                dataType: 'json',
                timeout: 8000, // 8 second timeout per router
                success: function(resources) {
                    var result = {};
                    result.routerId = routerId;
                    result.resources = resources;
                    resolve(result);
                },
                error: function(xhr, status, error) {
                    var errorType = status === 'timeout' ? 'timeout' : 'error';
                    var result = {};
                    result.routerId = routerId;
                    result.error = errorType;
                    result.resources = null;
                    resolve(result);
                }
            });
        });
    });

    // Process all results when they complete
    Promise.all(loadPromises).then(function(results) {
        results.forEach(function(result) {
            var routerId = result.routerId;
            var resources = result.resources;
            var error = result.error;
            
            // Find all elements for this router
            var row = $('[data-router-id="' + routerId + '"]').first().closest('tr');
            
            if (error) {
                // Handle error state
                row.find('.router-uptime').html('<span class="text-warning">' + (error === 'timeout' ? 'Timeout' : 'Error') + '</span>');
                row.find('.router-used-memory').html('<span class="text-warning">' + (error === 'timeout' ? 'Timeout' : 'Error') + '</span>');
                row.find('.router-cpu-load').html('<span class="text-warning">' + (error === 'timeout' ? 'Timeout' : 'Error') + '</span>');
                row.find('.router-status').html('<span class="status offline">' + (error === 'timeout' ? 'Timeout' : 'Error') + '</span>');
            } else if (resources) {
                // Update all fields for this router
                row.find('.router-uptime').html(resources.uptime || 'N/A');
                row.find('.router-used-memory').html(resources.freeMemory || 'N/A');
                row.find('.router-cpu-load').html(resources.cpuLoad || 'N/A');
                
                // Update router status
                var statusElement = row.find('.router-status');
                if (resources.status === 'Online') {
                    statusElement.html('<span class="status online">Online</span>');
                } else {
                    statusElement.html('<span class="status offline">Offline</span>');
                }
            } else {
                // No data available
                row.find('.router-uptime').html('N/A');
                row.find('.router-used-memory').html('N/A');
                row.find('.router-cpu-load').html('N/A');
                row.find('.router-status').html('<span class="status offline">Offline</span>');
            }
        });
    });

    // Option 2: Alternative bulk loading approach (commented out - uncomment to use)
    /*
    $.ajax({
        url: '{$_url}routers/get_all_resources',
        dataType: 'json',
        timeout: 15000, // 15 second timeout for bulk request
        success: function(allResources) {
            Object.keys(allResources).forEach(function(routerId) {
                var resources = allResources[routerId];
                var row = $('[data-router-id="' + routerId + '"]').first().closest('tr');
                
                if (resources) {
                    row.find('.router-uptime').html(resources.uptime || 'N/A');
                    row.find('.router-used-memory').html(resources.freeMemory || 'N/A');
                    row.find('.router-cpu-load').html(resources.cpuLoad || 'N/A');
                    
                    var statusElement = row.find('.router-status');
                    if (resources.status === 'Online') {
                        statusElement.html('<span class="status online">Online</span>');
                    } else {
                        statusElement.html('<span class="status offline">Offline</span>');
                    }
                } else {
                    row.find('.router-uptime').html('N/A');
                    row.find('.router-used-memory').html('N/A');
                    row.find('.router-cpu-load').html('N/A');
                    row.find('.router-status').html('<span class="status offline">Offline</span>');
                }
            });
        },
        error: function(xhr, status, error) {
            console.error('Bulk loading failed:', error);
            // Fallback to individual loading
            $('.router-uptime, .router-used-memory, .router-cpu-load, .router-status').html('<span class="text-danger">Error</span>');
        }
    });
    */

    // Reboot router
    $('.btn-reboot').on('click', function() {
        var routerId = $(this).data('router-id');
        if (confirm('Are you sure you want to reboot this router?')) {
            $.ajax({
                url: '{$_url}routers/reboot',
                data: { router_id: routerId },
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'Rebooting') {
                        alert(response.message);
                    } else {
                        alert('Error: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText);
                    alert('Failed to send reboot command. Please try again.');
                }
            });
        }
    });
});
</script>