<?php
/**
 * Optimized File Upload Handler for High Concurrency
 * Handles uploads efficiently with proper validation and storage
 */
class UploadOptimizer {
    private static array $allowedTypes = [
        'image/jpeg', 'image/png', 'image/gif', 'image/webp'
    ];
    
    private static int $maxSize = 5 * 1024 * 1024; // 5MB
    
    /**
     * Handle file upload with optimization
     */
    public static function handleUpload(array $file, string $destination): array {
        $startTime = microtime(true);
        
        // Validate file
        $validation = self::validateFile($file);
        if (!$validation['valid']) {
            return [
                'success' => false,
                'error' => $validation['error']
            ];
        }
        
        // Create optimized filename
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid() . '_' . time() . '.' . $extension;
        $filepath = $destination . '/' . $filename;
        
        // Ensure directory exists
        if (!is_dir($destination)) {
            mkdir($destination, 0755, true);
        }
        
        // Move uploaded file
        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            return [
                'success' => false,
                'error' => 'Failed to move uploaded file'
            ];
        }
        
        // Optimize image if it's an image
        if (strpos($file['type'], 'image/') === 0) {
            self::optimizeImage($filepath);
        }
        
        $uploadTime = microtime(true) - $startTime;
        
        return [
            'success' => true,
            'filename' => $filename,
            'filepath' => $filepath,
            'size' => filesize($filepath),
            'upload_time' => round($uploadTime * 1000, 2) // in ms
        ];
    }
    
    /**
     * Validate uploaded file
     */
    private static function validateFile(array $file): array {
        // Check if file was uploaded
        if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
            return ['valid' => false, 'error' => 'No file uploaded'];
        }
        
        // Check file size
        if ($file['size'] > self::$maxSize) {
            return ['valid' => false, 'error' => 'File size exceeds maximum limit'];
        }
        
        // Check file type
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        
        if (!in_array($mimeType, self::allowedTypes)) {
            return ['valid' => false, 'error' => 'Invalid file type'];
        }
        
        return ['valid' => true];
    }
    
    /**
     * Optimize image (compress and resize if needed)
     */
    private static function optimizeImage(string $filepath): void {
        try {
            $imageInfo = getimagesize($filepath);
            if (!$imageInfo) {
                return;
            }
            
            $width = $imageInfo[0];
            $height = $imageInfo[1];
            $type = $imageInfo[2];
            
            // Only optimize if image is larger than needed
            if ($width > 1920 || $height > 1080) {
                $newWidth = min($width, 1920);
                $newHeight = min($height, 1080);
                
                // Create new image
                switch ($type) {
                    case IMAGETYPE_JPEG:
                        $source = imagecreatefromjpeg($filepath);
                        break;
                    case IMAGETYPE_PNG:
                        $source = imagecreatefrompng($filepath);
                        break;
                    case IMAGETYPE_GIF:
                        $source = imagecreatefromgif($filepath);
                        break;
                    case IMAGETYPE_WEBP:
                        $source = imagecreatefromwebp($filepath);
                        break;
                    default:
                        return;
                }
                
                if (!$source) {
                    return;
                }
                
                // Resize
                $destination = imagecreatetruecolor($newWidth, $newHeight);
                imagecopyresampled($destination, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                
                // Save with compression
                switch ($type) {
                    case IMAGETYPE_JPEG:
                        imagejpeg($destination, $filepath, 85); // 85% quality
                        break;
                    case IMAGETYPE_PNG:
                        imagepng($destination, $filepath, 9); // Maximum compression
                        break;
                    case IMAGETYPE_GIF:
                        imagegif($destination, $filepath);
                        break;
                    case IMAGETYPE_WEBP:
                        imagewebp($destination, $filepath, 85); // 85% quality
                        break;
                }
                
                imagedestroy($source);
                imagedestroy($destination);
            }
        } catch (Exception $e) {
            // Silently fail on image optimization
            error_log("Image optimization failed: " . $e->getMessage());
        }
    }
    
    /**
     * Clean up old uploads
     */
    public static function cleanupOldUploads(string $directory, int $days = 30): int {
        $count = 0;
        $cutoffTime = time() - ($days * 86400);
        
        if (!is_dir($directory)) {
            return 0;
        }
        
        $files = glob($directory . '/*');
        
        foreach ($files as $file) {
            if (is_file($file) && filemtime($file) < $cutoffTime) {
                @unlink($file);
                $count++;
            }
        }
        
        return $count;
    }
}
