<?php
/**
 * ============================================================================
 * admin/performance.php - System Performance Monitoring
 * Real-time performance metrics and optimization tools
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Check permission
if (!hasAdminPermission('view_server_stats')) {
    setFlashMessage('Access denied. Server statistics viewing permission required.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Performance', 'url' => '']
];

// Get performance metrics
function getPerformanceMetrics() {
    global $db;
    
    $metrics = [];
    
    // Database performance
    try {
        // Query execution time
        $start = microtime(true);
        $db->query("SELECT COUNT(*) FROM users");
        $metrics['db_response_time'] = round((microtime(true) - $start) * 1000, 2);
        
        // Database size and stats
        $sql = "SELECT 
                    table_schema,
                    SUM(data_length + index_length) / 1024 / 1024 AS size_mb,
                    SUM(data_length) / 1024 / 1024 AS data_mb,
                    SUM(index_length) / 1024 / 1024 AS index_mb
                FROM information_schema.tables 
                WHERE table_schema = ?
                GROUP BY table_schema";
        $stmt = $db->prepare($sql);
        $stmt->execute([DB_NAME]);
        $db_size = $stmt->fetch(PDO::FETCH_ASSOC);
        $metrics['db_size'] = $db_size;
        
        // Slow queries
        $sql = "SELECT COUNT(*) as slow_query_count 
                FROM mysql.slow_log 
                WHERE start_time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)";
        try {
            $stmt = $db->query($sql);
            $metrics['slow_queries'] = $stmt->fetch(PDO::FETCH_ASSOC)['slow_query_count'] ?? 0;
        } catch (Exception $e) {
            $metrics['slow_queries'] = 'N/A';
        }
        
        // Table stats
        $sql = "SELECT 
                    table_name,
                    table_rows,
                    ROUND(((data_length + index_length) / 1024 / 1024), 2) AS size_mb,
                    ROUND((data_length / 1024 / 1024), 2) AS data_mb,
                    ROUND((index_length / 1024 / 1024), 2) AS index_mb,
                    ROUND((data_free / 1024 / 1024), 2) AS fragmentation_mb
                FROM information_schema.tables 
                WHERE table_schema = ?
                ORDER BY (data_length + index_length) DESC
                LIMIT 20";
        $stmt = $db->prepare($sql);
        $stmt->execute([DB_NAME]);
        $metrics['table_stats'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        logError('Performance metrics error: ' . $e->getMessage());
    }
    
    // PHP Performance
    $metrics['php_memory_usage'] = memory_get_usage(true) / 1024 / 1024;
    $metrics['php_memory_peak'] = memory_get_peak_usage(true) / 1024 / 1024;
    $metrics['php_memory_limit'] = ini_get('memory_limit');
    
    // Recent performance data
    try {
        $sql = "SELECT * FROM server_metrics 
                WHERE recorded_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                ORDER BY recorded_at ASC";
        $stmt = $db->query($sql);
        $metrics['historical_data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $metrics['historical_data'] = [];
    }
    
    return $metrics;
}

$metrics = getPerformanceMetrics();

renderAdminHeader('System Performance', $breadcrumbs);
?>

<style>
.metric-badge {
    padding: 8px 16px;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.875rem;
}
.metric-badge.excellent { background-color: #d1fae5; color: #065f46; }
.metric-badge.good { background-color: #dbeafe; color: #1e40af; }
.metric-badge.warning { background-color: #fef3c7; color: #92400e; }
.metric-badge.critical { background-color: #fee2e2; color: #991b1b; }

.performance-chart {
    height: 300px;
}

.table-stat-row:hover {
    background-color: #f9fafb;
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">
            <i class="bi bi-speedometer me-2"></i>System Performance
        </h2>
        <p class="text-muted mb-0">Monitor and optimize system performance</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise me-2"></i>Refresh
        </button>
        <button class="btn btn-primary" onclick="optimizeDatabase()">
            <i class="bi bi-gear-fill me-2"></i>Optimize Database
        </button>
    </div>
</div>

<!-- Performance Summary Cards -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">Database Response</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo $metrics['db_response_time']; ?> ms</h3>
                    </div>
                    <div class="text-primary" style="font-size: 2rem;">
                        <i class="bi bi-lightning-charge-fill"></i>
                    </div>
                </div>
                <span class="metric-badge <?php echo $metrics['db_response_time'] < 10 ? 'excellent' : ($metrics['db_response_time'] < 50 ? 'good' : 'warning'); ?>">
                    <?php echo $metrics['db_response_time'] < 10 ? 'Excellent' : ($metrics['db_response_time'] < 50 ? 'Good' : 'Needs Optimization'); ?>
                </span>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">Database Size</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo number_format($metrics['db_size']['size_mb'] ?? 0, 1); ?> MB</h3>
                    </div>
                    <div class="text-success" style="font-size: 2rem;">
                        <i class="bi bi-database-fill"></i>
                    </div>
                </div>
                <small class="text-muted">
                    Data: <?php echo number_format($metrics['db_size']['data_mb'] ?? 0, 1); ?> MB | 
                    Index: <?php echo number_format($metrics['db_size']['index_mb'] ?? 0, 1); ?> MB
                </small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">PHP Memory</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo number_format($metrics['php_memory_usage'], 1); ?> MB</h3>
                    </div>
                    <div class="text-info" style="font-size: 2rem;">
                        <i class="bi bi-memory"></i>
                    </div>
                </div>
                <small class="text-muted">
                    Peak: <?php echo number_format($metrics['php_memory_peak'], 1); ?> MB / 
                    Limit: <?php echo $metrics['php_memory_limit']; ?>
                </small>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div>
                        <h6 class="text-muted mb-0">Slow Queries</h6>
                        <h3 class="mb-0 fw-bold mt-1"><?php echo $metrics['slow_queries']; ?></h3>
                    </div>
                    <div class="text-warning" style="font-size: 2rem;">
                        <i class="bi bi-hourglass-split"></i>
                    </div>
                </div>
                <small class="text-muted">Last hour</small>
            </div>
        </div>
    </div>
</div>

<!-- Performance Charts -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-graph-up me-2"></i>Performance Trends (24 Hours)
                </h5>
            </div>
            <div class="card-body">
                <canvas id="performanceTrendChart" class="performance-chart"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- Database Tables Statistics -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-table me-2"></i>Database Tables (Top 20 by Size)
        </h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Table Name</th>
                        <th class="text-end">Rows</th>
                        <th class="text-end">Total Size</th>
                        <th class="text-end">Data Size</th>
                        <th class="text-end">Index Size</th>
                        <th class="text-end">Fragmentation</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($metrics['table_stats'] as $table): ?>
                    <tr class="table-stat-row">
                        <td class="fw-semibold"><?php echo htmlspecialchars($table['table_name']); ?></td>
                        <td class="text-end"><?php echo number_format($table['table_rows']); ?></td>
                        <td class="text-end"><?php echo number_format($table['size_mb'], 2); ?> MB</td>
                        <td class="text-end"><?php echo number_format($table['data_mb'], 2); ?> MB</td>
                        <td class="text-end"><?php echo number_format($table['index_mb'], 2); ?> MB</td>
                        <td class="text-end">
                            <?php if ($table['fragmentation_mb'] > 0): ?>
                                <span class="badge bg-warning"><?php echo number_format($table['fragmentation_mb'], 2); ?> MB</span>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-outline-primary" onclick="optimizeTable('<?php echo $table['table_name']; ?>')">
                                <i class="bi bi-gear"></i> Optimize
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Optimization Recommendations -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-lightbulb me-2"></i>Optimization Recommendations
        </h5>
    </div>
    <div class="card-body">
        <div class="list-group list-group-flush">
            <?php
            $recommendations = [];
            
            if ($metrics['db_response_time'] > 50) {
                $recommendations[] = [
                    'type' => 'warning',
                    'title' => 'Database Response Time High',
                    'message' => 'Database queries are taking longer than optimal. Consider adding indexes or optimizing queries.',
                    'action' => 'Review slow query log and add appropriate indexes'
                ];
            }
            
            foreach ($metrics['table_stats'] as $table) {
                if ($table['fragmentation_mb'] > 10) {
                    $recommendations[] = [
                        'type' => 'info',
                        'title' => 'Table Fragmentation Detected',
                        'message' => "Table '{$table['table_name']}' has " . number_format($table['fragmentation_mb'], 2) . " MB fragmentation.",
                        'action' => 'Run OPTIMIZE TABLE to reduce fragmentation'
                    ];
                    break; // Only show one fragmentation warning
                }
            }
            
            if (empty($recommendations)) {
                $recommendations[] = [
                    'type' => 'success',
                    'title' => 'All Systems Optimal',
                    'message' => 'No performance issues detected. System is running efficiently.',
                    'action' => 'Continue monitoring'
                ];
            }
            ?>
            
            <?php foreach ($recommendations as $rec): ?>
            <div class="list-group-item border-0 px-0">
                <div class="d-flex align-items-start">
                    <div class="me-3">
                        <?php if ($rec['type'] === 'success'): ?>
                            <i class="bi bi-check-circle-fill text-success fs-4"></i>
                        <?php elseif ($rec['type'] === 'warning'): ?>
                            <i class="bi bi-exclamation-triangle-fill text-warning fs-4"></i>
                        <?php else: ?>
                            <i class="bi bi-info-circle-fill text-info fs-4"></i>
                        <?php endif; ?>
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-1"><?php echo $rec['title']; ?></h6>
                        <p class="mb-1 text-muted"><?php echo $rec['message']; ?></p>
                        <small class="text-primary"><i class="bi bi-arrow-right"></i> <?php echo $rec['action']; ?></small>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
// Optimize Database
function optimizeDatabase() {
    Swal.fire({
        title: 'Optimize Database?',
        text: 'This will optimize all database tables. This may take a few minutes.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#059669',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, Optimize',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return $.post(APP_URL + '/admin/actions/optimize-database.php', {
                action: 'optimize_all'
            }).then(response => {
                if (!response.success) {
                    throw new Error(response.message || 'Optimization failed');
                }
                return response;
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Optimized!',
                text: result.value.message || 'Database has been optimized successfully.',
                icon: 'success',
                confirmButtonColor: '#059669'
            }).then(() => {
                location.reload();
            });
        }
    });
}

// Optimize Single Table
function optimizeTable(tableName) {
    Swal.fire({
        title: `Optimize ${tableName}?`,
        text: 'This will optimize the selected table.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#059669',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, Optimize',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return $.post(APP_URL + '/admin/actions/optimize-database.php', {
                action: 'optimize_table',
                table: tableName
            }).then(response => {
                if (!response.success) {
                    throw new Error(response.message || 'Optimization failed');
                }
                return response;
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error}`);
            });
        },
        allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Optimized!',
                text: `Table ${tableName} has been optimized.`,
                icon: 'success',
                confirmButtonColor: '#059669'
            }).then(() => {
                location.reload();
            });
        }
    });
}

// Performance Trend Chart
<?php if (!empty($metrics['historical_data'])): ?>
const performanceData = <?php echo json_encode($metrics['historical_data']); ?>;

// Group data by metric type
const cpuData = performanceData.filter(m => m.metric_type === 'cpu').map(m => ({
    x: new Date(m.recorded_at),
    y: parseFloat(m.metric_value)
}));

const memoryData = performanceData.filter(m => m.metric_type === 'memory').map(m => ({
    x: new Date(m.recorded_at),
    y: parseFloat(m.metric_value)
}));

const responseTimeData = performanceData.filter(m => m.metric_type === 'response_time').map(m => ({
    x: new Date(m.recorded_at),
    y: parseFloat(m.metric_value)
}));

const ctx = document.getElementById('performanceTrendChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [
            {
                label: 'CPU Usage (%)',
                data: cpuData,
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4,
                yAxisID: 'y'
            },
            {
                label: 'Memory Usage (%)',
                data: memoryData,
                borderColor: 'rgb(16, 185, 129)',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                tension: 0.4,
                yAxisID: 'y'
            },
            {
                label: 'Response Time (ms)',
                data: responseTimeData,
                borderColor: 'rgb(245, 158, 11)',
                backgroundColor: 'rgba(245, 158, 11, 0.1)',
                tension: 0.4,
                yAxisID: 'y1'
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
            mode: 'index',
            intersect: false
        },
        plugins: {
            legend: {
                display: true,
                position: 'top'
            }
        },
        scales: {
            x: {
                type: 'time',
                time: {
                    unit: 'hour'
                },
                title: {
                    display: true,
                    text: 'Time'
                }
            },
            y: {
                type: 'linear',
                display: true,
                position: 'left',
                title: {
                    display: true,
                    text: 'Percentage (%)'
                },
                max: 100
            },
            y1: {
                type: 'linear',
                display: true,
                position: 'right',
                title: {
                    display: true,
                    text: 'Response Time (ms)'
                },
                grid: {
                    drawOnChartArea: false
                }
            }
        }
    }
});
<?php endif; ?>
</script>

<?php renderAdminFooter(); ?>