<?php
/**
 * Save settings ajax action
 *
 * @author        Alex Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
 * @copyright (c) 21.09.2019, Webcraftic
 * @version       1.0
 */

// Exit if accessed directly
if( !defined('ABSPATH') ) {
	exit;
}

/**
 * Ajax action for save plugin settings.
 *
 * @author Alexander Kovalev <alex.kovalevv@gmail.com>
 * @since  1.2.3
 */
function wam_add_dns_prefetch_action()
{
	check_ajax_referer('wam_add_dns_prefetch');

	if( !current_user_can('manage_options') ) {
		wp_send_json_error([
			'error_message_title' => __('Domain added failed!', 'gonzales'),
			'error_message_content' => __('You don\'t have enough capability to edit this information.', 'gonzales')
		]);
	}
	$domain = WGZ_Plugin::app()->request->post('domain');

	if( !empty($domain) ) {
		$urls_prefetch = WCL_Plugin::app()->getPopulateOption('urls_prefetch');

		if( !empty($urls_prefetch) ) {
			$urls_prefetch = preg_split('/\r\n|\n|\r/', $urls_prefetch);
			$urls_prefetch = array_map(function ($value) {
				return trim(rtrim($value));
			}, $urls_prefetch);
			$urls_prefetch = array_filter($urls_prefetch, function ($value) {
				return !is_null($value) && $value !== '';
			});
		} else {
			$urls_prefetch = [];
		}

		$urls_prefetch[] = $domain;
		$urls_prefetch = array_unique($urls_prefetch);

		WCL_Plugin::app()->updatePopulateOption('urls_prefetch', implode("\r\n", $urls_prefetch));

		// Flush cache for all cache plugins
		WCL_Helper::flush_cache();

		$save_message_title = __('Domain added successfully!', 'gonzales');
		$save_message_content = sprintf(__('Domain %s c has been successfully added to the dns prefetch list. You can see the list of dns prefetch in the Clearfy plugin settings -> Performance -> Preload', 'gonzales'), $domain);

		wp_send_json_success([
			'save_massage_title' => $save_message_title,
			'save_message_content' => $save_message_content
		]);
	}

	wp_send_json_error([
		'error_message_title' => __('Domain added failed!', 'gonzales'),
		'error_message_content' => __('An unknown error has occurred.', 'gonzales')
	]);
}

add_action('wp_ajax_nopriv_wam-add-to-dns-prefetch', 'wam_add_dns_prefetch_action');
add_action('wp_ajax_wam-add-to-dns-prefetch', 'wam_add_dns_prefetch_action');