<?php
/**
 * Image utilities for the Bidda school management system
 */

/**
 * Validates and compresses an image file
 * 
 * @param array $file The $_FILES array for the uploaded image
 * @param string $upload_dir The directory to save the compressed image
 * @param int $quality The quality percentage (1-100) for compression
 * @return array Result array with success status, path, and error message
 */
function validate_and_compress_image($file, $upload_dir, $quality = 80) {
    $result = [
        'success' => false,
        'path' => '',
        'error' => ''
    ];

    // Check if file was uploaded without errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $result['error'] = 'ছবি আপলোড করতে সমস্যা হয়েছে। ত্রুটি কোড: ' . $file['error'];
        return $result;
    }

    // Validate file type
    $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    $file_type = mime_content_type($file['tmp_name']);
    
    if (!in_array($file_type, $allowed_types)) {
        $result['error'] = 'অবৈধ ছবির ফরম্যাট। শুধুমাত্র JPG, JPEG, PNG, GIF বা WEBP ফাইল অনুমোদিত।';
        return $result;
    }

    // Get image info
    $image_info = getimagesize($file['tmp_name']);
    if ($image_info === false) {
        $result['error'] = 'বৈধ ছবি নয়।';
        return $result;
    }

    // Check file size (limit to 5MB)
    if ($file['size'] > 5 * 1024 * 1024) {
        $result['error'] = 'ছবির সাইজ ৫ এমবির বেশি। ছোট সাইজের ছবি নির্বাচন করুন।';
        return $result;
    }

    // Generate unique filename
    $extension = '';
    switch ($image_info['mime']) {
        case 'image/jpeg':
        case 'image/jpg':
            $extension = '.jpg';
            break;
        case 'image/png':
            $extension = '.png';
            break;
        case 'image/gif':
            $extension = '.gif';
            break;
        case 'image/webp':
            $extension = '.webp';
            break;
    }

    $filename = 'photo_' . uniqid() . $extension;
    $filepath = $upload_dir . $filename;

    // Process and compress the image based on type
    $compressed = false;
    $source_image = null;

    switch ($image_info['mime']) {
        case 'image/jpeg':
        case 'image/jpg':
            $source_image = imagecreatefromjpeg($file['tmp_name']);
            break;
        case 'image/png':
            $source_image = imagecreatefrompng($file['tmp_name']);
            break;
        case 'image/gif':
            $source_image = imagecreatefromgif($file['tmp_name']);
            break;
        case 'image/webp':
            $source_image = imagecreatefromwebp($file['tmp_name']);
            break;
    }

    if ($source_image) {
        // Get original dimensions
        $original_width = imagesx($source_image);
        $original_height = imagesy($source_image);

        // Calculate new dimensions (max 1024x1024 while preserving aspect ratio)
        $max_width = 1024;
        $max_height = 1024;
        
        $ratio = min($max_width / $original_width, $max_height / $original_height);
        
        if ($ratio < 1) {
            $new_width = $original_width * $ratio;
            $new_height = $original_height * $ratio;
            
            // Create a new true color image
            $resized_image = imagecreatetruecolor($new_width, $new_height);
            
            // Preserve transparency for PNG and GIF
            if ($image_info['mime'] == 'image/png' || $image_info['mime'] == 'image/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);
            }
            
            // Resize the image
            imagecopyresampled(
                $resized_image, $source_image,
                0, 0, 0, 0,
                $new_width, $new_height,
                $original_width, $original_height
            );
            
            // Clean up the original source image
            imagedestroy($source_image);
            
            // Set the source to the resized image for saving
            $source_image = $resized_image;
        }

        // Save the compressed image
        switch ($image_info['mime']) {
            case 'image/jpeg':
            case 'image/jpg':
                $compressed = imagejpeg($source_image, $filepath, $quality);
                break;
            case 'image/png':
                // PNG compression uses 0-9 (0 = best quality, 9 = best compression)
                $png_quality = 9 - ceil(($quality / 10) - 1); // Convert 1-100 to 0-9
                if ($png_quality < 0) $png_quality = 0;
                if ($png_quality > 9) $png_quality = 9;
                $compressed = imagepng($source_image, $filepath, $png_quality);
                break;
            case 'image/gif':
                $compressed = imagegif($source_image, $filepath);
                break;
            case 'image/webp':
                $compressed = imagewebp($source_image, $filepath, $quality);
                break;
        }

        // Clean up the image resource
        imagedestroy($source_image);
    }

    if ($compressed) {
        $result['success'] = true;
        $result['path'] = $filepath;
    } else {
        $result['error'] = 'ছবি সংরক্ষণ করতে সমস্যা হয়েছে।';
    }

    return $result;
}

/**
 * Resizes and compresses an image from base64 data (used for camera captures)
 * 
 * @param string $base64_data Base64 encoded image data
 * @param string $upload_dir Directory to save the compressed image
 * @param int $quality Quality percentage (1-100)
 * @return array Result array with success status, path, and error message
 */
function resize_and_compress_base64_image($base64_data, $upload_dir, $quality = 80) {
    $result = [
        'success' => false,
        'path' => '',
        'error' => ''
    ];

    // Decode base64 data
    $image_data = base64_decode($base64_data);
    if ($image_data === false) {
        $result['error'] = 'ছবির ডেটা বৈধ নয়।';
        return $result;
    }

    // Create temporary file
    $temp_file = tempnam(sys_get_temp_dir(), 'bidda_img_');
    file_put_contents($temp_file, $image_data);

    // Validate image
    $image_info = getimagesize($temp_file);
    if ($image_info === false) {
        unlink($temp_file);
        $result['error'] = 'বৈধ ছবি নয়।';
        return $result;
    }

    // Generate unique filename
    $extension = '';
    switch ($image_info['mime']) {
        case 'image/jpeg':
        case 'image/jpg':
            $extension = '.jpg';
            break;
        case 'image/png':
            $extension = '.png';
            break;
        case 'image/gif':
            $extension = '.gif';
            break;
        case 'image/webp':
            $extension = '.webp';
            break;
    }

    $filename = 'captured_' . uniqid() . $extension;
    $filepath = $upload_dir . $filename;

    // Process image
    $source_image = null;
    switch ($image_info['mime']) {
        case 'image/jpeg':
        case 'image/jpg':
            $source_image = imagecreatefromjpeg($temp_file);
            break;
        case 'image/png':
            $source_image = imagecreatefrompng($temp_file);
            break;
        case 'image/gif':
            $source_image = imagecreatefromgif($temp_file);
            break;
        case 'image/webp':
            $source_image = imagecreatefromwebp($temp_file);
            break;
    }

    if ($source_image) {
        // Get original dimensions
        $original_width = imagesx($source_image);
        $original_height = imagesy($source_image);

        // Calculate new dimensions (max 1024x1024 while preserving aspect ratio)
        $max_width = 1024;
        $max_height = 1024;
        
        $ratio = min($max_width / $original_width, $max_height / $original_height);
        
        if ($ratio < 1) {
            $new_width = $original_width * $ratio;
            $new_height = $original_height * $ratio;
            
            // Create a new true color image
            $resized_image = imagecreatetruecolor($new_width, $new_height);
            
            // Preserve transparency for PNG and GIF
            if ($image_info['mime'] == 'image/png' || $image_info['mime'] == 'image/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);
            }
            
            // Resize the image
            imagecopyresampled(
                $resized_image, $source_image,
                0, 0, 0, 0,
                $new_width, $new_height,
                $original_width, $original_height
            );
            
            // Clean up the original source image
            imagedestroy($source_image);
            
            // Set the source to the resized image for saving
            $source_image = $resized_image;
        }

        // Save the compressed image
        $compressed = false;
        switch ($image_info['mime']) {
            case 'image/jpeg':
            case 'image/jpg':
                $compressed = imagejpeg($source_image, $filepath, $quality);
                break;
            case 'image/png':
                // PNG compression uses 0-9 (0 = best quality, 9 = best compression)
                $png_quality = 9 - ceil(($quality / 10) - 1); // Convert 1-100 to 0-9
                if ($png_quality < 0) $png_quality = 0;
                if ($png_quality > 9) $png_quality = 9;
                $compressed = imagepng($source_image, $filepath, $png_quality);
                break;
            case 'image/gif':
                $compressed = imagegif($source_image, $filepath);
                break;
            case 'image/webp':
                $compressed = imagewebp($source_image, $filepath, $quality);
                break;
        }

        // Clean up the image resource
        imagedestroy($source_image);
        
        if ($compressed) {
            $result['success'] = true;
            $result['path'] = $filepath;
        } else {
            $result['error'] = 'ছবি সংরক্ষণ করতে সমস্যা হয়েছে।';
        }
    } else {
        $result['error'] = 'ছবি প্রসেস করতে সমস্যা হয়েছে।';
    }

    // Clean up temp file
    unlink($temp_file);

    return $result;
}
?>