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

// Check if caching is enabled
$cacheEnabled = (bool)get_option('mamba_enable_page_cache', 0);

$stats = get_option('mamba_cache_stats', [
    'cache_hits' => 0,
    'cache_misses' => 0,
    'cache_size' => 0,
    'last_cleared' => 0,
    'by_type' => [
        'product' => ['hits' => 0, 'misses' => 0],
        'category' => ['hits' => 0, 'misses' => 0],
        'shop' => ['hits' => 0, 'misses' => 0],
        'store_api' => ['hits' => 0, 'misses' => 0],
        'other' => ['hits' => 0, 'misses' => 0],
        'homepage' => ['hits' => 0, 'misses' => 0]
    ]
]);

$hits = (int)($stats['cache_hits'] ?? 0);
$miss = (int)($stats['cache_misses'] ?? 0);
$byType = $stats['by_type'] ?? [];
$rate = $cacheEnabled ? (($hits + $miss) > 0 ? round(($hits / ($hits + $miss)) * 100) : 0) : 0;

// Calculate score excluding Store API metrics
$totalHits = 0;
$totalMisses = 0;

// Sum up all hits/misses except Store API
foreach ($byType as $type => $metrics) {
    if ($type !== 'store_api') {
        $totalHits += (int)($metrics['hits'] ?? 0);
        $totalMisses += (int)($metrics['misses'] ?? 0);
    }
}

// Calculate rate based on non-Store API metrics only
$adjustedRate = ($totalHits + $totalMisses) > 0 ? 
    round(($totalHits / ($totalHits + $totalMisses)) * 100) : 
    0;

// Enhanced efficiency score with performance benchmarks (excluding Store API)
$score = $cacheEnabled ? $adjustedRate : 0;
$scoreClass = $cacheEnabled ? 
    ($score >= 90 ? 'excellent' : ($score >= 75 ? 'good' : ($score >= 50 ? 'average' : 'poor'))) : 
    'neutral';
$scoreStatus = $cacheEnabled ? 
    ($score >= 90 ? 'Excellent' : ($score >= 75 ? 'Good' : ($score >= 50 ? 'Average' : 'Needs Work'))) : 
    'Disabled';

// Performance benchmarks for context
$performanceBenchmark = '';
if ($cacheEnabled) {
    if ($score >= 90) {
        $performanceBenchmark = 'Top 10% of sites';
    } elseif ($score >= 75) {
        $performanceBenchmark = 'Above average';
    } elseif ($score >= 50) {
        $performanceBenchmark = 'Industry average';
    } else {
        $performanceBenchmark = 'Below average';
    }
} else {
    $performanceBenchmark = 'Cache disabled';
}

// warmup stats
$warm = get_option('mamba_warmup_stats', ['last_run'=>0,'total_urls'=>0,'success'=>0]);
$byType = $stats['by_type'] ?? [];
$gen = $stats['gen'] ?? ['total_ms'=>0,'misses'=>0];
$avgGenMs = 0;

// Calculate average generation time with outlier handling
$avgGenMs = 0;
if (($gen['misses'] ?? 0) > 0) {
    $totalMs = (int)($gen['total_ms'] ?? 0);
    $misses = (int)($gen['misses'] ?? 0);
    
    // Calculate raw average
    $rawAvg = $totalMs / $misses;
    
    // Apply outlier handling (cap at 2000ms to prevent extreme values from skewing metrics)
    $avgGenMs = min(2000, round($rawAvg));
}
// If no misses recorded, avgGenMs remains 0 - we can handle this in display logic

$timeSavedMs = 0;
$timeSavedToday = 0; // Will calculate from daily stats

// Only calculate time saved if caching is enabled
if ($cacheEnabled) {
    // Calculate time saved from page cache hits
    $pageHits = ($byType['product']['hits'] ?? 0) + ($byType['category']['hits'] ?? 0) + ($byType['shop']['hits'] ?? 0) + ($byType['homepage']['hits'] ?? 0) + ($byType['other']['hits'] ?? 0);
    
    // Calculate time saved from page cache hits
    $timeSavedMs += $pageHits * $avgGenMs;
    
    // Calculate time saved from Store API hits (only if there's actual usage)
    $storeApiHits = $byType['store_api']['hits'] ?? 0;
    $storeApiMisses = $byType['store_api']['misses'] ?? 0;
    $storeApiTotal = $storeApiHits + $storeApiMisses;
    $storeApiGen = $stats['gen_store_api'] ?? ['total_ms' => 0, 'misses' => 0];
    $avgStoreApiGenMs = ($storeApiGen['misses'] ?? 0) > 0 ? round(($storeApiGen['total_ms'] ?? 0) / $storeApiGen['misses']) : 0; // Only use actual measured data
    
    // Only include Store API time savings if there's actual usage and measured data
    if ($storeApiTotal > 0 && $avgStoreApiGenMs > 0) {
        $timeSavedMs += $storeApiHits * $avgStoreApiGenMs;
    }
}

// Daily impact and performance metrics
$daily = get_option('mamba_daily_stats', []);
$timeSavedToday = 0;
$todayVisitors = 0;

if (!empty($daily)) {
    $today = wp_date('Y-m-d');
    $todayStats = null;
    foreach ($daily as $day) {
        if ($day['date'] === $today) {
            $todayStats = $day;
            break;
        }
    }
    if ($todayStats) {
        $todayHits = (int)($todayStats['hits'] ?? 0);
        $todayMisses = (int)($todayStats['misses'] ?? 0);
        $todayVisitors = $todayHits + $todayMisses;
        
        // Calculate today's time saved
        $todayPageHits = ($todayStats['by_type']['product']['hits'] ?? 0) + 
                        ($todayStats['by_type']['category']['hits'] ?? 0) + 
                        ($todayStats['by_type']['shop']['hits'] ?? 0) + 
                        ($todayStats['by_type']['homepage']['hits'] ?? 0);
        $todayStoreApiHits = $todayStats['by_type']['store_api']['hits'] ?? 0;
        $todayStoreApiMisses = $todayStats['by_type']['store_api']['misses'] ?? 0;
        $todayStoreApiTotal = $todayStoreApiHits + $todayStoreApiMisses;
        
        $timeSavedToday = 0;
        if ($cacheEnabled) {
            if ($avgGenMs > 0) {
                $timeSavedToday += $todayPageHits * $avgGenMs;
            }
            if ($todayStoreApiTotal > 0 && $avgStoreApiGenMs > 0) {
                $timeSavedToday += $todayStoreApiHits * $avgStoreApiGenMs;
            }
        }
        

    }
}

// Humanize time functions
$humanizeTime = 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);
};

$timeSavedStr = $humanizeTime($timeSavedMs);

// Average Page Load Time (only actual measured data)
$measuredMisses = (int)($gen['misses'] ?? 0); // measured generation events only
$avgPageLoadTime = 0;
if ($cacheEnabled && $measuredMisses > 0 && $avgGenMs > 0) {
    $avgPageLoadTime = $avgGenMs; // Use actual measured generation time
}

// Object cache improvement is already reflected in actual generation times

$hasObjectCache = \Mamba\Support\ObjectCache::hasPersistentCache();

// Pperformance benchmarks
$loadTimeStatus = 'No Data';
$loadTimeClass = 'neutral';
if ($cacheEnabled) {
    if ($avgPageLoadTime > 0) {
        if ($avgPageLoadTime < 200) {
            $loadTimeStatus = 'Excellent';
            $loadTimeClass = 'positive';
        } elseif ($avgPageLoadTime < 500) {
            $loadTimeStatus = 'Good';
            $loadTimeClass = 'neutral';
        } elseif ($avgPageLoadTime < 1000) {
            $loadTimeStatus = 'Average';
            $loadTimeClass = 'neutral';
        } else {
            $loadTimeStatus = 'Needs Improvement';
            $loadTimeClass = 'negative';
        }
    } else {
        $loadTimeStatus = 'No Data Yet';
        $loadTimeClass = 'neutral';
    }
} else {
    $loadTimeStatus = 'Disabled';
    $loadTimeClass = 'neutral';
}

// Cache counts using actual file counting instead of estimation
$cacheCounts = ['products'=>0,'categories'=>0,'shop'=>0,'homepage'=>0,'other'=>0];
$cacheSizeBytes = $cacheEnabled ? (int)($stats['cache_size'] ?? 0) : 0;
$cacheSizeMB = $cacheEnabled ? ($cacheSizeBytes > 0 ? round($cacheSizeBytes / (1024 * 1024), 1) : 0) : 0;

// Only count cache files if caching is enabled
if ($cacheEnabled && defined('WP_CONTENT_DIR')) {
    $cacheDir = WP_CONTENT_DIR . '/cache/mamba';
    if (is_dir($cacheDir)) {
        $cacheCounts = countActualCacheFiles($cacheDir);
    }
}

// Cache Coverage (real system health metric)
$cacheCoverage = $cacheEnabled ? calculateAccurateCacheCoverage($cacheCounts) : 0;
$coverageStatus = $cacheEnabled ? ($cacheCoverage >= 90 ? 'Complete' : ($cacheCoverage >= 70 ? 'Good' : ($cacheCoverage >= 50 ? 'Partial' : 'Limited'))) : 'Disabled';
$coverageClass = $cacheEnabled ? ($cacheCoverage >= 90 ? 'positive' : ($cacheCoverage >= 70 ? 'neutral' : 'negative')) : 'neutral';


?>
  <div class="mamba-admin-wrap">
    
    <div class="mamba-metrics-dashboard">
    <div class="mamba-metric-card efficiency-score">
      <span class="score-badge <?php echo esc_attr($scoreClass); ?>"><?php echo esc_html($score); ?></span>
      <div class="metric-title"><?php echo esc_html( __('Cache Efficiency', 'mamba-cache-for-woocommerce') ); ?></div>
      <div class="metric-value"><?php echo esc_html($scoreStatus); ?></div>
      <div class="metric-trend <?php echo esc_attr($scoreClass); ?>">
        <span class="dashicons dashicons-chart-line"></span>
        <?php echo esc_html($performanceBenchmark); ?>
      </div>
      <div class="metric-note">
        <small><?php echo esc_html( __('Stats update every minute', 'mamba-cache-for-woocommerce') ); ?></small>
        <?php if ($cacheEnabled): ?>
        <br><small><?php // translators: %s is the cache backend type
echo esc_html(sprintf(__('Cache backend: %s', 'mamba-cache-for-woocommerce'), $hasObjectCache ? \Mamba\Support\ObjectCache::getCacheType() : 'File Cache')); ?></small>
        <?php endif; ?>
      </div>
    </div>



    <div class="mamba-metric-card">
      <div class="metric-icon dashicons dashicons-performance"></div>
      <div class="metric-title"><?php echo esc_html( __('Page Load Time', 'mamba-cache-for-woocommerce') ); ?></div>
      <div class="metric-value">
        <?php if ($avgPageLoadTime > 0): ?>
            <?php echo esc_html($avgPageLoadTime.'ms'); ?>
        <?php else: ?>
            <?php echo esc_html( __('No data yet', 'mamba-cache-for-woocommerce') ); ?>
        <?php endif; ?>
      </div>
      <div class="metric-trend <?php echo esc_attr($loadTimeClass); ?>">
        <span class="dashicons dashicons-clock"></span>
        <?php echo esc_html($loadTimeStatus); ?>
      </div>
      <?php if ($cacheEnabled && $hasObjectCache): ?>
      <div class="metric-note">
        <small><?php echo esc_html( __('Object cache active', 'mamba-cache-for-woocommerce') ); ?></small>
      </div>
      <?php endif; ?>
      <?php if ($cacheEnabled && $avgPageLoadTime > 0): ?>
      <div class="metric-note">
        <small><?php // translators: %d is the number of measurements
echo esc_html(sprintf(__('Based on %d measurements', 'mamba-cache-for-woocommerce'), $measuredMisses)); ?></small>
      </div>
      <?php endif; ?>
    </div>

    <div class="mamba-metric-card">
      <div class="metric-icon dashicons dashicons-chart-area"></div>
      <div class="metric-title"><?php echo esc_html( __('Cache Coverage', 'mamba-cache-for-woocommerce') ); ?></div>
      <div class="metric-value"><?php echo esc_html($cacheCoverage.'%'); ?></div>
      <div class="metric-trend <?php echo esc_attr($coverageClass); ?>">
        <span class="dashicons dashicons-admin-site"></span>
        <?php echo esc_html($coverageStatus); ?>
      </div>
    </div>

    <div class="mamba-metric-card">
      <div class="metric-icon dashicons dashicons-products"></div>
      <div class="metric-title"><?php echo esc_html( __('Cached Products', 'mamba-cache-for-woocommerce') ); ?></div>
      <div class="metric-value"><?php echo esc_html(number_format_i18n($cacheCounts['products'])); ?></div>
      <div class="metric-note">
        <small><?php echo esc_html( __('Includes desktop, mobile & tablet variants', 'mamba-cache-for-woocommerce') ); ?></small>
      </div>
    </div>

    <div class="mamba-metric-card">
      <div class="metric-icon dashicons dashicons-category"></div>
      <div class="metric-title"><?php echo esc_html( __('Cached Categories', 'mamba-cache-for-woocommerce') ); ?></div>
      <div class="metric-value"><?php echo esc_html(number_format_i18n($cacheCounts['categories'])); ?></div>
      <div class="metric-note">
        <small><?php echo esc_html( __('Includes desktop, mobile & tablet variants', 'mamba-cache-for-woocommerce') ); ?></small>
      </div>
    </div>

    <div class="mamba-metric-card">
      <div class="metric-icon dashicons dashicons-database"></div>
      <div class="metric-title"><?php echo esc_html( __('Cache Size', 'mamba-cache-for-woocommerce') ); ?></div>
      <div class="metric-value"><?php echo esc_html($cacheSizeMB.' MB'); ?></div>
      <div class="metric-trend neutral">
        <span class="dashicons dashicons-admin-site"></span>
        <?php // translators: %d is the number of cached files
echo esc_html(sprintf(__('%d files cached','mamba-cache-for-woocommerce'), array_sum($cacheCounts))); ?>
      </div>
    </div>

    <?php
      $types = [
        'product' => ['label' => 'Products', 'icon' => 'dashicons-products'],
        'category' => ['label' => 'Categories', 'icon' => 'dashicons-category'],
        'shop' => ['label' => 'Shop', 'icon' => 'dashicons-store'],
        'store_api' => ['label' => 'Store API', 'icon' => 'dashicons-rest-api']
      ];
      foreach ($types as $k => $type):
        $h = (int)($byType[$k]['hits'] ?? 0);
        $m = (int)($byType[$k]['misses'] ?? 0);
        $total = $h + $m;
        
        // Special handling for Store API - show meaningful status even with no usage
        if ($k === 'store_api' && $total === 0) {
            $r = 0;
            $statusClass = 'neutral';
            $displayText = __('No usage yet', 'mamba-cache-for-woocommerce');
        } else {
            $r = $total > 0 ? round($h * 100 / $total) : 0;
            $statusClass = $r >= 80 ? 'positive' : ($r >= 50 ? 'neutral' : 'negative');
            $displayText = sprintf(__('%d hits, %d misses','mamba-cache-for-woocommerce'), $h, $m);
        }
    ?>
    <div class="mamba-metric-card">
      <div class="metric-icon <?php echo esc_attr($type['icon']); ?>"></div>
      <div class="metric-title"><?php echo esc_html($type['label'] . ' ' . __('Performance','mamba-cache-for-woocommerce')); ?></div>
      <div class="metric-value"><?php echo esc_html($r.'%'); ?></div>
      <div class="metric-trend <?php echo esc_attr($statusClass); ?>">
        <span class="dashicons dashicons-visibility"></span>
        <?php // translators: %d is the number of hits, %d is the number of misses
echo esc_html(sprintf(__('%d hits, %d misses','mamba-cache-for-woocommerce'), $h, $m)); ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

</div>

<?php
/**
 * Count actual cache files by type
 */
function countActualCacheFiles($cacheDir) {
    $counts = ['products' => 0, 'categories' => 0, 'shop' => 0, 'homepage' => 0, 'other' => 0];
    
    if (!is_dir($cacheDir)) {
        return $counts;
    }
    
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($cacheDir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        
        foreach ($iterator as $file) {
            if (!$file->isFile() || $file->getExtension() !== 'html') continue;
            $htmlPath = $file->getPathname();
            $metaPath = preg_replace('/\.html$/', '.meta.json', $htmlPath);

            $classified = false;
            if ($metaPath && file_exists($metaPath)) {
                $meta = json_decode(@file_get_contents($metaPath), true);
                if (is_array($meta)) {
                    $tags = isset($meta['tags']) && is_array($meta['tags']) ? $meta['tags'] : [];
                    // Prefer tag-based classification when available
                    if (!empty($tags)) {
                        // Product wins over category, then shop, then home
                        $hasProduct = false; $hasCategory = false; $hasShop = false; $hasHome = false;
                        foreach ($tags as $t) {
                            if (!$hasProduct && strpos($t, 'product_') === 0) { $hasProduct = true; }
                            elseif (!$hasCategory && strpos($t, 'category_') === 0) { $hasCategory = true; }
                            elseif (!$hasShop && $t === 'shop') { $hasShop = true; }
                            elseif (!$hasHome && $t === 'home') { $hasHome = true; }
                        }
                        if ($hasProduct) { $counts['products']++; $classified = true; }
                        elseif ($hasCategory) { $counts['categories']++; $classified = true; }
                        elseif ($hasShop) { $counts['shop']++; $classified = true; }
                        elseif ($hasHome) { $counts['homepage']++; $classified = true; }
                    }
                }
            }

            if ($classified) continue;

            // Fallback to path-based heuristic when meta missing
            $relativePath = str_replace($cacheDir . '/', '', $htmlPath);
            $pathParts = explode('/', $relativePath);
            if (empty($pathParts)) { $counts['other']++; continue; }
            if (count($pathParts) > 1) {
                $urlPath = $pathParts[1];
                if (strpos($urlPath, 'product') !== false && strpos($urlPath, 'product-category') === false) {
                    $counts['products']++;
                } elseif (strpos($urlPath, 'product-category') !== false) {
                    $counts['categories']++;
                } elseif (strpos($urlPath, 'shop') !== false) {
                    $counts['shop']++;
                } elseif ($urlPath === '' || $urlPath === 'index') {
                    $counts['homepage']++;
                } else {
                    $counts['other']++;
                }
            } else {
                $counts['homepage']++;
            }
        }
    } catch (Exception $e) {
        // Fallback to empty counts if scanning fails
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mamba: Cache file counting failed: ' . $e->getMessage());
        }
    }
    
    return $counts;
}

/**
 * Calculate accurate cache coverage based on actual cached files vs expected cacheable pages
 */
function calculateAccurateCacheCoverage($cacheCounts) {
    // Count total cached files
    $totalCachedFiles = array_sum($cacheCounts);
    
    if ($totalCachedFiles === 0) {
        return 0;
    }
    
    // Calculate expected cacheable pages
    $expectedPages = 0;
    
    // Products
    if (function_exists('wc_get_products')) {
        $productsQuery = wc_get_products(['limit' => 1, 'status' => 'publish', 'paginate' => true]);
        $expectedPages += $productsQuery->total ?? 0;
    }
    
    // Categories
    if (function_exists('get_terms')) {
        $totalCategories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => true, 'fields' => 'count']);
        $expectedPages += is_numeric($totalCategories) ? $totalCategories : 0;
    }
    
    // Product tags
    if (function_exists('get_terms')) {
        $totalTags = get_terms(['taxonomy' => 'product_tag', 'hide_empty' => true, 'fields' => 'count']);
        $expectedPages += is_numeric($totalTags) ? $totalTags : 0;
    }
    
    // Core pages
    $expectedPages += 1; // Shop page
    $expectedPages += 1; // Homepage
    
    // If we can't determine expected pages, use a reasonable estimate
    if ($expectedPages === 0) {
        $expectedPages = 10; // Default minimum
    }
    
    // Calculate coverage based on actual cached files vs expected pages
    $coverage = round(($totalCachedFiles / $expectedPages) * 100);
    // Cap at 100% to avoid misleading metrics
    return min(100, $coverage);
}
?>


