<?php

namespace GravityKit\GravityActions\Utils;

use GFCommon;

/**
 * Class Form.
 *
 * @since   1.4
 *
 * @package GravityKit\GravityActions\Utils
 */
class Form {
	/**
	 * Given a form determine which are the calculation fields.
	 *
	 * @since 1.4
	 *
	 * @param array|int|string $form Form Array or ID.
	 *
	 * @return array
	 */
	public static function get_calculation_fields( $form ): array {
		if ( is_numeric( $form ) ) {
			$form = \GFAPI::get_form( $form );
		}

		if ( ! static::has_calculation_field( $form ) ) {
			return [];
		}

		$fields = [];

		foreach ( $form['fields'] as $field ) {
			/* @var $field \GF_Field */
			if ( ! $field->has_calculation() ) {
				continue;
			}

			$fields[] = $field;
		}

		return $fields;
	}

	/**
	 * Given a form determine which are the formula fields.
	 *
	 * @since 1.4
	 *
	 * @param array|int|string $form Form Array or ID.
	 *
	 * @return array
	 */
	public static function get_formula_fields( $form ): array {
		if ( is_numeric( $form ) ) {
			$form = \GFAPI::get_form( $form );
		}

		$calculation_fields = static::get_calculation_fields( $form );
		if ( empty( $calculation_fields ) ) {
			return [];
		}

		$fields = [];

		foreach ( $calculation_fields as $field ) {
			$type = $field->get_input_type();

			if ( $type !== 'number' ) {
				continue;
			}

			if ( ! $field->calculationFormula ) {
				continue;
			}
			$ids = GFCommon::get_field_ids_from_formula_tag( $field->calculationFormula );

			$fields = array_merge( $fields, $ids );
		}

		return $fields;
	}

	public static function get_calculation_fields_by_formula_field( $form, $formula_field ): array {
		if ( is_numeric( $form ) ) {
			$form = \GFAPI::get_form( $form );
		}

		$calculation_fields = static::get_calculation_fields( $form );
		if ( empty( $calculation_fields ) ) {
			return [];
		}

		$fields = [];
		foreach ( $calculation_fields as $field ) {
			$type = $field->get_input_type();

			if ( $type !== 'number' ) {
				continue;
			}

			if ( ! $field->calculationFormula ) {
				continue;
			}
			$ids = GFCommon::get_field_ids_from_formula_tag( $field->calculationFormula );

			if ( ! in_array( $formula_field, $ids ) ) {
				continue;
			}

			$fields[] = $field->id;
		}

		return $fields;
	}

	/**
	 * Given a form determine if there are any calculation fields.
	 *
	 * @since 1.4
	 *
	 * @param array|int|string $form Form Array or ID.
	 *
	 * @return bool
	 */
	public static function has_calculation_field( $form ): bool {
		if ( is_numeric( $form ) ) {
			$form = \GFAPI::get_form( $form );
		}

		if ( empty( $form ) ) {
			return false;
		}

		if ( ! class_exists( '\GFFormDisplay' ) ) {
			require_once GFCommon::get_base_path() . '/form_display.php';
		}

		return \GFFormDisplay::has_calculation_field( $form ) ;
	}
}