<?php

/**
 * Image Service
 * Handles image compression and WebP conversion
 */
class ImageService {
    
    private $uploadPath;
    private $quality;
    
    public function __construct() {
        $this->uploadPath = UPLOAD_PATH . '/images/';
        $this->quality = IMAGE_QUALITY;
        
        // Create upload directory if it doesn't exist
        if (!is_dir($this->uploadPath)) {
            mkdir($this->uploadPath, 0755, true);
        }
    }
    
    /**
     * Process uploaded image: compress and convert to WebP
     * 
     * @param array $file Uploaded file from $_FILES
     * @return string|false WebP file path on success, false on failure
     */
    public function processImage($file) {
        // Validate file
        if (!$this->validateImage($file)) {
            logError("Image validation failed", ['file' => $file]);
            return false;
        }
        
        // Generate unique filename
        $filename = $this->generateFilename();
        $webpPath = $this->uploadPath . $filename . '.webp';
        
        // Load image based on type
        $image = $this->loadImage($file['tmp_name'], $file['type']);
        if (!$image) {
            logError("Failed to load image", ['file' => $file['tmp_name'], 'type' => $file['type']]);
            return false;
        }
        
        // Convert to WebP
        if (!imagewebp($image, $webpPath, $this->quality)) {
            imagedestroy($image);
            logError("Failed to convert image to WebP", ['path' => $webpPath]);
            return false;
        }
        
        imagedestroy($image);
        
        // Log success
        logError("Image processed successfully", ['path' => $webpPath, 'relative' => 'images/' . $filename . '.webp']);
        
        // Return relative path for database storage
        return 'images/' . $filename . '.webp';
    }
    
    /**
     * Validate uploaded image
     * 
     * @param array $file
     * @return bool
     */
    private function validateImage($file) {
        // Check for upload errors
        if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
            return false;
        }
        
        // Check file size (max 5MB)
        if ($file['size'] > 5 * 1024 * 1024) {
            return false;
        }
        
        // Check MIME type
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($file['type'], $allowedTypes)) {
            return false;
        }
        
        // Verify it's actually an image
        $imageInfo = getimagesize($file['tmp_name']);
        if ($imageInfo === false) {
            return false;
        }
        
        return true;
    }
    
    /**
     * Load image from file based on type
     * 
     * @param string $filepath
     * @param string $mimeType
     * @return resource|false
     */
    private function loadImage($filepath, $mimeType) {
        $image = false;
        
        switch ($mimeType) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($filepath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($filepath);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($filepath);
                break;
            default:
                return false;
        }
        
        // Convert palette images to true color for WebP support
        if ($image && !imageistruecolor($image)) {
            $width = imagesx($image);
            $height = imagesy($image);
            $trueColorImage = imagecreatetruecolor($width, $height);
            
            // Preserve transparency
            imagealphablending($trueColorImage, false);
            imagesavealpha($trueColorImage, true);
            
            // Copy palette image to true color
            imagecopy($trueColorImage, $image, 0, 0, 0, 0, $width, $height);
            imagedestroy($image);
            
            return $trueColorImage;
        }
        
        return $image;
    }
    
    /**
     * Generate unique filename
     * 
     * @return string
     */
    private function generateFilename() {
        return uniqid('img_', true) . '_' . time();
    }
    
    /**
     * Delete image file
     * 
     * @param string $relativePath Relative path from database
     * @return bool
     */
    public function deleteImage($relativePath) {
        if (empty($relativePath)) {
            return false;
        }
        
        $fullPath = UPLOAD_PATH . $relativePath;
        
        if (file_exists($fullPath)) {
            return unlink($fullPath);
        }
        
        return false;
    }
    
    /**
     * Get full path for image
     * 
     * @param string $relativePath
     * @return string
     */
    public function getImagePath($relativePath) {
        return UPLOAD_PATH . $relativePath;
    }
    
    /**
     * Get image URL for display
     * 
     * @param string $relativePath
     * @return string
     */
    public function getImageUrl($relativePath) {
        if (empty($relativePath)) {
            return '';
        }
        
        // Return URL using BASE_URL instead of hardcoded path
        $urlPath = (URL_PATH !== '') ? URL_PATH : '';
        return $urlPath . '/uploads/' . $relativePath;
    }
    
    /**
     * Check if image exists
     * 
     * @param string $relativePath
     * @return bool
     */
    public function imageExists($relativePath) {
        if (empty($relativePath)) {
            return false;
        }
        
        $fullPath = UPLOAD_PATH . $relativePath;
        return file_exists($fullPath);
    }
}
