<?php
/**
 * TamRank WebP Bulk Processor
 */

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

class TamRank_WebP_Bulk {
    private $generator;

    public function __construct() {
        $this->generator = new TamRank_WebP_Generator();
        add_action('wp_ajax_tamrank_generate_webp_batch', array($this, 'ajax_generate_batch'));
    }

    public function ajax_generate_batch() {
        check_ajax_referer('tamrank_webp_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => tamrank__('error_permission_denied', 'You do not have permission for this action.'), 'code' => 'permission_denied'));
        }

        $offset = isset($_POST['offset']) ? (int) $_POST['offset'] : 0;
        $limit = isset($_POST['limit']) ? max(1, (int) $_POST['limit']) : 25;

        $attachments = get_posts(array(
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'posts_per_page' => $limit,
            'offset' => $offset,
            'fields' => 'ids',
            'post_mime_type' => 'image'
        ));

        $settings = tamrank_webp_get_settings();
        $processed = array();

        foreach ($attachments as $attachment_id) {
            if (get_post_mime_type($attachment_id) === 'image/svg+xml') {
                continue;
            }
            // Skip attachments already converted (full-size twin on disk) so a
            // re-run is cheap instead of re-encoding the whole library.
            if ($this->has_webp_twin($attachment_id)) {
                continue;
            }
            $res = $this->generator->generate_for_attachment($attachment_id, $settings);
            if (!empty($res)) {
                update_post_meta($attachment_id, '_tamrank_webp_generated', 1);
                update_post_meta($attachment_id, '_tamrank_webp_last_generated', time());
                $processed[] = $attachment_id;
            }
        }

        wp_send_json_success(array(
            'processed' => $processed,
            'next_offset' => $offset + $limit,
            'done' => count($attachments) < $limit
        ));
    }

    /**
     * True when the full-size .webp twin already exists on disk.
     */
    private function has_webp_twin($attachment_id)
    {
        $file = get_attached_file($attachment_id);
        if (!$file) {
            return false;
        }
        $info = pathinfo($file);
        if (empty($info['dirname']) || empty($info['filename'])) {
            return false;
        }
        return file_exists($info['dirname'] . '/' . $info['filename'] . '.webp');
    }
}
