<?php
defined('ABSPATH') or die("you do not have acces to this page!");
/**
 * Drop in for TCF integration
 */
$debug = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? time() : '';

/**
 * Conditionally initialize
 */
add_action('plugins_loaded', 'cmplz_tcf_init', 10);
add_action( 'complianz_after_save_wizard_option', 'cmplz_tcf_after_save_cookie_settings_option', 10, 4 );

function cmplz_tcf_init() {
	if ( cmplz_iab_is_enabled() ) {
		add_action( 'admin_init', 'cmplz_tcf_change_settings' );
		add_shortcode( 'cmplz-tcf-vendors', 'cmplz_tcf_vendors' );
		add_action( 'wp_enqueue_scripts', 'cmplz_tcf_enqueue_assets' , PHP_INT_MAX);
		add_filter( 'cmplz_tcf_active', 'cmplz_iab_is_enabled' );
		add_filter( 'cmplz_fields_load_types', 'cmplz_tcf_edit_cookiebanner_settings', 20 );
		add_filter( 'cmplz_cookiebanner_settings', 'cmplz_tcf_add_link_to_banner', 10, 2 );
		add_filter( 'cmplz_dynamic_categories_ajax', 'cmplz_cookiebanner_preview_settings', 10, 2 );
		add_filter( 'cmplz_cookiebanner_tabs', 'cmplz_tcf_cookiebanner_tabs');
		add_filter( 'cmplz_cookie_policy_snapshot_html' , 'cmplz_tcf_adjust_cookie_policy_snapshot_html' );
		add_filter( 'cmplz_regions_for_consenttype', 'cmplz_tcf_regions_for_consenttype', 10, 2 );
		add_filter( 'cmplz_cookiebanner_settings', 'cmplz_tcf_ajax_loaded_banner_data', 10, 2);
	}
}

/**
 * EU changes to consenttype tcf
 *
 * @param array $regions
 * @param string $consenttype
 *
 * @return array
 */

function cmplz_tcf_regions_for_consenttype( $regions, $consenttype ) {

	if ( $consenttype === 'tcf' ) {
		$regions = get_regions_for_consent_type('optin');
	}

	return $regions;
}

/**
 * On activation set some new settings in cookiebanner
 */
function cmplz_tcf_change_settings()
{
	if (!current_user_can('manage_options')) return;
	if ( !get_option("cmplz_tcf_initialized") ) {
		//set the color scheme
		$color_schemes = cmplz_banner_color_schemes();
		$color_scheme = $color_schemes['tcf'];

		//set banner to center variant
		$banners = cmplz_get_cookiebanners();
		if ( $banners ) {
			foreach ( $banners as $banner_item ) {
				$banner = new CMPLZ_COOKIEBANNER( $banner_item->ID );
				$banner->message_optin = cmplz_get_default_banner_text();
				$banner->soft_cookiewall = false;
				$banner->banner_width = '672';
				$banner->dismiss = __("Continue without consent", "complianz-gdpr");
				$banner->hide_revoke = false;
				foreach ($color_scheme as $fieldname => $value ){
					$banner->{$fieldname} = $value;
				}
				$banner->view_preferences = __('Manage options', 'complianz-gdpr');
				if ($banner->use_categories !== 'hidden') {
					$banner->use_categories = 'hidden';
				}
				if ($banner->use_categories_optinstats !== 'hidden') {
					$banner->use_categories_optinstats = 'hidden';
				}
				$banner->save();
			}
		}

		//set default values for the TCF features.
		cmplz_update_option('wizard', 'tcf_purposes', cmplz_tcf_get('purposes', true) );
		cmplz_update_option('wizard', 'tcf_specialPurposes', cmplz_tcf_get('specialPurposes', true) );
		cmplz_update_option('wizard', 'tcf_features', cmplz_tcf_get('features', true) );

		//deactivate a/b testing
		cmplz_update_option( 'settings', 'a_b_testing', false );

		/**
		 * Send an email
		 * but only once
		 */
		if ( !get_option('cmplz_tcf_mail_sent') ) {
			$from = get_option('admin_email');
			$site_url = site_url();
			$subject = "TCF enabled on ".$site_url;
			$to      = "support@complianz.io";
			$headers = array();
			$message = "TCF was enabled on $site_url";
			add_filter( 'wp_mail_content_type', function ( $content_type ) {return 'text/html';} );
			$headers[] = "Reply-To: $from <$from>" . "\r\n";
			wp_mail( $to, $subject, $message, $headers );
			remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
			update_option( 'cmplz_tcf_mail_sent', true );
		}

		update_option("cmplz_tcf_initialized", true);
	}
}

/**
 * Generate default banner text
 * @return string
 */
function cmplz_get_default_banner_text(){
	$global = false;
	$str = '<p>'.__("To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.", "complianz-gdpr").'</p>';
	$str .= '<p>'.__("Click below to consent to the above or make granular choices.", "complianz-gdpr");
	if ($global) {
		$str .= '&nbsp;'.__("Your choices will be applied globally.", "complianz-gdpr");
        $str .= '&nbsp;'.__("This means that your settings will be available on other sites that set your choices globally.", "complianz-gdpr");
	} else {
		$str .= '&nbsp;'.__("Your choices will be applied to this site only.", "complianz-gdpr");

	}
	$str .= '&nbsp;'.__("You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.", "complianz-gdpr").
	'</p>';
	return $str;
}

/**
 * Get items from the most recent vendor list, and cache it for one month
 * @param string $fieldname
 * @param bool $default_on
 * @return array
 */

function cmplz_tcf_get($fieldname, $default_on = false){

	//user locale
	$locale = substr(get_user_locale(), 0, 2);
	$existing_languages = array('bg', 'ca', 'cs', 'da', 'de', 'el', 'es', 'et', 'fi', 'fr', 'hr', 'hu', 'it', 'ja', 'lt', 'lv', 'mt', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'tr', 'zh',);
	if ( !in_array($locale, $existing_languages)) {
		$locale = 'en';
	}
	$items = get_transient("cmplz_tcf_".$locale."_".$fieldname);
	if ( !$items ) {
		//get the purposes
		if ($locale === 'en' ) {
			$url = "https://complianz.io/cmp/vendorlist/vendor-list.json";
		} else {
			$url = "https://complianz.io/cmp/vendorlist/purposes-$locale.json";
		}
		$response = wp_remote_get($url);

		if ( is_wp_error( $response ) ){
			error_log("error retrieving TCF data");
			return array();
		} else {
			if (isset($response["response"]['code']) && $response["response"]['code'] === 200 && isset($response["body"])) {
				$json = json_decode($response["body"]);
				$remote_items = $json->{$fieldname};
				$items = array();
				foreach ($remote_items as $remote_item ) {
					$items[$remote_item->id] = $remote_item->name;
				}

				set_transient("cmplz_tcf_".$locale."_".$fieldname, $items, MONTH_IN_SECONDS);
			}
		}


	}

	//for default value purposes
	if ( $default_on ) {
		foreach ($items as $key => $item ){
			$items[$key] = 1;
		}
	}

	return $items;
}

/**
 * Add TCF section to WIZARD
 * @param $steps
 *
 * @return mixed
 */
function cmplz_tcf_add_step($steps){
	if ( cmplz_iab_is_enabled() ) {

		$steps['wizard'][ STEP_COOKIES ]['sections'][7] = array(
			'title' => __( 'Transparency Consent Framework', 'complianz-gdpr' ),
			'intro' => __( 'The below questions will help you configure a vendor list of your choosing. Only vendors that adhere to the purposes and special features you configure will be able to serve ads.',
					'complianz-gdpr' )
			           . cmplz_read_more( 'https://complianz.io/tcf/' ),
		);
	}
	return $steps;
}
add_filter( 'cmplz_steps', 'cmplz_tcf_add_step' );

/**
 * If the region is a tcf region, force some settings
 * @param array $data
 * @param CMPLZ_COOKIEBANNER $banner
 *
 * @return mixed
 */

function cmplz_tcf_ajax_loaded_banner_data($data, $banner){
	$tcf_regions = cmplz_tcf_regions();
	$current_region = $data['region'];
	if ( in_array($current_region, $tcf_regions ) ) {
		$data['position'] = 'center';
		$data['theme'] = 'minimal';
		$data['message_optin'] = cmplz_get_default_banner_text();
	}
	$data['tcf_regions'] = $tcf_regions;
	return $data;
}

/**
 * Get regions where the TCF applies
 * As canada may have optin, we add Canada to the gdpr regions as well in that case
 * @return array
 */
function cmplz_tcf_regions(){
	$tcf_regions = array('eu', 'uk');

	if ( cmplz_site_shares_data()
	     && cmplz_get_value( 'sensitive_information_processed' ) === 'yes'
	) {
		$tcf_regions[] = 'ca';
	}

	return $tcf_regions;
}

/**
 * Change settings options
 */

function cmplz_tcf_edit_cookiebanner_settings($fields){
	unset($fields['hide_revoke']);

	$fields['a_b_testing']['disabled'] = true;
	$fields['tagmanager_categories']['step'] = array( 'tcf' );
	$fields['category_functional']['step'] = array( 'tcf' );
	$fields['category_prefs']['step'] = array( 'tcf' );
	$fields['category_stats']['step'] = array( 'tcf' );
	$fields['category_all']['step'] = array( 'tcf' );
	$fields['readmore_optin']['step'] = array( 'tcf' );
	$fields['readmore_impressum']['step'] = array( 'tcf' );
	$fields['dismiss']['step'] = array( 'tcf' );

	//hide this, so the banner preview still works, but is not changeable.
	$fields['message_optin']['condition'] = array( 'hidden' => true );
	unset($fields['color_scheme']);
	$fields['use_categories']['condition'] = array( 'hidden' => true, );

	//we prevent all editing, as these options have to be the same for all regions.
	$fields['position']['condition'] = array( 'hidden' => true, );
	$fields['theme']['condition'] = array( 'hidden' => true, );

	$fields['tcf_purposes'] = array(
		'step'               => STEP_COOKIES,
		'section'            => 7,
		'source'             => 'wizard',
		'translatable'       => false,
		'default'            => cmplz_tcf_get('purposes', true),
		'type'               => 'multicheckbox',
		'options'            => cmplz_tcf_get('purposes'),
		'label'              => __( "Your site will show vendors with the purposes selected here", 'complianz-gdpr' ),
		'help'              => __( "To get a better understanding of vendors, purposes and features please read this definitions guide.", 'complianz-gdpr' ).cmplz_read_more('https://complianz.io/definitions/what-are-vendors/'),
		'callback_condition' => array( 'uses_cookies' => 'yes' ),
		'time'               => 5,
		'disabled'  => array(
			1,
		)
	);

	$fields['tcf_specialPurposes'] = array(
		'step'               => STEP_COOKIES,
		'section'            => 7,
		'source'             => 'wizard',
		'translatable'       => false,
		'default'            => cmplz_tcf_get('specialPurposes', true),
		'type'               => 'multicheckbox',
		'options'            => cmplz_tcf_get('specialPurposes'),
		'label'              => __( "Your site will show vendors with the special purposes selected here",
			'complianz-gdpr' ),
		'help'              => __( "These special purposes should be enabled for best performance. These purposes are set based on legitimate interest of the vendor, one of the legal bases of data processing.", 'complianz-gdpr' ).cmplz_read_more('https://complianz.io/definition/what-is-a-lawful-basis-for-data-processing/#legitimate-interest'),
		'callback_condition' => array( 'uses_cookies' => 'yes' ),
		'time'               => 5,
	);

	$fields['tcf_features'] = array(
		'step'               => STEP_COOKIES,
		'section'            => 7,
		'source'             => 'wizard',
		'translatable'       => false,
		'default'            => cmplz_tcf_get('features', true ),
		'type'               => 'multicheckbox',
		'options'            => cmplz_tcf_get('features'),
		'label'              => __( "Your site will show vendors with the features selected here", 'complianz-gdpr' ),
		'callback_condition' => array( 'uses_cookies' => 'yes' ),
		'time'               => 5,
	);

	$fields['tcf_specialFeatures'] = array(
		'step'               => STEP_COOKIES,
		'section'            => 7,
		'source'             => 'wizard',
		'translatable'       => false,
		'default'            => false,
		'type'               => 'multicheckbox',
		'options'            => cmplz_tcf_get('specialFeatures'),
		'label'              => __( "Your site will show vendors with the special features selected here", 'complianz-gdpr' ),
		'callback_condition' => array( 'uses_cookies' => 'yes' ),
		'time'               => 5,
	);

	$fields['tcf_default_hide_purposes'] = array(
		'step'               => STEP_COOKIES,
		'section'            => 7,
		'source'  => 'wizard',
		'type'    => 'radio',
		'options' => COMPLIANZ::$config->yes_no,
		'default' => 'yes',
		'label'   => __( "By default the purposes on the banner are visible with descriptions. Do you want to hide the descriptions with a toggle?", 'complianz-gdpr' ),
	);
	return $fields;
}

/**
 * @param string $fieldname
 *
 * @return array
 */
function cmplz_tcf_get_selected_array_keys( $fieldname ) {
	$values = cmplz_get_value("tcf_".$fieldname);
	if (!is_array($values)) $values = array($values);
	return  array_keys(array_filter($values));
}

/**
 * Enqueue scripts
 * @param $hook
 */

function cmplz_tcf_enqueue_assets( $hook ) {
	$minified = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
	wp_register_style( 'cmplz-tcf', cmplz_url . "/pro/tcf/assets/css/tcf$minified.css", false, cmplz_version );
	wp_enqueue_style( 'cmplz-tcf' );
    wp_enqueue_script( 'cmplz-tcf', cmplz_url . "/pro/tcf/dist/blocks.build.js", array(), filemtime( cmplz_path . 'dist/blocks.build.js'), true );

	$isServiceSpecific = true;//cmplz_get_value('tcf_global') !== 'global';
	$purposes = cmplz_tcf_get_selected_array_keys('purposes');
	$specialPurposes = cmplz_tcf_get_selected_array_keys('specialPurposes');
	$features = cmplz_tcf_get_selected_array_keys('features');
	$specialFeatures = cmplz_tcf_get_selected_array_keys('specialFeatures');

	wp_localize_script(
		'cmplz-tcf',
		'cmplz_tcf',
		array(
			'isServiceSpecific' => $isServiceSpecific,
			'purposes' => $purposes,
			'specialPurposes' => $specialPurposes,
			'features' => $features,
			'specialFeatures' => $specialFeatures,
			'publisherCountryCode' => cmplz_tcf_get_publisher_country_code(),
		)
	);
}

function cmplz_tcf_get_publisher_country_code() {
	$country_code = cmplz_get_value( 'country_company' );
	$country_code = substr(strtoupper($country_code),0,2);
	if ( empty($country_code) )  $country_code = 'EN';
	return $country_code;
}

function cmplz_cookiebanner_preview_settings($html, $banner){
	return cmplz_purposes_overview_html();
}
/**
 * Add link to privacy policy
 * @param $array
 * @param $banner
 *
 * @return mixed
 */
function cmplz_tcf_add_link_to_banner($array, $banner){
	$tmpl = '<span class="cc-divider">&nbsp;-&nbsp;</span><a aria-label="learn more about privacy in our {type}" class="cc-link {type}" href="{link}">{description}</a>';
	$link = cmplz_get_document_url( 'privacy-statement', 'eu' );
	$privacy_link = str_replace( array(
		'{link}',
		'{description}',
		'{type}'
	), array(
		$link,
		$banner->readmore_privacy_x,
		'privacy-statement'
	), $tmpl );

	$array['privacy_link'][ 'eu' ] = $privacy_link;
	$array['message_optin'] = cmplz_get_default_banner_text();
	$array['categories'] = cmplz_purposes_overview_html();
	return $array;
}

/**
 * Get html for purposes overview on banner
 * @return string
 */
function cmplz_purposes_overview_html(){
	$hide_purposes = cmplz_get_value("tcf_default_hide_purposes")==='yes';
	$title_class  = $hide_purposes ? '' : 'cmplz-tcf-hidden';
	$desc_class  = $hide_purposes ? 'cmplz-tcf-hidden' : '';
	$html = '<div class="cmplz-tcf-category-expl">
				<p>'.__("On our site we use the following purposes:","complianz-gdpr").'</p>
				<div class="cmplz-tcf-expl-header statistics-purposes '.$title_class.'">'.__("Statistics","complianz-gdpr").'</div>
				<div class="cmplz-tcf-expl-desc statistics-purposes '.$desc_class.'"></div>
				<div class="cmplz-tcf-expl-header marketing-purposes '.$title_class.'">'.__("Marketing","complianz-gdpr").'</div>
				<div class="cmplz-tcf-expl-desc marketing-purposes '.$desc_class.'"></div>
				<div class="cmplz-tcf-expl-header features '.$title_class.'">'.__("Features","complianz-gdpr").'<span class="cmplz-tcf-active">'.__("Always active", "complianz-gdpr").'</span></div>
				<div class="cmplz-tcf-expl-desc features '.$desc_class.'"></div>
				<div class="cmplz-tcf-expl-header specialFeatures '.$title_class.'">'.__("Special Features","complianz-gdpr").'</div>
				<div class="cmplz-tcf-expl-desc specialFeatures '.$desc_class.'"></div>
				<div class="cmplz-tcf-expl-header specialPurposes '.$title_class.'">'.__("Special Purposes","complianz-gdpr").'<span class="cmplz-tcf-active">'.__("Always active", "complianz-gdpr").'</span></div>
				<div class="cmplz-tcf-expl-desc specialPurposes '.$desc_class.'"></div>
				<a class="cmplz-tcf-manage-vendors"href="#">'.__("Manage vendors", "complianz-gdpr").'</a>
				<a class="cmplz-tcf-purposes-readmore" target="_blank" rel="noopener noreferrer nofollow" href="https://cookiedatabase.org/tcf/purposes">'.__("Read more about these purposes", "complianz-gdpr").'</a>
			</div>';

	//we add the complianz categories to ensure compatibility for those cats as well
	$html .= '<div style="display:none">'.
	         '<input type="checkbox" class="cmplz-consent-checkbox cmplz_stats" data-category="cmplz_statistics">' .
	         '<input type="checkbox" class="cmplz-consent-checkbox cmplz_marketing" data-category="cmplz_marketing">' .
	         '</div>';

	$html .= '<div class="cmplz-tcf-banner-header"><div class="cmplz-tcf-header">'.__("Manage Your Privacy", 'complianz-gdpr') .'</div></div>';
	return $html;
}

/**
 *
 * Shortcode to insert IAB container in the Cookie Policy
 * @param array  $atts
 * @param null   $content
 * @param string $tag
 *
 * @return false|string
 */

function cmplz_tcf_vendors( $atts = array(), $content = null, $tag = '' ) {
	$template =
		'<div class="cmplz-tcf-vendor-container cmplz-tcf-checkbox-container">
				<label for="cmplz-tcf-vendor-{vendor_id}">
					<input id="cmplz-tcf-{vendor_id}" class="cmplz-tcf-vendor-input" value="1" type="checkbox" name="cmplz-tcf-vendor-{vendor_id}">
					{vendor_name}
					<a href="#" class="cmplz-tcf-toggle-vendor cmplz-tcf-rm"></a>
				</label>
				<div class="cmplz-tcf-links">
					<div class="cmplz-tcf-policy-url"><a target="_blank" rel="noopener noreferrer nofollow" href="{privacy_policy}">'.__("Privacy Policy","complianz-gdpr").'</a></div>

				</div>
				<div class="cmplz-tcf-info">
					<div class="cmplz-tcf-info-content">
						<div class="cmplz-tcf-header">'.__("Legal bases", 'complianz-gdpr').'</div>
						<div class="cmplz-tcf-description">
							<label for="consent_{vendor_id}">
									<input type="checkbox" name="consent_{vendor_id}" class="cmplz-tcf-consent-input">
									<a target="_blank" rel="noopener noreferrer nofollow" href="https://cookiedatabase.org/tcf/consent">'.__("Consent", 'complianz-gdpr').'</a>
							</label>
							<label for="legitimate_interest_{vendor_id}" class="cmplz_tcf_legitimate_interest_checkbox">
									<input type="checkbox" name="legitimate_interest_{vendor_id}" class="cmplz-tcf-legitimate-interest-input">
									<a target="_blank" rel="noopener noreferrer nofollow" href="https://cookiedatabase.org/tcf/legitimate-interest">'.__("Legitimate interest", 'complianz-gdpr').'</a>
							</label>
						</div>
					</div>
					<div class="cmplz-tcf-info-content">
						<div class="cmplz-tcf-header">'.__("Maximum cookie retention:", 'complianz-gdpr').'</div>
						<div class="cmplz-tcf-description">&nbsp;
							<span class="session-storage">'.__("Session Storage", "complianz-gdpr").'</span>
							<span class="retention_days">'.sprintf(__("%s Days", "complianz-gdpr"), '{cookie_retention_days}').'</span>
							<span class="retention_seconds">'.sprintf(__("%s Seconds", "complianz-gdpr"), '{cookie_retention_seconds}').'</span>
						</div>
					</div>
					<div class="cmplz-tcf-info-content">
						<div class="cmplz-tcf-header">'.__("Non-cookie storage and access:", 'complianz-gdpr').'</div>
						<div class="cmplz-tcf-description">&nbsp;<span class="non-cookie-storage-active">'.__("Yes", "complianz-gdpr").'</span><span class="non-cookie-storage-inactive">'.__("No", "complianz-gdpr").'</span></div>
					</div>
					<div class="cmplz-tcf-info-content">
						<div class="cmplz-tcf-header">'.__("Purposes", 'complianz-gdpr').'</div>
						<div class="cmplz-tcf-description">{purposes}</div>
					</div>
				</div>
			</div>';

	$type_template = cmplz_iab_getcheckbox_html();

	$buttons = '<div id="cmplz-tcf-buttons-template"><div class="cmplz-tcf-buttons"><button id="cmplz-tcf-selectall">'.__("Select all","complianz-gdpr").'</button><button id="cmplz-tcf-deselectall">'.__("Deselect all","complianz-gdpr").'</button></div></div>';

	$html = $buttons.'<div id="cmplz-tcf-vendor-template" class="cmplz-tcf-template">'.$template.'</div><div id="cmplz-tcf-type-template" class="cmplz-tcf-template">'.$type_template.'</div>
	<p>'.
    __("These are the partners we share data with. By clicking into each partner, you can see which purposes they are requesting consent and/or which purposes they are claiming legitimate interest for. You can turn each one on and off to control whether or not data is shared with them or simply disable all data processing. However, please note that by disabling all data processing, some site functionality may be affected.","complianz-gdpr").
    '</p>'.
    '<p>'.__("When you consent to a category you consent to the following purposes:","complianz-gdpr").'</p>
	<b>'.__("Statistics","complianz-gdpr").'</b>
	<p id="cmplz-tcf-statistics-purposes-container" class="cmplz-tcf-container"></p>

	<b>'.__("Marketing","complianz-gdpr").'</b>
	<p id="cmplz-tcf-marketing-purposes-container" class="cmplz-tcf-container"></p>

	<b>'.__("Special features","complianz-gdpr").'</b>
	<p>'.__("For some of the purposes we and/or our partners", "complianz-gdpr").'</p>
	<p id="cmplz-tcf-specialfeatures-container" class="cmplz-tcf-container"></p>

	<b>'.__("Special purposes","complianz-gdpr").'</b>
	<p>' . __( "We need your consent for all the purposes above. We and/or our partners have a legitimate interest for the following two purposes:", "complianz-gdpr" ) . '</p>
	<p id="cmplz-tcf-specialpurposes-container" class="cmplz-tcf-container"></p>

	<b>'.__("Features","complianz-gdpr").'</b>
	<p>'.__("For some of the purposes above we and our partners", "complianz-gdpr").'</p>
	<p id="cmplz-tcf-features-container" class="cmplz-tcf-container"></p>

	<b>'.__("Vendors","complianz-gdpr").'</b>
	<p id="cmplz-tcf-vendor-container" class="cmplz-tcf-container"></p>';

	return apply_filters('cmplz_tcf_container', $html);
}


function cmplz_iab_getcheckbox_html(  ) {

	return '<div class="cmplz-tcf-{type}-container cmplz-tcf-checkbox-container">
		<label for="cmplz-tcf-{type}-{type_id}">
			<input id="cmplz-tcf-{type}-{type_id}" class="cmplz-tcf-{type}-input cmplz-tcf-input" value="1" type="checkbox" name="cmplz-tcf-{type}-{type_id}">
			{type_name} <a href="#" class="cmplz-tcf-toggle cmplz-tcf-rm"></a>
			<div id="cmplz-tcf-{type}-{type_id}-desc" class="cmplz-tcf-type-description">{type_description}</div>
		</label>
	</div>';
}

/**
 * If the global settings is changed, we need to reset the text
 * @param $fieldname
 * @param $fieldvalue
 * @param $prev_value
 * @param $type
 */

function cmplz_tcf_after_save_cookie_settings_option($fieldname, $fieldvalue, $prev_value, $type){
	if (!current_user_can('manage_options')) return;
	//only run when changes have been made
	if ($fieldvalue === $prev_value) return;

	if ($fieldname==='uses_ad_cookies' && $fieldvalue === 'no' ) {
		//because the post values are already in a sanitized array, we can't stop the current tcf value from being saved.
		//we add another hook, which resets the value after the saving has completed
		add_action('cmplz_after_saved_all_fields', 'cmplz_tcf_reset_tcf', 10, 1 );
	}

	if ($fieldname==='uses_ad_cookies_personalized' && $fieldvalue === 'tcf' ) {
		update_option("cmplz_tcf_initialized", false);
	}
}

/**
 * After all fields have been saved, reset the tcf if 'uses_ad_cookies' has been set to no.
 * @param array $posted_fields
 */
function cmplz_tcf_reset_tcf($posted_fields){
	cmplz_update_option( 'wizard', 'uses_ad_cookies_personalized', 'no' );
}

/**
 * Check if there are compatibility issues
 */

function cmplz_iab_is_enabled(){
	return cmplz_get_value('uses_ad_cookies_personalized', false, 'wizard') === 'tcf';
}

/**
 * Disable advertising integrations
 */
function cmplz_tcf_disable_integrations(){
	remove_filter( 'cmplz_known_script_tags', 'cmplz_advertising_script' );
	remove_filter( 'cmplz_known_iframe_tags', 'cmplz_advertising_iframetags' );
}
add_action( 'init', 'cmplz_tcf_disable_integrations' );

/**
 * With TCF, we need to hardcode some categories
 * @param $settings
 *
 * @return mixed
 */
function cmplz_tcf_adjust_cookie_policy_snapshot_settings($settings){
	unset($settings['categories']);

	return $settings;
}
add_filter( 'cmplz_cookie_policy_snapshot_settings' , 'cmplz_tcf_adjust_cookie_policy_snapshot_settings' );

/**
 * Add link to vendors overview
 * @param $html
 *
 * @return mixed
 */

function cmplz_tcf_adjust_cookie_policy_snapshot_html($html){
	$purposes = array_keys(array_filter(cmplz_get_value('tcf_purposes')));
	$special_purposes = array_keys(array_filter(cmplz_get_value('tcf_specialPurposes')));
	$features= array_keys(array_filter(cmplz_get_value('tcf_features')));
	$special_features = array_keys(array_filter(cmplz_get_value('tcf_specialFeatures')));
	$marker_marketing = '<p id="cmplz-tcf-marketing-purposes-container" class="cmplz-tcf-container"></p>';
	$marker_statistics = '<p id="cmplz-tcf-statistics-purposes-container" class="cmplz-tcf-container"></p>';
	$marker_specialfeatures = '<p id="cmplz-tcf-specialfeatures-container" class="cmplz-tcf-container"></p>';
	$marker_features = '<p id="cmplz-tcf-features-container" class="cmplz-tcf-container"></p>';
	$marker_specialpurposes = '<p id="cmplz-tcf-specialpurposes-container" class="cmplz-tcf-container"></p>';

	$p_labels = cmplz_tcf_get('purposes');
	$sp_labels = cmplz_tcf_get('specialPurposes');
	$f_labels = cmplz_tcf_get('features');
	$sf_labels = cmplz_tcf_get('specialFeatures');

	foreach ($p_labels as $key => $label ) {
		if (!in_array($key, $purposes) ) unset($p_labels[$key]);
	}
	foreach ($sp_labels as $key => $label ) {
		if (!in_array($key, $special_purposes) ) unset($sp_labels[$key]);
	}
	foreach ($f_labels as $key => $label ) {
		if (!in_array($key, $features) ) unset($f_labels[$key]);
	}
	foreach ($sf_labels as $key => $label ) {
		if (!in_array($key, $special_features) ) unset($sf_labels[$key]);
	}
	$stats_purposes = cmplz_tcf_filter_by_category($p_labels, 'statistics');
	$marketing_purposes = cmplz_tcf_filter_by_category($p_labels, 'marketing');
	$stats_purposes = '<div>'.implode('<br>', $stats_purposes).'</div>';
	$marketing_purposes = '<div>'.implode('<br>', $marketing_purposes).'</div>';
	$features = '<div>'.implode('<br>', $f_labels).'</div>';
	$special_features = '<div>'.implode('<br>', $sf_labels).'</div>';
	$special_purposes = '<div>'.implode('<br>', $sp_labels).'</div>';
	$html = str_replace( $marker_statistics, $stats_purposes, $html);
	$html = str_replace( $marker_marketing, $marketing_purposes, $html);

	$html = str_replace( $marker_specialfeatures, $special_features, $html);
	$html = str_replace( $marker_features, $features, $html);
	$html = str_replace( $marker_specialpurposes, $special_purposes, $html);

	$marker = '<div id="cmplz-tcf-vendor-template"';
	$add = sprintf(__("The vendor list can be found at %s", "complianz-gdpr"),'<a href="https://complianz.io/cmp/vendorlist/vendor-list.json">complianz.io</a><br><br>');
	$html = str_replace($marker, $add . $marker, $html);
	return $html;
}


function cmplz_tcf_filter_by_category( $purposes, $category ) {
	$p['marketing'] = array(1, 2, 3, 4, 5, 6, 10);
	$p['statistics']  = array(1, 7, 8, 9);

	foreach ( $purposes as $key => $value ) {
		if ( !in_array( $key, $p[ $category ] )) unset($purposes[$key]);
	}

	return $purposes;
}

/**
 * remove other consenttypes from cookiebanner tabs when tcf active
 * @param array $tabs
 *
 * @return array
 */

function cmplz_tcf_cookiebanner_tabs($tabs){
	foreach ($tabs as $key => $consenttype ) {
		if ($consenttype !== 'optout') unset($tabs[$key]);
	}
	$tabs[] = 'tcf';
	return $tabs;
}

add_action('cmplz_cookiebanner_tab_content_tcf', 'cmplz_tcf_cookiebanner_tab_tcf');
function cmplz_tcf_cookiebanner_tab_tcf(){
	?>
		<p>
			<?php _e("Configuring your TCF cookie banner is a bit different than our standard cookie banners.", "complianz-gdpr")?>
			<?php _e("Because of guidelines stated by IAB Europe, most changes to this banner could violate these guidelines.", "complianz-gdpr")?>
		</p>
		<p>
			<?php _e("These changes could lead to lost revenue, a suspended account, or the CMP ID might be revoked.", "complianz-gdpr")?>
			<?php _e("For a preview, please load your website on the front-end.", "complianz-gdpr")?>
			<?php echo cmplz_read_more('https://complianz.io/customizing-the-tcf-banner/')?>
		</p>
	<?php
}
