<?php
/**
 * Performance Optimizer for AloneDeals.com
 * Optimizes Core Web Vitals and page speed for better SEO
 */

class PerformanceOptimizer {
    private $siteUrl = 'https://alonedeals.com';
    
    /**
     * Generate preconnect links for external resources
     */
    public function generatePreconnectLinks() {
        $domains = [
            'https://fonts.googleapis.com',
            'https://fonts.gstatic.com',
            'https://www.google-analytics.com',
            'https://www.googletagmanager.com'
        ];
        
        $html = '';
        foreach ($domains as $domain) {
            $html .= '<link rel="preconnect" href="' . $domain . '">' . "\n";
            $html .= '<link rel="dns-prefetch" href="' . $domain . '">' . "\n";
        }
        
        return $html;
    }
    
    /**
     * Generate critical CSS inline
     */
    public function generateCriticalCSS() {
        return '<style>
/* Critical CSS for Above-the-Fold Content */
body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;line-height:1.6;color:#333}
.container{max-width:1200px;margin:0 auto;padding:0 20px}
header{background:#fff;box-shadow:0 2px 4px rgba(0,0,0,.1);position:sticky;top:0;z-index:1000}
.header-content{display:flex;justify-content:space-between;align-items:center;padding:15px 0}
.logo{font-size:24px;font-weight:700;color:#6366f1;text-decoration:none}
nav a{margin:0 15px;text-decoration:none;color:#333;font-weight:500}
.hero{padding:60px 0;text-align:center;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:#fff}
.hero h1{font-size:48px;margin:0 0 20px;font-weight:800}
.btn{display:inline-block;padding:12px 30px;background:#6366f1;color:#fff;text-decoration:none;border-radius:6px;font-weight:600;transition:all .3s}
.btn:hover{background:#4f46e5;transform:translateY(-2px)}
@media(max-width:768px){.hero h1{font-size:32px}.header-content{flex-direction:column}}
</style>';
    }
    
    /**
     * Defer non-critical CSS
     */
    public function deferCSS($cssFiles) {
        $html = '';
        foreach ($cssFiles as $file) {
            $html .= '<link rel="preload" href="' . $file . '" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">' . "\n";
            $html .= '<noscript><link rel="stylesheet" href="' . $file . '"></noscript>' . "\n";
        }
        return $html;
    }
    
    /**
     * Defer JavaScript
     */
    public function deferJS($jsFiles) {
        $html = '';
        foreach ($jsFiles as $file) {
            $html .= '<script src="' . $file . '" defer></script>' . "\n";
        }
        return $html;
    }
    
    /**
     * Generate resource hints
     */
    public function generateResourceHints($resources) {
        $html = '';
        
        // Preload critical resources
        if (!empty($resources['preload'])) {
            foreach ($resources['preload'] as $resource) {
                $html .= '<link rel="preload" href="' . $resource['url'] . '" as="' . $resource['type'] . '"';
                if (!empty($resource['crossorigin'])) {
                    $html .= ' crossorigin';
                }
                $html .= '>' . "\n";
            }
        }
        
        // Prefetch next-page resources
        if (!empty($resources['prefetch'])) {
            foreach ($resources['prefetch'] as $url) {
                $html .= '<link rel="prefetch" href="' . $url . '">' . "\n";
            }
        }
        
        return $html;
    }
    
    /**
     * Minify HTML output
     */
    public function minifyHTML($html) {
        // Remove comments
        $html = preg_replace('/<!--(?!<!)[^\[>].*?-->/s', '', $html);
        
        // Remove whitespace
        $html = preg_replace('/\s+/', ' ', $html);
        
        // Remove whitespace around tags
        $html = preg_replace('/>\s+</', '><', $html);
        
        return trim($html);
    }
    
    /**
     * Generate service worker for caching
     */
    public function generateServiceWorker() {
        return "// Service Worker for AloneDeals.com
const CACHE_NAME = 'alonedeals-v1';
const urlsToCache = [
  '/',
  '/assets/css/main.css',
  '/assets/js/main.js',
  '/images/logo.png'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});";
    }
    
    /**
     * Generate Web App Manifest
     */
    public function generateManifest() {
        return json_encode([
            "name" => "AloneDeals - Best Coupons & Deals",
            "short_name" => "AloneDeals",
            "description" => "Find the best coupons, deals, and discounts from top stores",
            "start_url" => "/",
            "display" => "standalone",
            "background_color" => "#ffffff",
            "theme_color" => "#6366f1",
            "icons" => [
                [
                    "src" => "/images/icon-192.png",
                    "sizes" => "192x192",
                    "type" => "image/png"
                ],
                [
                    "src" => "/images/icon-512.png",
                    "sizes" => "512x512",
                    "type" => "image/png"
                ]
            ]
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Add security headers
     */
    public function getSecurityHeaders() {
        return [
            'X-Content-Type-Options' => 'nosniff',
            'X-Frame-Options' => 'SAMEORIGIN',
            'X-XSS-Protection' => '1; mode=block',
            'Referrer-Policy' => 'strict-origin-when-cross-origin',
            'Permissions-Policy' => 'geolocation=(), microphone=(), camera=()',
            'Strict-Transport-Security' => 'max-age=31536000; includeSubDomains'
        ];
    }
    
    /**
     * Generate performance monitoring script
     */
    public function generatePerformanceMonitoring() {
        return "<script>
// Core Web Vitals Monitoring
if ('PerformanceObserver' in window) {
  // Largest Contentful Paint (LCP)
  new PerformanceObserver((list) => {
    const entries = list.getEntries();
    const lastEntry = entries[entries.length - 1];
    console.log('LCP:', lastEntry.renderTime || lastEntry.loadTime);
  }).observe({entryTypes: ['largest-contentful-paint']});
  
  // First Input Delay (FID)
  new PerformanceObserver((list) => {
    list.getEntries().forEach((entry) => {
      console.log('FID:', entry.processingStart - entry.startTime);
    });
  }).observe({entryTypes: ['first-input']});
  
  // Cumulative Layout Shift (CLS)
  let clsScore = 0;
  new PerformanceObserver((list) => {
    list.getEntries().forEach((entry) => {
      if (!entry.hadRecentInput) {
        clsScore += entry.value;
        console.log('CLS:', clsScore);
      }
    });
  }).observe({entryTypes: ['layout-shift']});
}
</script>";
    }
    
    /**
     * Optimize database queries
     */
    public function optimizeQueries($db) {
        $optimizations = [];
        
        // Add indexes for common queries
        $indexes = [
            "CREATE INDEX IF NOT EXISTS idx_post_status ON blog_posts(post_status)",
            "CREATE INDEX IF NOT EXISTS idx_post_slug ON blog_posts(post_slug)",
            "CREATE INDEX IF NOT EXISTS idx_coupon_status ON coupons(coupon_status)",
            "CREATE INDEX IF NOT EXISTS idx_coupon_slug ON coupons(coupon_slug)",
            "CREATE INDEX IF NOT EXISTS idx_store_status ON stores(store_status)",
            "CREATE INDEX IF NOT EXISTS idx_store_slug ON stores(store_slug)",
            "CREATE INDEX IF NOT EXISTS idx_category_status ON categories(category_status)"
        ];
        
        foreach ($indexes as $sql) {
            try {
                $db->exec($sql);
                $optimizations[] = "Added index: " . $sql;
            } catch (Exception $e) {
                $optimizations[] = "Index exists or error: " . $e->getMessage();
            }
        }
        
        return $optimizations;
    }
    
    /**
     * Generate .htaccess rules for performance
     */
    public function generateHtaccessRules() {
        return "# Performance Optimization for AloneDeals.com

# Enable GZIP Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Browser Caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg \"access plus 1 year\"
    ExpiresByType image/jpeg \"access plus 1 year\"
    ExpiresByType image/gif \"access plus 1 year\"
    ExpiresByType image/png \"access plus 1 year\"
    ExpiresByType image/webp \"access plus 1 year\"
    ExpiresByType text/css \"access plus 1 month\"
    ExpiresByType application/javascript \"access plus 1 month\"
    ExpiresByType application/pdf \"access plus 1 month\"
    ExpiresByType image/x-icon \"access plus 1 year\"
</IfModule>

# Security Headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options \"nosniff\"
    Header set X-Frame-Options \"SAMEORIGIN\"
    Header set X-XSS-Protection \"1; mode=block\"
    Header set Referrer-Policy \"strict-origin-when-cross-origin\"
    Header set Permissions-Policy \"geolocation=(), microphone=(), camera=()\"
</IfModule>

# Enable HTTP/2 Server Push
<IfModule mod_http2.c>
    H2Push on
    H2PushPriority * after
    H2PushPriority text/css before
    H2PushPriority application/javascript after
</IfModule>";
    }
}
?>
