<?php
/**
 * Progress tracking for bulk conversion.
 *
 * @package STWP
 * @since 1.1.0
 */

namespace STWP;

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

/**
 * Progress class tracks bulk conversion progress.
 *
 * @since 1.0.0
 */
class Progress {

	/**
	 * Mark an attachment as completed.
	 *
	 * @since 1.0.0
	 * @param int $id Attachment ID.
	 * @return void
	 */
	public static function add_done( $id ) {
		$done   = \get_option( 'stwp_bulk_done', array() );
		$done[] = $id;
		\update_option( 'stwp_bulk_done', $done, false );
	}

	/**
	 * Add an error for an attachment.
	 *
	 * @since 1.0.0
	 * @param int    $id  Attachment ID.
	 * @param string $msg Error message.
	 * @return void
	 */
	public static function add_error( $id, $msg ) {
		$errors       = \get_option( 'stwp_bulk_errors', array() );
		$errors[ $id ] = $msg;
		\update_option( 'stwp_bulk_errors', $errors, false );
	}

	/**
	 * Mark an attachment as skipped.
	 *
	 * @since 1.0.0
	 * @param int $id Attachment ID.
	 * @return void
	 */
	public static function add_skipped( $id ) {
		self::add_done( $id );
	}

	/**
	 * Get conversion statistics.
	 *
	 * @since 1.0.0
	 * @return array Statistics array with total, done, left, errors.
	 */
	public static function stats() {
		$done_count  = \count( \get_option( 'stwp_bulk_done', array() ) );
		$queue_count = \count( \get_option( 'stwp_bulk_queue', array() ) );
		$error_count = \count( \get_option( 'stwp_bulk_errors', array() ) );

		return array(
			'total'  => $done_count + $queue_count,
			'done'   => $done_count,
			'left'   => $queue_count,
			'errors' => $error_count,
		);
	}
}
