<?php

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

/**
 * Cross-field validation for the canonical Lead Form schema.
 */
class Niwa_AI_Lead_Form_Validator {

	/**
	 * Validate question requirements and conditional branch references.
	 *
	 * @param array $schema Sanitized Lead Form schema.
	 * @return array{success:bool,error?:string,errors?:array}
	 */
	public static function validate( $schema ) {
		if ( ! is_array( $schema ) ) {
			return array( 'success' => false, 'error' => 'Lead Form schema mora biti objekat.' );
		}

		$questions = array();
		$errors    = array();
		foreach ( isset( $schema['steps'] ) && is_array( $schema['steps'] ) ? $schema['steps'] : array() as $step ) {
			foreach ( isset( $step['questions'] ) && is_array( $step['questions'] ) ? $step['questions'] : array() as $question ) {
				$id = isset( $question['id'] ) ? (string) $question['id'] : '';
				if ( '' === $id ) {
					$errors[] = 'Svako Lead Form pitanje mora imati id.';
					continue;
				}
				$questions[ $id ] = $question;
			}
		}

		if ( ! empty( $schema['enabled'] ) && empty( $questions ) ) {
			$errors[] = 'Aktivna Lead Form mora imati bar jedno pitanje.';
		}

		foreach ( $questions as $question_id => $question ) {
			if ( '' === trim( isset( $question['label'] ) ? (string) $question['label'] : '' ) ) {
				$errors[] = 'Pitanje ' . $question_id . ' mora imati label.';
			}

			$type = isset( $question['type'] ) ? (string) $question['type'] : 'text';
			if ( in_array( $type, array( 'choice_single', 'choice_multi' ), true ) && empty( $question['options'] ) ) {
				$errors[] = 'Choice pitanje ' . $question_id . ' mora imati bar jednu opciju.';
			}

			$conditional = isset( $question['conditional'] ) && is_array( $question['conditional'] ) ? $question['conditional'] : array();
			if ( empty( $conditional['enabled'] ) ) {
				continue;
			}

			foreach ( isset( $conditional['rules'] ) && is_array( $conditional['rules'] ) ? $conditional['rules'] : array() as $rule ) {
				$target = isset( $rule['next_question'] ) ? (string) $rule['next_question'] : '';
				if ( Niwa_AI_Lead_Form_Schema::COMPLETE_SENTINEL !== $target && ! isset( $questions[ $target ] ) ) {
					$errors[] = 'Conditional rule iz pitanja ' . $question_id . ' pokazuje na nepostojece pitanje ' . $target . '.';
				}
			}

			foreach ( isset( $conditional['llm_candidates'] ) && is_array( $conditional['llm_candidates'] ) ? $conditional['llm_candidates'] : array() as $target ) {
				$target = (string) $target;
				if ( Niwa_AI_Lead_Form_Schema::COMPLETE_SENTINEL !== $target && ! isset( $questions[ $target ] ) ) {
					$errors[] = 'LLM candidate iz pitanja ' . $question_id . ' pokazuje na nepostojece pitanje ' . $target . '.';
				}
			}
		}

		if ( ! empty( $errors ) ) {
			return array(
				'success' => false,
				'error'   => implode( ' ', array_values( array_unique( $errors ) ) ),
				'errors'  => array_values( array_unique( $errors ) ),
			);
		}

		return array( 'success' => true );
	}
}
