<?php
/**
 * Image Cache Manager
 * Speichert und verwaltet Reifenbilder lokal
 */

class ImageCacheManager {
    private $cacheDir;
    private $db;
    
    public function __construct() {
        $this->cacheDir = __DIR__ . '/../cache/images/';
        if (!is_dir($this->cacheDir)) {
            mkdir($this->cacheDir, 0755, true);
        }
        
        require_once __DIR__ . '/../config/database.php';
        $this->db = new Database();
    }
    
    /**
     * Speichert ein Bild im Cache
     */
    public function cacheImage($lgfotoId, $imageData, $contentType, $appointmentId) {
        try {
            // Erstelle eindeutigen Dateinamen
            $filename = $this->generateFilename($lgfotoId, $contentType);
            $filepath = $this->cacheDir . $filename;
            
            // Speichere Bild
            if (file_put_contents($filepath, $imageData) === false) {
                throw new Exception("Fehler beim Speichern der Bilddatei");
            }
            
            // Speichere Metadaten in Datenbank
            $this->saveImageMetadata($lgfotoId, $filename, $contentType, $appointmentId, filesize($filepath));
            
            return [
                'success' => true,
                'filename' => $filename,
                'filepath' => $filepath,
                'size' => filesize($filepath)
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Lädt ein Bild aus dem Cache
     */
    public function getCachedImage($lgfotoId) {
        try {
            $conn = $this->db->getConnection();
            
            // Hole Bild-Metadaten aus Datenbank
            $stmt = $conn->prepare("
                SELECT filename, content_type, file_size, created_at 
                FROM cached_images 
                WHERE lgfoto_id = ? 
                ORDER BY created_at DESC 
                LIMIT 1
            ");
            $stmt->execute([$lgfotoId]);
            $metadata = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$metadata) {
                return ['success' => false, 'error' => 'Bild nicht im Cache gefunden'];
            }
            
            $filepath = $this->cacheDir . $metadata['filename'];
            
            if (!file_exists($filepath)) {
                // Datei existiert nicht mehr, lösche Datenbank-Eintrag
                $this->deleteCachedImage($lgfotoId);
                return ['success' => false, 'error' => 'Bilddatei nicht mehr vorhanden'];
            }
            
            $imageData = file_get_contents($filepath);
            if ($imageData === false) {
                return ['success' => false, 'error' => 'Fehler beim Lesen der Bilddatei'];
            }
            
            return [
                'success' => true,
                'data' => $imageData,
                'content_type' => $metadata['content_type'],
                'size' => $metadata['file_size'],
                'created_at' => $metadata['created_at']
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Prüft ob ein Bild im Cache ist
     */
    public function isImageCached($lgfotoId) {
        try {
            $conn = $this->db->getConnection();
            
            $stmt = $conn->prepare("
                SELECT COUNT(*) as count 
                FROM cached_images 
                WHERE lgfoto_id = ?
            ");
            $stmt->execute([$lgfotoId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            return $result['count'] > 0;
            
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Löscht ein Bild aus dem Cache
     */
    public function deleteCachedImage($lgfotoId) {
        try {
            $conn = $this->db->getConnection();
            
            // Hole Dateiname
            $stmt = $conn->prepare("SELECT filename FROM cached_images WHERE lgfoto_id = ?");
            $stmt->execute([$lgfotoId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result) {
                $filepath = $this->cacheDir . $result['filename'];
                if (file_exists($filepath)) {
                    unlink($filepath);
                }
            }
            
            // Lösche Datenbank-Eintrag
            $stmt = $conn->prepare("DELETE FROM cached_images WHERE lgfoto_id = ?");
            $stmt->execute([$lgfotoId]);
            
            return true;
            
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Generiert eindeutigen Dateinamen
     */
    private function generateFilename($lgfotoId, $contentType) {
        $extension = 'jpg'; // Standard
        if (strpos($contentType, 'png') !== false) {
            $extension = 'png';
        } elseif (strpos($contentType, 'gif') !== false) {
            $extension = 'gif';
        } elseif (strpos($contentType, 'webp') !== false) {
            $extension = 'webp';
        }
        
        return 'lgfoto_' . $lgfotoId . '_' . time() . '.' . $extension;
    }
    
    /**
     * Speichert Bild-Metadaten in Datenbank
     */
    private function saveImageMetadata($lgfotoId, $filename, $contentType, $appointmentId, $fileSize) {
        $conn = $this->db->getConnection();
        
        // Lösche alte Einträge für diese LGFOTO_ID
        $stmt = $conn->prepare("DELETE FROM cached_images WHERE lgfoto_id = ?");
        $stmt->execute([$lgfotoId]);
        
        // Füge neuen Eintrag hinzu
        $stmt = $conn->prepare("
            INSERT INTO cached_images (lgfoto_id, filename, content_type, appointment_id, file_size, created_at) 
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$lgfotoId, $filename, $contentType, $appointmentId, $fileSize]);
    }
    
    /**
     * Bereinigt alte Cache-Einträge
     */
    public function cleanupOldCache($daysOld = 30) {
        try {
            $conn = $this->db->getConnection();
            
            // Hole alte Einträge
            $stmt = $conn->prepare("
                SELECT filename FROM cached_images 
                WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
            ");
            $stmt->execute([$daysOld]);
            $oldFiles = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Lösche Dateien
            foreach ($oldFiles as $filename) {
                $filepath = $this->cacheDir . $filename;
                if (file_exists($filepath)) {
                    unlink($filepath);
                }
            }
            
            // Lösche Datenbank-Einträge
            $stmt = $conn->prepare("
                DELETE FROM cached_images 
                WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
            ");
            $stmt->execute([$daysOld]);
            
            return count($oldFiles);
            
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Gibt Cache-Statistiken zurück
     */
    public function getCacheStats() {
        try {
            $conn = $this->db->getConnection();
            
            $stmt = $conn->prepare("
                SELECT 
                    COUNT(*) as total_images,
                    SUM(file_size) as total_size,
                    AVG(file_size) as avg_size,
                    MIN(created_at) as oldest,
                    MAX(created_at) as newest
                FROM cached_images
            ");
            $stmt->execute();
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Berechne Verzeichnis-Größe
            $dirSize = $this->getDirectorySize($this->cacheDir);
            
            return [
                'total_images' => $stats['total_images'],
                'total_size_db' => $stats['total_size'],
                'total_size_dir' => $dirSize,
                'avg_size' => $stats['avg_size'],
                'oldest' => $stats['oldest'],
                'newest' => $stats['newest']
            ];
            
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Berechnet Verzeichnis-Größe
     */
    private function getDirectorySize($directory) {
        $size = 0;
        if (is_dir($directory)) {
            foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
                if ($file->isFile()) {
                    $size += $file->getSize();
                }
            }
        }
        return $size;
    }
}
?>
