<?php
/**
 * Image Boost — Bulk Optimizer
 * Handles batch processing of existing media library images.
 */

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

class ImgBoost_Bulk_Optimizer {

    /**
     * Process a batch of images.
     *
     * @param int    $batch_size Number of images to process per batch.
     * @param string $level      Compression level.
     * @return array             Results of the batch processing.
     */
    public static function process_batch($batch_size = null, $level = 'pro') {
        if ($batch_size === null) {
            $batch_size = (int) get_option('imgboost_batch_size', 5);
        }
        
        // Force batch size to 1 to guarantee we never hit 504 Gateway Timeout on slow servers.
        // The javascript will recursively call this until complete.
        $batch_size = 1;

        $ids = ImgBoost_Stats::get_unoptimized_ids($batch_size);

        if (empty($ids)) {
            return [
                'processed'  => 0,
                'remaining'  => 0,
                'complete'   => true,
                'results'    => [],
            ];
        }

        $results = [];

        foreach ($ids as $attachment_id) {
            $result = self::optimize_single($attachment_id, $level);
            $results[] = $result;
        }

        $remaining = ImgBoost_Stats::count_unoptimized();

        $imgboost_final_stats = ImgBoost_Stats::get_dashboard_stats();

        return [
            'processed'         => count($results),
            'remaining'         => $remaining,
            'complete'          => $remaining === 0,
            'results'           => $results,
            'total_saved_human' => $imgboost_final_stats['total_saved_human'],
        ];
    }

    /**
     * Optimize a single attachment (all sizes).
     *
     * @param int    $attachment_id
     * @param string $level
     * @return array
     */
    public static function optimize_single($attachment_id, $level = null) {
        if ($level === null) {
            $level = get_option('imgboost_compression_level', 'pro');
        }

        $file_path = imgboost_get_attachment_path($attachment_id);

        if (!$file_path || !file_exists($file_path)) {
            update_post_meta($attachment_id, '_imgboost_status', 'error');
            return [
                'id'      => $attachment_id,
                'status'  => 'error',
                'message' => __('File not found.', 'image-boost'),
            ];
        }

        if (!imgboost_is_optimizable($file_path)) {
            update_post_meta($attachment_id, '_imgboost_status', 'skipped');
            return [
                'id'      => $attachment_id,
                'status'  => 'skipped',
                'message' => __('File type not supported.', 'image-boost'),
            ];
        }
        
        // Ensure meta error is cleared so we can proceed
        delete_post_meta($attachment_id, '_imgboost_status');

        // Process all sizes via background engine synchronously for bulk
        ImgBoost_Background_Process::process_attachment($attachment_id);

        // Fetch new meta
        $status = get_post_meta($attachment_id, '_imgboost_status', true);
        if ($status === 'error') {
            return [
                'id'      => $attachment_id,
                'status'  => 'error',
                'message' => get_post_meta($attachment_id, '_imgboost_error', true),
            ];
        }

        $original_size = (int) get_post_meta($attachment_id, '_imgboost_original_size', true);
        $optimized_size = (int) get_post_meta($attachment_id, '_imgboost_optimized_size', true);
        $savings = get_post_meta($attachment_id, '_imgboost_savings', true);

        return [
            'id'            => $attachment_id,
            'status'        => 'optimized',
            'title'         => get_the_title($attachment_id),
            'original_size' => imgboost_format_bytes($original_size),
            'new_size'      => imgboost_format_bytes($optimized_size),
            'savings'       => $savings . '%',
            'level'         => $level,
            'thumbnail'     => wp_get_attachment_image_url($attachment_id, 'thumbnail'),
        ];
    }
}
