<?php

/**
 * Options
 *
 * @package Dotspice
 * @version 1.3.0
 */


/**
 * This function will return custom option with default value.
 *
 * @param  string $selector The field name or key
 * @param  string $default  The default value
 * @return mixed
 */
function dotspice_get_theme_option($field_name, $default = '')
{
	if (class_exists('acf_pro')) {
		$value = get_field($field_name, 'options');

		if (dotspice_value_exists($value)) {
			return $value;
		} else {
			return $default;
		}
	} else {
		return $default;
	}
}


/**
 * This function will print custom option with default value.
 *
 * @param  string $selector The field name or key
 * @param  string $default  The default value
 * @return mixed
 */
function dotspice_the_theme_option($field_name, $default = '')
{
	echo dotspice_get_theme_option($field_name, $default);
}


/**
 * This function will return custom option with depending on taxonomies.
 *
 * @param  string $selector The field name or key
 * @return mixed
 */
function dotspice_get_theme_settings($field_name)
{
	$field_value = get_field($field_name, get_queried_object());

	if (!$field_value) {

		// Shop
		if (class_exists('woocommerce')) {

			// Product
			if (is_product()) {
				$product_categories = get_the_terms('', 'product_cat');

				if (!empty($product_categories)) {
					$field_value = get_field($field_name, $product_categories[0]);
				}
			}

			// Product Category
			else if (is_product_category()) {
				$parent_categories = get_ancestors(get_queried_object()->term_taxonomy_id, 'product_cat');

				if (!empty($parent_categories)) {
					$field_value = get_field($field_name, 'product_cat_' . $parent_categories[0]);
				}
			}

			// Shop Pages
			if (!$field_value && (is_shop() || is_product() || is_product_category())) {
				$field_value = get_field($field_name, wc_get_page_id('shop'));
			}
		}

		// Post
		if (is_singular('post')) {
			$post_categories = get_the_category(get_queried_object());

			if (!empty($post_categories)) {
				$field_value = get_field($field_name, $post_categories[0]);
			}

			// Blog Posts Page
			if (!$jumbotron_bg) {
				$jumbotron_bg = get_field('jumbotron_bg', get_option('page_for_posts'));
			}
		}
	}

	if (!$field_value) {
		$field_value = get_field($field_name, 'options');
	}

	return $field_value;
}


/**
 * If ACF disabled or can not be found
 */
function dotspice_acf_alternatives()
{
	if (!class_exists('acf_pro')) {
		if (!function_exists('get_field')) {
			function get_field()
			{
				return false;
			}
		}
		if (!function_exists('the_field')) {
			function the_field()
			{
				return false;
			}
		}
		if (!function_exists('get_sub_field')) {
			function get_sub_field()
			{
				return false;
			}
		}
		if (!function_exists('the_sub_field')) {
			function the_sub_field()
			{
				return false;
			}
		}
		if (!function_exists('have_rows')) {
			function have_rows()
			{
				return false;
			}
		}
	}
}
add_action('template_redirect', 'dotspice_acf_alternatives');
