<?php
/**
 * Image utility functions for the BIDDA system
 */

// Check if GD extension is available
if (!extension_loaded('gd')) {
    // If GD is not available, show a warning but continue
    error_log('GD extension is not available. Image compression will be skipped.');
}

/**
 * Compress an image to a target file size (in KB)
 * 
 * @param string $source_path Path to the source image
 * @param string $target_path Path where the compressed image should be saved
 * @param int $target_size_kb Target size in KB (default 100KB)
 * @return bool True if compression was successful, false otherwise
 */
function compress_image_to_size($source_path, $target_path, $target_size_kb = 100) {
    // Check if GD extension is available
    if (!extension_loaded('gd')) {
        // If GD is not available, simply copy the file without compression
        return copy($source_path, $target_path);
    }
    
    // Get image info
    $image_info = getimagesize($source_path);
    if (!$image_info) {
        return false;
    }
    
    $original_size = filesize($source_path);
    $target_size_bytes = $target_size_kb * 1024;
    
    // If the image is already smaller than the target size, just copy it
    if ($original_size <= $target_size_bytes) {
        return copy($source_path, $target_path);
    }
    
    $image_type = $image_info[2];
    
    // Create image resource based on type
    switch ($image_type) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($source_path);
            $output_function = 'imagejpeg';
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($source_path);
            $output_function = 'imagepng';
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($source_path);
            $output_function = 'imagegif';
            break;
        default:
            return false; // Unsupported image type
    }
    
    if (!$image) {
        return false;
    }
    
    // Get original dimensions
    $original_width = imagesx($image);
    $original_height = imagesy($image);
    
    // Try different quality/compression levels to get close to target size
    $quality = 90; // Start with high quality for JPEG
    $success = false;
    
    // Try different quality levels for JPEG or different approaches for other formats
    while ($quality >= 10) {
        $temp_path = $target_path . '.temp';
        
        if ($image_type == IMAGETYPE_JPEG) {
            $result = $output_function($image, $temp_path, $quality);
        } elseif ($image_type == IMAGETYPE_PNG) {
            // For PNG, use compression level (0-9) instead of quality
            $png_compression = 9 - min(9, floor(($quality - 10) / 10)); // Convert quality to compression level
            $result = $output_function($image, $temp_path, $png_compression);
        } else {
            // For GIF, use default quality
            $result = $output_function($image, $temp_path);
        }
        
        if ($result) {
            $current_size = filesize($temp_path);
            
            if ($current_size <= $target_size_bytes) {
                // We've achieved the target size or smaller
                rename($temp_path, $target_path);
                $success = true;
                break;
            } else {
                // Try a lower quality
                unlink($temp_path);
                $quality -= 10;
            }
        } else {
            if (file_exists($temp_path)) {
                unlink($temp_path);
            }
            break;
        }
    }
    
    // If we couldn't achieve target size by quality adjustment, try resizing
    if (!$success) {
        // Start with original dimensions and reduce by 10% each iteration
        $scale_factor = 0.9;
        
        while ($scale_factor >= 0.1) {
            $new_width = (int)($original_width * $scale_factor);
            $new_height = (int)($original_height * $scale_factor);
            
            $resized_image = imagecreatetruecolor($new_width, $new_height);
            
            // Preserve transparency for PNG and GIF
            if ($image_type == IMAGETYPE_PNG || $image_type == IMAGETYPE_GIF) {
                imagealphablending($resized_image, false);
                imagesavealpha($resized_image, true);
                $transparent = imagecolorallocatealpha($resized_image, 255, 255, 255, 127);
                imagefilledrectangle($resized_image, 0, 0, $new_width, $new_height, $transparent);
            }
            
            imagecopyresampled(
                $resized_image, $image,
                0, 0, 0, 0,
                $new_width, $new_height,
                $original_width, $original_height
            );
            
            $temp_path = $target_path . '.temp';
            
            if ($image_type == IMAGETYPE_JPEG) {
                $result = imagejpeg($resized_image, $temp_path, 80);
            } elseif ($image_type == IMAGETYPE_PNG) {
                $result = imagepng($resized_image, $temp_path, 6);
            } else {
                $result = imagegif($resized_image, $temp_path);
            }
            
            if ($result) {
                $current_size = filesize($temp_path);
                
                if ($current_size <= $target_size_bytes) {
                    rename($temp_path, $target_path);
                    $success = true;
                    imagedestroy($resized_image);
                    break;
                } else {
                    unlink($temp_path);
                }
            }
            
            imagedestroy($resized_image);
            $scale_factor -= 0.1;
        }
    }
    
    // Clean up
    imagedestroy($image);
    
    return $success;
}

/**
 * Validate and compress an uploaded image file
 * 
 * @param array $file_upload The $_FILES array for the image
 * @param string $upload_dir Directory to save the compressed image
 * @param int $max_size_kb Maximum size in KB (default 100KB)
 * @return array Result with 'success', 'path', and 'error' keys
 */
function validate_and_compress_image($file_upload, $upload_dir, $max_size_kb = 100) {
    // Check for upload errors
    if ($file_upload['error'] !== UPLOAD_ERR_OK) {
        return [
            'success' => false,
            'error' => 'File upload error: ' . $file_upload['error']
        ];
    }
    
    // Validate file type
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
    $file_extension = strtolower(pathinfo($file_upload['name'], PATHINFO_EXTENSION));
    
    if (!in_array($file_extension, $allowed_extensions)) {
        return [
            'success' => false,
            'error' => 'শুধুমাত্র JPG, JPEG, PNG এবং GIF ফাইল গ্রহণ করা হয়।'
        ];
    }
    
    // Create upload directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Generate unique filename
    $filename = uniqid() . '_' . time() . '.' . $file_extension;
    $target_path = $upload_dir . $filename;
    
    // Compress the image
    if (compress_image_to_size($file_upload['tmp_name'], $target_path, $max_size_kb)) {
        $final_size = filesize($target_path);
        $final_size_kb = round($final_size / 1024, 2);
        
        return [
            'success' => true,
            'path' => $target_path,
            'size_kb' => $final_size_kb
        ];
    } else {
        return [
            'success' => false,
            'error' => 'ছবি কম্প্রেস করতে সমস্যা হয়েছে।'
        ];
    }
}
?>