<?php
/**
 * ImageHandler - Product Image Management
 * Aegean Dominance - İzmir Tenteci V2
 */

declare(strict_types=1);

class ImageHandler
{
    private Database $db;
    private string $urunlerPath;
    private array $log = [];

    // Image category mapping
    private array $categoryMap = [
        'bioclimatic' => 'bioklimatik-pergola',
        'pergola-tente' => 'pergola-tente',
        'askili-pergola' => 'askili-pergola',
        'radyal-pergola' => 'radyal-pergola',
        'cift-acilir-pergola' => 'cift-acilir-pergola',
        'mafsalli' => 'mafsalli-tente',
        'kasetli-tente' => 'kasetli-tente',
        'wintent-tente' => 'wintent-tente',
        'Karpuz' => 'karpuz-tente',
        'zip-perde' => 'zip-perde',
        'tavan-zipi' => 'tavan-zip-perde',
        'cam-tavan' => 'cam-tavan-sistemleri',
        'Giyotin' => 'giyotin-cam-sistemleri',
        'surgulu-cam' => 'surgulu-cam-balkon',
        'bombeli-askili' => 'bombeli-askili-pergola',
        'cift-acilir-askili' => 'cift-acilir-askili',
        'radyal-cift-acilir' => 'radyal-cift-acilir',
        'RoolingRoof' => 'rolling-roof'
    ];

    public function __construct()
    {
        $this->db = Database::getInstance();
        $this->urunlerPath = defined('PRODUCTS_PATH') ? PRODUCTS_PATH : dirname(__DIR__, 2) . '/urunler';
    }

    /**
     * Scan urunler folder and return all images
     */
    public function scanUrunlerFolder(): array
    {
        $images = [];
        
        try {
            if (!is_dir($this->urunlerPath)) {
                $this->log[] = "⚠️ Urunler klasörü bulunamadı: " . $this->urunlerPath;
                return $images;
            }
            
            if (!is_readable($this->urunlerPath)) {
                $this->log[] = "❌ Urunler klasörü okunamıyor (izin hatası): " . $this->urunlerPath;
                return $images;
            }

            $files = scandir($this->urunlerPath);
            if ($files === false) {
                $this->log[] = "❌ Klasör taranamadı: " . $this->urunlerPath;
                return $images;
            }
            
            foreach ($files as $file) {
                if ($file === '.' || $file === '..') continue;
                
                $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                $filePath = $this->urunlerPath . '/' . $file;
                
                if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp']) && is_file($filePath)) {
                    $images[] = [
                        'filename' => $file,
                        'extension' => $ext,
                        'path' => $filePath,
                        'size' => @filesize($filePath) ?: 0,
                        'is_webp' => $ext === 'webp'
                    ];
                }
            }

            $this->log[] = "✅ " . count($images) . " görsel tarandı";
            
        } catch (Exception $e) {
            $this->log[] = "❌ Tarama hatası: " . $e->getMessage();
            error_log("ImageHandler::scanUrunlerFolder error: " . $e->getMessage());
        }
        
        return $images;
    }

    /**
     * Categorize images by service type
     */
    public function categorizeImages(): array
    {
        $images = $this->scanUrunlerFolder();
        $categorized = [];

        foreach ($images as $image) {
            $filename = $image['filename'];
            $category = $this->detectCategory($filename);
            
            if (!isset($categorized[$category])) {
                $categorized[$category] = [];
            }
            
            $categorized[$category][] = $image;
        }

        // Log categorization
        foreach ($categorized as $cat => $imgs) {
            $this->log[] = "📁 {$cat}: " . count($imgs) . " görsel";
        }

        return $categorized;
    }

    /**
     * Detect category from filename
     */
    private function detectCategory(string $filename): string
    {
        foreach ($this->categoryMap as $pattern => $serviceSlug) {
            if (stripos($filename, $pattern) !== false) {
                return $serviceSlug;
            }
        }
        return 'uncategorized';
    }

    /**
     * Distribute images to service_images table
     */
    public function distributeToServices(): void
    {
        $this->log[] = "🚀 Görseller servislere dağıtılıyor...";

        $categorized = $this->categorizeImages();
        $totalInserted = 0;

        foreach ($categorized as $serviceSlug => $images) {
            if ($serviceSlug === 'uncategorized') continue;

            // Get service ID
            $serviceId = $this->db->fetchColumn(
                "SELECT id FROM services WHERE slug = ?",
                [$serviceSlug]
            );

            if (!$serviceId) {
                $this->log[] = "⚠️ Servis bulunamadı: {$serviceSlug}";
                continue;
            }

            // Clear existing images for this service
            $this->db->execute("DELETE FROM service_images WHERE service_id = ?", [$serviceId]);

            // Prefer WebP, group by base name
            $imageGroups = [];
            foreach ($images as $image) {
                $baseName = preg_replace('/\.(jpg|jpeg|png|webp)$/i', '', $image['filename']);
                if (!isset($imageGroups[$baseName])) {
                    $imageGroups[$baseName] = [];
                }
                $imageGroups[$baseName][$image['extension']] = $image;
            }

            $order = 0;
            foreach ($imageGroups as $baseName => $variants) {
                // Prefer WebP
                $primary = $variants['webp'] ?? $variants['jpg'] ?? $variants['jpeg'] ?? $variants['png'] ?? null;
                if (!$primary) continue;

                $webpPath = isset($variants['webp']) ? 'urunler/' . $variants['webp']['filename'] : null;
                $jpgPath = isset($variants['jpg']) ? 'urunler/' . $variants['jpg']['filename'] : 
                          (isset($variants['jpeg']) ? 'urunler/' . $variants['jpeg']['filename'] : null);

                $imagePath = $webpPath ?? $jpgPath ?? 'urunler/' . $primary['filename'];
                
                // Is featured? First image of each service
                $isFeatured = ($order === 0) ? 1 : 0;

                $sql = "INSERT INTO service_images 
                        (service_id, image_path, image_webp, alt_text, display_order, is_featured)
                        VALUES (?, ?, ?, ?, ?, ?)";
                
                $altText = ucwords(str_replace(['-', '_'], ' ', $baseName));
                
                $this->db->execute($sql, [
                    $serviceId,
                    $imagePath,
                    $webpPath,
                    $altText . ' - İzmir Tenteci',
                    $order,
                    $isFeatured
                ]);

                $order++;
                $totalInserted++;
            }

            $this->log[] = "✅ {$serviceSlug}: {$order} görsel eklendi";
        }

        $this->log[] = "✅ Toplam {$totalInserted} görsel dağıtıldı";
    }

    /**
     * Get WebP path for an image (convert if needed)
     */
    public function getWebPPath(string $imagePath): string
    {
        $ext = strtolower(pathinfo($imagePath, PATHINFO_EXTENSION));
        
        if ($ext === 'webp') {
            return $imagePath;
        }

        // Check if WebP version exists
        $webpPath = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $imagePath);
        
        if (file_exists($this->urunlerPath . '/' . basename($webpPath))) {
            return 'urunler/' . basename($webpPath);
        }

        return $imagePath;
    }

    /**
     * Get images for a service
     */
    public function getServiceImages(int $serviceId, int $limit = 20): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM service_images 
             WHERE service_id = ? 
             ORDER BY is_featured DESC, display_order ASC 
             LIMIT ?",
            [$serviceId, $limit]
        );
    }

    /**
     * Get featured image for a service
     */
    public function getFeaturedImage(int $serviceId): ?string
    {
        return $this->db->fetchColumn(
            "SELECT COALESCE(image_webp, image_path) 
             FROM service_images 
             WHERE service_id = ? AND is_featured = 1 
             LIMIT 1",
            [$serviceId]
        );
    }

    /**
     * Generate lazy-load HTML for image
     */
    public function lazyImage(string $src, string $alt, string $class = ''): string
    {
        $webpSrc = $this->getWebPPath($src);
        
        return sprintf(
            '<img src="%s" alt="%s" loading="lazy" decoding="async" class="%s">',
            htmlspecialchars($webpSrc),
            htmlspecialchars($alt),
            htmlspecialchars($class)
        );
    }

    /**
     * Get migration log
     */
    public function getLog(): array
    {
        return $this->log;
    }

    /**
     * Run full image distribution
     */
    public function run(): array
    {
        $this->log[] = "🖼️ Image Handler başlatılıyor...";
        $this->distributeToServices();
        return $this->log;
    }
}
