<?php
/**
 * Image Boost — Background Process
 * Handles asynchronous background optimization for images.
 */

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

class ImgBoost_Background_Process {

    public static function init() {
        add_action('imgboost_async_optimize_single', [__CLASS__, 'process_attachment']);
    }

    /**
     * Process an attachment in the background.
     *
     * @param int $attachment_id
     */
    public static function process_attachment($attachment_id) {
        $mime = get_post_mime_type($attachment_id);
        $supported = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

        if (!in_array($mime, $supported)) {
            return;
        }

        $level = get_option('imgboost_compression_level', 'pro');
        $file_path = imgboost_get_attachment_path($attachment_id);

        if (!$file_path || !file_exists($file_path)) {
            // Cannot find file, mark error
            update_post_meta($attachment_id, '_imgboost_status', 'error');
            update_post_meta($attachment_id, '_imgboost_error', __('File missing during background process.', 'image-boost'));
            return;
        }

        // Avoid OOM
        wp_raise_memory_limit('image');

        // Capture original size BEFORE compression
        $original_size = filesize($file_path);
        update_post_meta($attachment_id, '_imgboost_original_size', $original_size);

        $metadata = wp_get_attachment_metadata($attachment_id);

        // Process full size
        self::process_single_image($attachment_id, $file_path, 'full', $level);

        // Process thumbs
        $dir = dirname($file_path);

        if (!empty($metadata['sizes'])) {
            foreach ($metadata['sizes'] as $size_name => $size_data) {
                $size_path = $dir . '/' . $size_data['file'];
                if (file_exists($size_path)) {
                    self::process_single_image($attachment_id, $size_path, $size_name, $level);
                    // Add 150ms delay between thumbnails to give CPU breathing room for other requests
                    usleep(150000); 
                }
            }
        }

        self::imgboost_update_attachment_meta($attachment_id, $level);
    }

    /**
     * Extracted from previous Auto_Optimizer for reuse
     */
    public static function process_single_image($attachment_id, $file_path, $size_name, $level) {
        if ($size_name === 'full') {
            ImgBoost_Backup::create($file_path, $attachment_id);
        } else {
            if (get_option('imgboost_backup_enabled', 1)) {
                $upload_dir = wp_get_upload_dir();
                $norm_basedir = wp_normalize_path($upload_dir['basedir']);
                $norm_filepath = wp_normalize_path($file_path);
                
                $relative = preg_replace('/^' . preg_quote($norm_basedir, '/') . '/i', '', $norm_filepath);
                $relative = preg_replace('/\?.*/', '', $relative);
                $backup_path = wp_normalize_path(IMGBOOST_BACKUP_DIR . ltrim($relative, '/\\'));
                $backup_dir = dirname($backup_path);
                if (!file_exists($backup_dir)) {
                    wp_mkdir_p($backup_dir);
                }
                if (!file_exists($backup_path)) {
                    copy($file_path, $backup_path);
                }
            }
        }

        $original_size = filesize($file_path);
        $format_original = pathinfo($file_path, PATHINFO_EXTENSION);

        $result = ImgBoost_Compressor::compress($file_path, $level);

        if (is_wp_error($result)) {
            update_post_meta($attachment_id, '_imgboost_status', 'error');
            update_post_meta($attachment_id, '_imgboost_error', $result->get_error_message());
            return $result;
        }

        $webp_size = null;
        if (get_option('imgboost_webp_enabled', 1)) {
            $webp_result = ImgBoost_Converter::to_webp($file_path, $level);
            if (!is_wp_error($webp_result)) {
                $webp_size = $webp_result['size'];
                if ($size_name === 'full') {
                    update_post_meta($attachment_id, '_imgboost_webp_path', $webp_result['path']);
                }
            }
        }

        ImgBoost_DB::log_optimization([
            'attachment_id'     => $attachment_id,
            'file_path'         => $file_path,
            'size_name'         => $size_name,
            'original_size'     => $result['original_size'],
            'optimized_size'    => $result['optimized_size'],
            'savings_percent'   => $result['savings_percent'],
            'compression_level' => $level,
            'format_original'   => $format_original,
            'webp_size'         => $webp_size,
        ]);
        
        return true;
    }

    private static function imgboost_update_attachment_meta($attachment_id, $level) {
        $file_path = imgboost_get_attachment_path($attachment_id);
        if (!$file_path) return;

        $original_size = (int) get_post_meta($attachment_id, '_imgboost_original_size', true);
        if ($original_size === 0) {
            $backup_path = get_post_meta($attachment_id, '_imgboost_backup_path', true);
            $original_size = $backup_path && file_exists(wp_normalize_path($backup_path)) ? filesize(wp_normalize_path($backup_path)) : 0;
        }

        $optimized_size = filesize($file_path);

        // NATIVE BANDWIDTH SAVINGS: Use Next-Gen size if available for Dashboard stats
        $webp_path = get_post_meta($attachment_id, '_imgboost_webp_path', true);
        if ($webp_path && file_exists(wp_normalize_path($webp_path))) {
            $webp_size = filesize(wp_normalize_path($webp_path));
            if ($webp_size > 0 && $webp_size < $optimized_size) {
                $optimized_size = $webp_size;
            }
        }

        // We only calculate actual savings here.
        if ($optimized_size >= $original_size) {
            $optimized_size = $original_size;
        }

        $savings = $original_size > 0
            ? round((($original_size - $optimized_size) / $original_size) * 100, 2)
            : 0;

        // Check if error
        $status = get_post_meta($attachment_id, '_imgboost_status', true);
        if ($status !== 'error') {
            update_post_meta($attachment_id, '_imgboost_status', 'optimized');
            update_post_meta($attachment_id, '_imgboost_level', $level);
            update_post_meta($attachment_id, '_imgboost_original_size', $original_size);
            update_post_meta($attachment_id, '_imgboost_optimized_size', $optimized_size);
            update_post_meta($attachment_id, '_imgboost_savings', $savings);
            
            // Clean cache
            wp_cache_delete('imgboost_count_unoptimized', 'imgboost');
            wp_cache_delete('imgboost_stats_' . $attachment_id, 'imgboost');
        }
    }
}
