<?php
/**
 * Image Boost — Helper Functions
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Get the active image processing engine.
 * Prefers Imagick over GD for better quality.
 *
 * @return string 'imagick' or 'gd'
 */
function imgboost_get_engine() {
    if (extension_loaded('imagick') && class_exists('Imagick')) {
        return 'imagick';
    }
    if (extension_loaded('gd') && function_exists('imagecreatefromjpeg')) {
        return 'gd';
    }
    return 'none';
}

/**
 * Check if WebP is supported by the current engine.
 *
 * @return bool
 */
function imgboost_supports_webp() {
    $engine = imgboost_get_engine();
    if ($engine === 'imagick') {
        $formats = Imagick::queryFormats('WEBP');
        return !empty($formats);
    }
    if ($engine === 'gd') {
        return function_exists('imagewebp');
    }
    return false;
}

/**
 * Get compression quality settings for a given level.
 *
 * @param string $level 'normal' or 'pro'
 * @return array
 */
function imgboost_get_quality($level = 'pro') {
    $levels = [
        'normal' => [
            'jpeg_quality'  => 100,
            'png_quality'   => 9,
            'webp_quality'  => 100,
            'max_width'     => 0,
            'strip_meta'    => true,
            'label'         => __('Normal (Lossless)', 'image-boost'),
            'description'   => __('Strips metadata without quality loss. ~5-15% savings.', 'image-boost'),
        ],
        'pro' => [
            'jpeg_quality'  => 82,
            'png_quality'   => 8,
            'webp_quality'  => 80,
            'max_width'     => 2560,
            'strip_meta'    => true,
            'label'         => __('Pro (Smart Lossy)', 'image-boost'),
            'description'   => __('Smart compression with imperceptible quality loss. ~40-60% savings.', 'image-boost'),
        ],
    ];

    return isset($levels[$level]) ? $levels[$level] : $levels['pro'];
}

/**
 * Format bytes to human-readable string.
 *
 * @param int $bytes
 * @param int $precision
 * @return string
 */
function imgboost_format_bytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

/**
 * Get the MIME type of an image file.
 *
 * @param string $file_path
 * @return string|false
 */
function imgboost_get_mime_type($file_path) {
    if (!file_exists($file_path)) return false;

    // Use finfo to read MAGIC BYTES (Secure)
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file_path);
        finfo_close($finfo);
        return $mime;
    }

    // Fallback securely
    if (function_exists('mime_content_type')) {
        return mime_content_type($file_path);
    }

    $info = wp_check_filetype($file_path);
    return $info['type'] ?? false;
}

/**
 * Check if a file is an optimizable image.
 *
 * @param string $file_path
 * @return bool
 */
function imgboost_is_optimizable($file_path) {
    $mime = imgboost_get_mime_type($file_path);
    $supported = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    return in_array($mime, $supported);
}

/**
 * Get all image sizes registered in WordPress.
 *
 * @return array
 */
function imgboost_get_all_image_sizes() {
    global $_wp_additional_image_sizes;
    $sizes = [];

    foreach (get_intermediate_image_sizes() as $size) {
        if (in_array($size, ['thumbnail', 'medium', 'medium_large', 'large'])) {
            $sizes[$size] = [
                'width'  => (int) get_option("{$size}_size_w"),
                'height' => (int) get_option("{$size}_size_h"),
                'crop'   => (bool) get_option("{$size}_crop"),
            ];
        } elseif (isset($_wp_additional_image_sizes[$size])) {
            $sizes[$size] = $_wp_additional_image_sizes[$size];
        }
    }

    return $sizes;
}

/**
 * Get full file path from attachment ID.
 *
 * @param int $attachment_id
 * @return string|false
 */
function imgboost_get_attachment_path($attachment_id) {
    $file = get_attached_file($attachment_id);
    if ($file && file_exists($file)) {
        return $file;
    }
    return false;
}

/**
 * Get all file paths (original + thumbnails) for an attachment.
 *
 * @param int $attachment_id
 * @return array
 */
function imgboost_get_all_attachment_paths($attachment_id) {
    $paths = [];
    $main_file = imgboost_get_attachment_path($attachment_id);

    if (!$main_file) {
        return $paths;
    }

    $paths['full'] = $main_file;
    $dir = dirname($main_file);
    $metadata = wp_get_attachment_metadata($attachment_id);

    if (!empty($metadata['sizes'])) {
        foreach ($metadata['sizes'] as $size_name => $size_data) {
            $size_path = $dir . '/' . $size_data['file'];
            if (file_exists($size_path)) {
                $paths[$size_name] = $size_path;
            }
        }
    }

    return $paths;
}

/**
 * Check if an attachment has already been optimized.
 *
 * @param int $attachment_id
 * @return bool
 */
function imgboost_is_optimized($attachment_id) {
    $status = get_post_meta($attachment_id, '_imgboost_status', true);
    return $status === 'optimized';
}
