<?php

namespace Clonable\Controllers;

use Clonable\Helpers\Json;
use Clonable\Helpers\MultiCurrency as MultiCurrencyHelper;
use Clonable\Models\MultiCurrency;
use Clonable\Traits\Validation;
use Clonable\Views\MultiCurrencyView;

class MultiCurrencyController extends Controller {
	use Validation;

	//<editor-fold desc="Singleton pattern">
	private static $instance = null;

	public static function get_instance() {
		if (self::$instance == null) {
			self::$instance = new MultiCurrencyController();
		}
		return self::$instance;
	}

	private function __construct() {
		// Keep constructor private
		$this->view = new MultiCurrencyView();
	}
	//</editor-fold>

	public function validate($request) {
		$this->validate_fields($request, MultiCurrency::$fields);
	}

	public function clonable_enable_curcy_plugin_support_validate($input)
	{
		return $this->validate_checkbox($input, MultiCurrency::CURCY_SUPPORT_SETTING);
	}

	public function clonable_aelia_currency_support_validate($input)
	{
		return $this->validate_checkbox($input, MultiCurrency::AELIA_SUPPORT_SETTING);
	}

	public function clonable_multi_currency_by_clone_validate($input)
	{
		if (empty($input)) {
			return $input;
		}
		$old_input = get_option(MultiCurrency::MULTI_CURRENCY_BY_CLONE);
		$json_input = Json::handle_input($input);
		$available_currencies = MultiCurrencyHelper::get_all_currencies();

		foreach ($json_input as $custom_currency) {
			if (empty($custom_currency->currency) || !in_array($custom_currency->currency, $available_currencies)) {
				add_settings_error(MultiCurrency::MULTI_CURRENCY_BY_CLONE, 'err_invalid_domain', "You've entered a currency that is not supported.");
				return $old_input;
			}
		}

		if (empty($json_input)) {
			add_settings_error(MultiCurrency::MULTI_CURRENCY_BY_CLONE, 'err_no_input', "No input was given for the multi currency per clone setting");
			return null;
		}
		return Json::handle_output(json_encode($json_input));
	}

	public function clonable_multi_currency_force_per_clone_validate($input)
	{
		return $this->validate_checkbox($input, MultiCurrency::MULTI_CURRENCY_FORCE_PER_CLONE);
	}
}