<?php
/**
 * Image SEO Optimizer for AloneDeals.com
 * Automatically optimizes images for better SEO and performance
 */

class ImageSEOOptimizer {
    private $siteUrl = 'https://alonedeals.com';
    private $db;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    /**
     * Generate SEO-friendly alt text for images
     */
    public function generateAltText($imageName, $context = []) {
        // Remove file extension and clean filename
        $alt = pathinfo($imageName, PATHINFO_FILENAME);
        $alt = str_replace(['-', '_'], ' ', $alt);
        $alt = ucwords($alt);
        
        // Add context if available
        if (!empty($context['title'])) {
            $alt = $context['title'] . ' - ' . $alt;
        }
        
        if (!empty($context['store'])) {
            $alt .= ' at ' . $context['store'];
        }
        
        if (!empty($context['category'])) {
            $alt .= ' in ' . $context['category'];
        }
        
        // Add site branding
        $alt .= ' | AloneDeals';
        
        return $alt;
    }
    
    /**
     * Add lazy loading to images
     */
    public function addLazyLoading($html) {
        // Add loading="lazy" to all img tags
        $html = preg_replace('/<img(?![^>]*loading=)/', '<img loading="lazy"', $html);
        
        // Add decoding="async" for better performance
        $html = preg_replace('/<img(?![^>]*decoding=)/', '<img decoding="async"', $html);
        
        return $html;
    }
    
    /**
     * Generate responsive image srcset
     */
    public function generateSrcset($imagePath, $sizes = [320, 640, 1024, 1920]) {
        $srcset = [];
        $baseUrl = $this->siteUrl . '/images/';
        
        foreach ($sizes as $width) {
            $srcset[] = $baseUrl . $imagePath . ' ' . $width . 'w';
        }
        
        return implode(', ', $srcset);
    }
    
    /**
     * Add image schema markup
     */
    public function generateImageSchema($imageUrl, $caption, $author = 'AloneDeals') {
        $schema = [
            "@context" => "https://schema.org",
            "@type" => "ImageObject",
            "contentUrl" => $imageUrl,
            "caption" => $caption,
            "author" => [
                "@type" => "Organization",
                "name" => $author
            ],
            "copyrightNotice" => "© AloneDeals.com",
            "creditText" => "AloneDeals",
            "creator" => [
                "@type" => "Organization",
                "name" => "AloneDeals"
            ]
        ];
        
        return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES) . '</script>';
    }
    
    /**
     * Optimize all images in content
     */
    public function optimizeContentImages($html, $context = []) {
        // Find all img tags
        preg_match_all('/<img[^>]+>/i', $html, $images);
        
        foreach ($images[0] as $img) {
            $newImg = $img;
            
            // Add alt text if missing
            if (!preg_match('/alt=["\']([^"\']*)["\']/', $img)) {
                preg_match('/src=["\']([^"\']*)["\']/', $img, $src);
                if (!empty($src[1])) {
                    $imageName = basename($src[1]);
                    $alt = $this->generateAltText($imageName, $context);
                    $newImg = str_replace('<img', '<img alt="' . htmlspecialchars($alt) . '"', $newImg);
                }
            }
            
            // Add lazy loading
            if (!preg_match('/loading=/', $newImg)) {
                $newImg = str_replace('<img', '<img loading="lazy"', $newImg);
            }
            
            // Add async decoding
            if (!preg_match('/decoding=/', $newImg)) {
                $newImg = str_replace('<img', '<img decoding="async"', $newImg);
            }
            
            // Add width and height if missing (prevents layout shift)
            if (!preg_match('/width=/', $newImg) && !preg_match('/height=/', $newImg)) {
                $newImg = str_replace('<img', '<img width="800" height="600"', $newImg);
            }
            
            $html = str_replace($img, $newImg, $html);
        }
        
        return $html;
    }
    
    /**
     * Generate WebP version notice
     */
    public function suggestWebP($imagePath) {
        $webpPath = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $imagePath);
        
        return [
            'original' => $imagePath,
            'webp' => $webpPath,
            'html' => '<picture>
                <source srcset="' . $webpPath . '" type="image/webp">
                <img src="' . $imagePath . '" alt="">
            </picture>'
        ];
    }
    
    /**
     * Audit images in database
     */
    public function auditImages() {
        $issues = [];
        
        // Check blog post images
        $posts = $this->db->query("SELECT post_id, post_title, post_featured_image, post_content FROM blog_posts")->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($posts as $post) {
            // Check featured image alt
            if (!empty($post['post_featured_image'])) {
                $issues[] = [
                    'type' => 'blog_post',
                    'id' => $post['post_id'],
                    'title' => $post['post_title'],
                    'issue' => 'Featured image needs alt text',
                    'image' => $post['post_featured_image']
                ];
            }
            
            // Check content images
            preg_match_all('/<img[^>]+>/i', $post['post_content'], $images);
            foreach ($images[0] as $img) {
                if (!preg_match('/alt=["\']([^"\']*)["\']/', $img) || preg_match('/alt=["\']["\']/i', $img)) {
                    $issues[] = [
                        'type' => 'blog_post_content',
                        'id' => $post['post_id'],
                        'title' => $post['post_title'],
                        'issue' => 'Image missing alt text in content'
                    ];
                }
            }
        }
        
        return $issues;
    }
}
?>
