<?php
defined( 'ABSPATH' ) || die();

class Ecafe_Condition_Rules {
	public static $_instance = null;

	private $storage;

	public function __construct() {
		$this->storage = new Ecafe_Conditions_Data();
	}

	public static function get_instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	public function ec_get_templates_ids( $location ) {
		$templates = $this->get_templates_location( $location );
		return $templates;
	}

	public function get_templates_location( $location ) {
		$result = array();

		$ec_get_location_data = $this->storage->ec_get_location_data( $location );

		if ( empty( $ec_get_location_data ) ) {
			return $result;
		}

		foreach ( $ec_get_location_data as $template_id => $conditions ) {
			if ( ( $location == 'header' || $location == 'footer' ) && $conditions === 'entire' ) {
				$result[ $template_id ] = 10;
			} elseif ( $location == 'singular' ) {
				if ( get_post_type() === $conditions ) {
					$result[ $template_id ] = 10;
				}
			} elseif ( $location == 'archives' ) {
				if ( is_category() && in_array( 'category', $conditions ) ) {
					$result[ $template_id ] = 10;
				} elseif ( is_tag() && in_array( 'post_tag', $conditions ) ) {
					$result[ $template_id ] = 10;
				} elseif ( is_tax() ) {
					foreach ( $conditions as $tax ) {
						if ( is_tax( $tax ) ) {
							$result[ $template_id ] = 10;
							break;
						}
					}
				}
			} elseif ( $location == 'page404' && is_404() ) {
				$result[ $template_id ] = 10;
			}
		}
		asort( $result );

		return $result;
	}

	public function ec_get_location_type( $location ) {
		$templates_ids = $this->ec_get_templates_ids( $location );

		$template_ids = array();
		foreach ( $templates_ids as $templates_id => $priority ) {
			$template_ids[] = $templates_id;
		}

		return $template_ids;
	}
}

Ecafe_Condition_Rules::get_instance();
