<?php
if (!defined('ABSPATH')) exit;

use Mamba\Support\SavingsTracker;

// Get all savings data
$savingsSummary = SavingsTracker::getDashboardSummary();
$imageSavings = $savingsSummary['image'];
$minifySavings = $savingsSummary['minify'];
$dbSavings = $savingsSummary['db'];

// Get cache stats for requests saved calculation
$cacheStats = get_option('mamba_cache_stats', ['cache_hits' => 0, 'cache_misses' => 0]);
$cacheHits = (int)($cacheStats['cache_hits'] ?? 0);
$cacheMisses = (int)($cacheStats['cache_misses'] ?? 0);

// Calculate time saved from cache hits
$genStats = $cacheStats['gen'] ?? ['total_ms' => 0, 'misses' => 0];
$avgGenMs = ($genStats['misses'] ?? 0) > 0 ? round(($genStats['total_ms'] ?? 0) / $genStats['misses']) : 200;
$timeSavedMs = $cacheHits * $avgGenMs;

// Format time saved
$formatTime = function($ms) {
    if ($ms <= 0) return '0s';
    $sec = (int)floor($ms / 1000);
    if ($sec < 60) return $sec . 's';
    $min = (int)floor($sec / 60);
    $sec = $sec % 60;
    if ($min < 60) return sprintf('%dm %ds', $min, $sec);
    $hrs = (int)floor($min / 60);
    $min = $min % 60;
    return sprintf('%dh %dm', $hrs, $min);
};

$timeSavedFormatted = $formatTime($timeSavedMs);

// Check if there's any data to show
$hasAnySavings = ($savingsSummary['total_bytes_saved'] > 0 || 
                  $savingsSummary['requests_saved'] > 0 || 
                  $dbSavings['rows_cleaned'] > 0 ||
                  $timeSavedMs > 0);
?>

<div class="mamba-admin-wrap">
    <!-- Savings Overview -->
    <div class="mamba-form-section">
        <div class="mamba-section-header">
            <h4 class="mamba-section-title">
                <span class="dashicons dashicons-chart-bar"></span>
                <?php echo esc_html(__('Monthly Savings & Impact', 'mamba-cache-for-woocommerce')); ?>
                <small style="font-weight: normal; opacity: 0.7; margin-left: 8px;"><?php echo esc_html($savingsSummary['month']); ?></small>
            </h4>
        </div>
        
        <div class="mamba-performance-overview">
            <div class="mamba-performance-card">
                <div class="mamba-performance-icon">
                    <span class="dashicons dashicons-awards"></span>
                </div>
                <div class="mamba-performance-content">
                    <h3 class="mamba-performance-title"><?php echo esc_html(__('Performance Impact', 'mamba-cache-for-woocommerce')); ?></h3>
                    <p class="mamba-performance-description">
                        <?php echo esc_html(__('Track the real impact of Mamba\'s optimizations on your WooCommerce store. All metrics reset monthly to give you fresh, relevant insights.', 'mamba-cache-for-woocommerce')); ?>
                    </p>
                    <div style="margin-top: 12px; padding: 12px; background: var(--mamba-bg); border-radius: 6px; font-size: 13px;">
                        <strong style="display: block; margin-bottom: 8px; color: var(--mamba-text);"><?php echo esc_html(__('What\'s tracked:', 'mamba-cache-for-woocommerce')); ?></strong>
                        <ul style="margin: 0; padding-left: 20px; color: var(--mamba-text-muted); line-height: 1.8;">
                            <li><strong><?php echo esc_html(__('Cache Performance', 'mamba-cache-for-woocommerce')); ?></strong> — <?php echo esc_html(__('Appears when Page Cache is enabled. Shows cache hits, server time saved, and average generation time.', 'mamba-cache-for-woocommerce')); ?></li>
                            <li><strong><?php echo esc_html(__('Image Optimization', 'mamba-cache-for-woocommerce')); ?></strong> — <?php echo esc_html(__('Appears after WebP/AVIF conversions. Shows images optimized and data saved.', 'mamba-cache-for-woocommerce')); ?></li>
                            <li><strong><?php echo esc_html(__('HTML Minification', 'mamba-cache-for-woocommerce')); ?></strong> — <?php echo esc_html(__('Appears when HTML Minify is enabled. Shows pages minified and payload reduction.', 'mamba-cache-for-woocommerce')); ?></li>
                            <li><strong><?php echo esc_html(__('Database Cleanup', 'mamba-cache-for-woocommerce')); ?></strong> — <?php echo esc_html(__('Appears after scheduled DB tasks run. Shows rows cleaned and tasks executed.', 'mamba-cache-for-woocommerce')); ?></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if ($hasAnySavings): ?>
    
    <!-- Primary Metrics -->
    <div class="mamba-form-section">
        <div class="mamba-section-header">
            <h4 class="mamba-section-title">
                <span class="dashicons dashicons-performance"></span>
                <?php echo esc_html(__('Cache Performance', 'mamba-cache-for-woocommerce')); ?>
            </h4>
        </div>
        
        <div class="mamba-metrics-dashboard">
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-yes-alt"></div>
                <div class="metric-title"><?php echo esc_html(__('Cache Hits', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($cacheHits)); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('PHP requests avoided', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-clock"></div>
                <div class="metric-title"><?php echo esc_html(__('Server Time Saved', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html($timeSavedFormatted); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-performance"></span>
                    <?php echo esc_html(__('From cache hits', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-dashboard"></div>
                <div class="metric-title"><?php echo esc_html(__('Avg. Generation Time', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html($avgGenMs); ?>ms</div>
                <div class="metric-trend neutral">
                    <span class="dashicons dashicons-clock"></span>
                    <?php echo esc_html(__('Per uncached request', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <?php if ($savingsSummary['total_bytes_saved'] > 0): ?>
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-download"></div>
                <div class="metric-title"><?php echo esc_html(__('Total Data Saved', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html($savingsSummary['total_bytes_saved_formatted']); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('From all optimizations', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($imageSavings['images_optimized'] > 0): ?>
    <!-- Image Optimization Savings -->
    <div class="mamba-form-section">
        <div class="mamba-section-header">
            <h4 class="mamba-section-title">
                <span class="dashicons dashicons-format-image"></span>
                <?php echo esc_html(__('Image Optimization', 'mamba-cache-for-woocommerce')); ?>
            </h4>
        </div>
        
        <div class="mamba-metrics-dashboard">
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-images-alt2"></div>
                <div class="metric-title"><?php echo esc_html(__('Images Optimized', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($imageSavings['images_optimized'])); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('WebP/AVIF conversions', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-download"></div>
                <div class="metric-title"><?php echo esc_html(__('Image Data Saved', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html($imageSavings['bytes_saved_formatted']); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('Smaller file sizes', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <?php if ($imageSavings['webp_count'] > 0): ?>
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-format-image"></div>
                <div class="metric-title"><?php echo esc_html(__('WebP Conversions', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($imageSavings['webp_count'])); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('Next-gen format', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($imageSavings['avif_count'] > 0): ?>
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-format-image"></div>
                <div class="metric-title"><?php echo esc_html(__('AVIF Conversions', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($imageSavings['avif_count'])); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('Best compression', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($minifySavings['pages_minified'] > 0): ?>
    <!-- HTML Minification Savings -->
    <div class="mamba-form-section">
        <div class="mamba-section-header">
            <h4 class="mamba-section-title">
                <span class="dashicons dashicons-editor-code"></span>
                <?php echo esc_html(__('HTML Minification', 'mamba-cache-for-woocommerce')); ?>
            </h4>
        </div>
        
        <div class="mamba-metrics-dashboard">
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-media-code"></div>
                <div class="metric-title"><?php echo esc_html(__('Pages Minified', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($minifySavings['pages_minified'])); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('HTML optimized', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-download"></div>
                <div class="metric-title"><?php echo esc_html(__('Minification Savings', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html($minifySavings['bytes_saved_formatted']); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('Reduced payload', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($dbSavings['rows_cleaned'] > 0): ?>
    <!-- Database Cleanup Savings -->
    <div class="mamba-form-section">
        <div class="mamba-section-header">
            <h4 class="mamba-section-title">
                <span class="dashicons dashicons-database-remove"></span>
                <?php echo esc_html(__('Database Cleanup', 'mamba-cache-for-woocommerce')); ?>
            </h4>
        </div>
        
        <div class="mamba-metrics-dashboard">
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-trash"></div>
                <div class="metric-title"><?php echo esc_html(__('Rows Cleaned', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($dbSavings['rows_cleaned'])); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('Database optimized', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
            
            <div class="mamba-metric-card">
                <div class="metric-icon dashicons dashicons-update"></div>
                <div class="metric-title"><?php echo esc_html(__('Cleanup Tasks Run', 'mamba-cache-for-woocommerce')); ?></div>
                <div class="metric-value"><?php echo esc_html(number_format_i18n($dbSavings['tasks_run'])); ?></div>
                <div class="metric-trend positive">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <?php echo esc_html(__('Automated cleanup', 'mamba-cache-for-woocommerce')); ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php else: ?>
    
    <!-- No Data Yet -->
    <div class="mamba-form-section">
        <div class="mamba-empty-state" style="text-align: center; padding: 40px 20px;">
            <span class="dashicons dashicons-chart-line" style="font-size: 48px; width: 48px; height: 48px; color: var(--mamba-text-muted); margin-bottom: 16px;"></span>
            <h3 style="margin: 0 0 8px 0; color: var(--mamba-text);"><?php echo esc_html(__('No Savings Data Yet', 'mamba-cache-for-woocommerce')); ?></h3>
            <p style="margin: 0; color: var(--mamba-text-muted); max-width: 400px; margin: 0 auto;">
                <?php echo esc_html(__('As Mamba optimizes your store, you\'ll see detailed savings metrics here. Enable caching, image optimization, or HTML minification to start tracking your performance gains.', 'mamba-cache-for-woocommerce')); ?>
            </p>
        </div>
    </div>
    
    <?php endif; ?>

    <!-- Info Note -->
    <div class="mamba-form-section">
        <div class="mamba-info-box" style="background: var(--mamba-bg-alt); border-radius: 8px; padding: 16px; display: flex; align-items: flex-start; gap: 12px;">
            <span class="dashicons dashicons-info" style="color: var(--mamba-primary); flex-shrink: 0; margin-top: 2px;"></span>
            <div>
                <strong style="color: var(--mamba-text);"><?php echo esc_html(__('How savings are calculated', 'mamba-cache-for-woocommerce')); ?></strong>
                <p style="margin: 8px 0 0 0; color: var(--mamba-text-muted); font-size: 13px;">
                    <?php echo esc_html(__('Cache hits represent PHP requests avoided. Server time saved is calculated from cache hits multiplied by average page generation time. Image and minification savings are measured by comparing original vs optimized file sizes. All metrics reset at the start of each month.', 'mamba-cache-for-woocommerce')); ?>
                </p>
            </div>
        </div>
    </div>
</div>
