<?php
/**
 * Job runner for bulk conversion processing.
 *
 * @package STWP
 * @since 1.1.0
 */

namespace STWP;

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access not allowed.' );
}

/**
 * Job_Runner class handles batch processing of conversions.
 *
 * @since 1.0.0
 */
class Job_Runner {

	/**
	 * Batch size for processing attachments.
	 *
	 * @since 1.0.0
	 * @var int
	 */
	const BATCH_SIZE = 5;

	/**
	 * Initialize job runner hooks.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function init() {
		\add_action( 'stwp_process_batch', array( __CLASS__, 'process_batch' ) );
	}

	/**
	 * Process a batch of attachments.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function process_batch() {
		if ( ! \get_option( 'stwp_bulk_running' ) ) {
			return;
		}

		$queue = \get_option( 'stwp_bulk_queue', array() );
		if ( empty( $queue ) ) {
			\update_option( 'stwp_bulk_running', false );
			return;
		}

		$batch = \array_splice( $queue, 0, self::BATCH_SIZE );
		\update_option( 'stwp_bulk_queue', $queue );

		foreach ( $batch as $attachment_id ) {
			self::process_attachment( $attachment_id );
		}

		\wp_schedule_single_event( \time() + 10, 'stwp_process_batch' );
	}

	/**
	 * Process a single attachment conversion.
	 *
	 * @since 1.0.0
	 * @param int $id Attachment ID.
	 * @return void
	 */
	protected static function process_attachment( $id ) {
		$file = \get_attached_file( $id );
		if ( ! $file || ! \file_exists( $file ) ) {
			Progress::add_error( $id, 'File missing' );
			return;
		}

		$upload = array(
			'file' => $file,
			'url'  => \wp_get_attachment_url( $id ),
			'type' => \get_post_mime_type( $id ),
		);

		$result = Converter::handle_upload( $upload );

		if ( $result['file'] !== $file ) {
			\update_attached_file( $id, $result['file'] );
			Progress::add_done( $id );
		} else {
			Progress::add_skipped( $id );
		}
	}
}
