<?php

namespace Jet_Menu\Modules\Dynamic_Visibility;

use Jet_Menu\Modules\Dynamic_Visibility\Conditions\Registry;

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

class Checker {

	protected $conditions = array();

	public function __construct() {
		$this->register_default_conditions();
	}

	protected function register_default_conditions() {
		$registry = new Registry();
		$this->conditions = $registry->all();
	}

	public function check( $dv_settings, $context ) {

		$dv_settings = is_array( $dv_settings ) ? $dv_settings : array();

		$relation = isset( $dv_settings['relation'] ) ? $dv_settings['relation'] : 'AND';
		$relation = in_array( $relation, array( 'AND', 'OR' ), true ) ? $relation : 'AND';

		$rules = isset( $dv_settings['rules'] ) ? $dv_settings['rules'] : array();
		$rules = is_array( $rules ) ? $rules : array();

		// enabled but no rules => "no match"
		if ( empty( $rules ) ) {
			return false;
		}

		$results = array();

		foreach ( $rules as $rule ) {

			$rule = is_array( $rule ) ? $rule : array();

			$type = isset( $rule['type'] ) ? $rule['type'] : '';
			if ( ! $type || ! isset( $this->conditions[ $type ] ) ) {
				$results[] = false;
				continue;
			}

			$results[] = $this->conditions[ $type ]->check( $rule, $context );
		}

		if ( 'AND' === $relation ) {
			return ! in_array( false, $results, true );
		}

		return in_array( true, $results, true );
	}
}
