<?php
/**
 * Collects Errors Trait
 *
 * Provides error collection functionality for validators.
 *
 * @package Sequensy\Validation\Concerns
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Validation\Concerns;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Trait CollectsErrors
 *
 * Shared error collection functionality for validators.
 */
trait CollectsErrors {

	/**
	 * Validation errors collected during validation.
	 *
	 * @var array
	 */
	private array $errors = array();

	/**
	 * Add an error to the errors collection.
	 *
	 * @param string $code    Error code.
	 * @param string $message Error message.
	 * @param array  $context Optional context data.
	 * @return void
	 */
	protected function add_error( string $code, string $message, array $context = array() ): void {
		$error = array(
			'code'    => $code,
			'message' => $message,
		);

		if ( ! empty( $context ) ) {
			$error['context'] = $context;
		}

		$this->errors[] = $error;
	}

	/**
	 * Get collected errors.
	 *
	 * @return array Array of error objects.
	 */
	public function get_errors(): array {
		return $this->errors;
	}

	/**
	 * Clear collected errors.
	 *
	 * @return void
	 */
	public function clear_errors(): void {
		$this->errors = array();
	}

	/**
	 * Check if there are any errors.
	 *
	 * @return bool True if errors exist.
	 */
	public function has_errors(): bool {
		return ! empty( $this->errors );
	}

	/**
	 * Merge errors from another source.
	 *
	 * @param array $errors Errors to merge.
	 * @return void
	 */
	protected function merge_errors( array $errors ): void {
		$this->errors = array_merge( $this->errors, $errors );
	}

	/**
	 * Get validation result.
	 *
	 * @return array Result with 'valid' and 'errors'.
	 */
	protected function get_result(): array {
		return array(
			'valid'  => empty( $this->errors ),
			'errors' => $this->errors,
		);
	}
}
