<?php $this->load->view('header'); ?>

<div class="content-wrapper">
    <section class="content-header">
        <h1>
            <i class="fa fa-tachometer"></i> Performance Dashboard
            <small>System Performance Monitoring</small>
        </h1>
    </section>

    <section class="content">
        <div class="row">
            <!-- Memory Usage -->
            <div class="col-lg-3 col-xs-6">
                <div class="small-box bg-aqua">
                    <div class="inner">
                        <h3><?= $memory_usage['current'] ?></h3>
                        <p>Current Memory</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-memory"></i>
                    </div>
                </div>
            </div>

            <!-- Peak Memory -->
            <div class="col-lg-3 col-xs-6">
                <div class="small-box bg-green">
                    <div class="inner">
                        <h3><?= $memory_usage['peak'] ?></h3>
                        <p>Peak Memory</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-line-chart"></i>
                    </div>
                </div>
            </div>

            <!-- Cache Files -->
            <div class="col-lg-3 col-xs-6">
                <div class="small-box bg-yellow">
                    <div class="inner">
                        <h3 id="cache-files">0</h3>
                        <p>Cache Files</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-files-o"></i>
                    </div>
                </div>
            </div>

            <!-- Database Size -->
            <div class="col-lg-3 col-xs-6">
                <div class="small-box bg-red">
                    <div class="inner">
                        <h3 id="db-size">0 MB</h3>
                        <p>Database Size</p>
                    </div>
                    <div class="icon">
                        <i class="fa fa-database"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Performance Actions -->
            <div class="col-md-6">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">
                            <i class="fa fa-cogs"></i> Performance Actions
                        </h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-6">
                                <button class="btn btn-warning btn-block" onclick="clearAllCache()">
                                    <i class="fa fa-trash"></i> Clear All Cache
                                </button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-info btn-block" onclick="optimizeDatabase()">
                                    <i class="fa fa-database"></i> Optimize Database
                                </button>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <button class="btn btn-success btn-block" onclick="testPerformance()">
                                    <i class="fa fa-play"></i> Test Performance
                                </button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-primary btn-block" onclick="refreshStats()">
                                    <i class="fa fa-refresh"></i> Refresh Stats
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- System Status -->
            <div class="col-md-6">
                <div class="box box-success">
                    <div class="box-header with-border">
                        <h3 class="box-title">
                            <i class="fa fa-check-circle"></i> System Status
                        </h3>
                    </div>
                    <div class="box-body">
                        <div class="status-item">
                            <i class="fa fa-check text-green"></i>
                            <span>Database Connection: <strong>OK</strong></span>
                        </div>
                        <div class="status-item">
                            <i class="fa fa-check text-green"></i>
                            <span>Cache System: <strong>Active</strong></span>
                        </div>
                        <div class="status-item">
                            <i class="fa fa-check text-green"></i>
                            <span>Compression: <strong>Enabled</strong></span>
                        </div>
                        <div class="status-item">
                            <i class="fa fa-check text-green"></i>
                            <span>Database Indexes: <strong>Optimized</strong></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Metrics -->
        <div class="row">
            <div class="col-md-12">
                <div class="box box-info">
                    <div class="box-header with-border">
                        <h3 class="box-title">
                            <i class="fa fa-bar-chart"></i> Performance Metrics
                        </h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-4">
                                <h4>Database Performance</h4>
                                <div id="db-metrics">
                                    <p><strong>Total Tables:</strong> <span id="total-tables">-</span></p>
                                    <p><strong>Database Size:</strong> <span id="db-size-detail">-</span></p>
                                    <p><strong>Largest Table:</strong> <span id="largest-table">-</span></p>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <h4>Cache Performance</h4>
                                <div id="cache-metrics">
                                    <p><strong>Cache Files:</strong> <span id="cache-files-detail">-</span></p>
                                    <p><strong>Cache Size:</strong> <span id="cache-size">-</span></p>
                                    <p><strong>Hit Rate:</strong> <span id="cache-hit-rate">-</span></p>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <h4>System Performance</h4>
                                <div id="system-metrics">
                                    <p><strong>Load Time:</strong> <span id="load-time">-</span></p>
                                    <p><strong>Memory Usage:</strong> <span id="memory-usage">-</span></p>
                                    <p><strong>PHP Version:</strong> <span id="php-version">-</span></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<style>
.status-item {
    margin: 10px 0;
    padding: 5px 0;
    border-bottom: 1px solid #eee;
}

.status-item:last-child {
    border-bottom: none;
}

.small-box .inner h3 {
    font-size: 28px;
    font-weight: bold;
}

.small-box .inner p {
    font-size: 14px;
}
</style>

<script>
$(document).ready(function() {
    loadPerformanceStats();
    
    // Auto-refresh every 30 seconds
    setInterval(loadPerformanceStats, 30000);
});

function loadPerformanceStats() {
    // Load database stats
    $.get('<?= base_url("performance/query_stats") ?>', function(data) {
        if (data.total_queries) {
            $('#total-tables').text(data.total_queries);
        }
    });
    
    // Load cache stats
    var cacheFiles = 0;
    var cacheSize = 0;
    
    <?php if (isset($cache_stats['database'])): ?>
    cacheFiles += <?= $cache_stats['database']['file_count'] ?>;
    cacheSize += <?= $cache_stats['database']['total_size'] ?>;
    <?php endif; ?>
    
    <?php if (isset($cache_stats['file'])): ?>
    cacheFiles += <?= $cache_stats['file']['file_count'] ?>;
    cacheSize += <?= $cache_stats['file']['total_size'] ?>;
    <?php endif; ?>
    
    $('#cache-files').text(cacheFiles);
    $('#cache-files-detail').text(cacheFiles);
    $('#cache-size').text(formatBytes(cacheSize));
    
    // Load database size
    <?php if (isset($database_stats['total_size'])): ?>
    $('#db-size').text('<?= $database_stats['total_size'] ?> MB');
    $('#db-size-detail').text('<?= $database_stats['total_size'] ?> MB');
    <?php endif; ?>
    
    // Load system info
    $('#php-version').text('<?= PHP_VERSION ?>');
    $('#memory-usage').text('<?= $memory_usage['current'] ?>');
}

function clearAllCache() {
    if (confirm('Are you sure you want to clear all caches?')) {
        $.post('<?= base_url("performance/clear_cache") ?>', function(data) {
            if (data.status === 'success') {
                alert('Cache cleared successfully!');
                loadPerformanceStats();
            } else {
                alert('Error: ' + data.message);
            }
        });
    }
}

function optimizeDatabase() {
    if (confirm('Are you sure you want to optimize the database?')) {
        $.post('<?= base_url("performance/optimize_database") ?>', function(data) {
            if (data.status === 'success') {
                alert('Database optimized successfully! ' + data.optimized_count + ' tables optimized.');
                loadPerformanceStats();
            } else {
                alert('Error: ' + data.message);
            }
        });
    }
}

function testPerformance() {
    $.get('<?= base_url("performance/test_performance") ?>', function(data) {
        $('#load-time').text(data.load_time);
        alert('Performance Test Results:\n' +
              'Load Time: ' + data.load_time + '\n' +
              'Memory Used: ' + data.memory_used + '\n' +
              'Peak Memory: ' + data.peak_memory);
    });
}

function refreshStats() {
    loadPerformanceStats();
    alert('Stats refreshed!');
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    var k = 1024;
    var sizes = ['Bytes', 'KB', 'MB', 'GB'];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
</script>

<?php $this->load->view('footer'); ?>
