<?php
defined('ABSPATH') or die("you do not have acces to this page!");

if ( !defined('CMPLZ_SITES_PER_BATCH' ) ) define('CMPLZ_SITES_PER_BATCH', 50);

add_action( 'cmplz_settings_items', 'cmplz_ms_drop_license_block', 60, 1);
function cmplz_ms_drop_license_block($items){
	unset($items['license']);
	return $items;
}

add_filter('cmplz_fields', 'cmplz_filter_multisite_fields', 10, 1);
function cmplz_filter_multisite_fields($fields) {

	if (is_multisite() && is_main_site(get_current_blog_id())) {
	$fields['copy_settings_multisite'] = array(
			'warn'     => __( 'Are you sure? This will overwrite the settings in all your subsites with the Complianz settings of this site.', 'complianz-gdpr' ),
			'source'   => 'settings',
			'step'     => 'general',
			'type'     => 'button',
			'action'   => 'cmplz_copy_settings_multisite',
			'post_get' => 'post',
			'label'    => __( "Copy settings to subsites", 'complianz-gdpr' ),
			'table'    => true,
			'help'     => __( 'This will overwrite the Complianz settings in all your subsites with the settings of the current site.', 'complianz-gdpr' ),
		);
	}
	return $fields;
}



/**
 * Initialize copy process
 */

function cmplz_activate_copy_settings_multisite() {
	if (!current_user_can('manage_options')) return;

	if ( ! isset( $_POST['cmplz_copy_settings_multisite'] ) ) {
		return;
	}

	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	if ( ! isset( $_POST['cmplz_nonce'] ) || ! wp_verify_nonce( $_POST['cmplz_nonce'], 'complianz_save' ) ) {
		return;
	}
	update_site_option('cmplz_copy_settings_active', true);
	update_site_option('cmplz_siteprocessing_progress', 0);

}
add_action('admin_init', 'cmplz_activate_copy_settings_multisite', 10, 1);

/**
 * Run chunked copy of wizard settings.
 */

function cmplz_run_copy_settings(){
	if (!is_multisite()) return;
	if (!is_main_site(get_current_blog_id())) return;

	if (!current_user_can('manage_options')) return;

	if (!get_site_option('cmplz_copy_settings_active')) return;

	global $wpdb;
	//get table names for cookies and services in the main site
	$table_name_cookies = $wpdb->prefix . 'cmplz_cookies';
	$table_name_services = $wpdb->prefix . 'cmplz_services';
	$table_name_cookiebanners = $wpdb->prefix . 'cmplz_cookiebanners';

	$main_blog_id = get_current_blog_id();
	$options = array(
		'cmplz_wizard_completed_once' ,
		'complianz_options_settings',
		'complianz_options_wizard',
		'complianz_options_dataleak',
		'complianz_options_processing',
		'cmplz_detected_social_media',
		'cmplz_detected_thirdparty_services',
		'cmplz_run_cdb_sync_once',
		'cmplz_geo_ip_file',
		'cmplz_plugin_new_features',
		'cmplz_changed_cookies',
		'cmplz_plugins_updated',
		'cmplz_plugins_changed',
		'cmplz_publish_date',
		'cmplz_documents_update_date',
	);

	$option_values = array();
	foreach ($options as $option_name) {
		$option_values[$option_name] = get_option($option_name, true);
	}

	//get custom url value

	//Save the custom URL's for not Complianz generated pages.
	$docs = COMPLIANZ::$document->get_document_types();
	$custom_urls = array();
	$generated_docs = array();
	$regions = cmplz_get_regions(true);
	foreach ( $docs as $document ){
		if ( cmplz_get_value( $document ) === 'url' ){
			$custom_urls[$document] = get_option("cmplz_".$document."_custom_page_url" );
		}

		if ( cmplz_get_value( $document ) === 'generated' ){
			foreach ( $regions as $region => $label ) {
				if (!isset(COMPLIANZ::$config->pages[$region][$document]) ) continue;
				$generated_docs[$region][] = $document;
			}

		}
	}


	//run chunked
	$nr_of_sites = CMPLZ_SITES_PER_BATCH;
	$offset = get_site_option('cmplz_siteprocessing_progress');

	//set batch of sites
	$args = array(
		'number' => $nr_of_sites,
		'offset' => $offset,
		'public' => 1,
	);
	$sites = get_sites($args);

	//if no sites are found, we assume we're done.
	if (count($sites)==0) {
		update_site_option('cmplz_copy_settings_active', false);
	} else {
		foreach ($sites as $site) {

			if ($site->blog_id == $main_blog_id) continue;
			switch_to_blog($site->blog_id);

			foreach ( $regions as $region => $label ) {
				//e.g. 'all' region may not have been added.
				if ( !isset($generated_docs[$region]) ) {
					continue;
				}
				foreach ( $generated_docs[$region] as $type ) {
					$current_page_id = COMPLIANZ::$document->get_shortcode_page_id($type, $region);
					if ( !$current_page_id ){
						$title = COMPLIANZ::$config->pages[ $region ][ $type ]['title'];
						COMPLIANZ::$document->create_page( $type, $region, $title  );
					}
				}
			}

			//copy options
			foreach ($options as $option_name) {
				update_option($option_name, $option_values[$option_name]);
			}

			//Save the custom URL's for not Complianz generated pages.
			foreach ($custom_urls as $document => $url){
				update_option("cmplz_".$document."_custom_page_url", $url );
			}

			//if the plugins page is reviewed, we can reset the privacy statement suggestions from WordPress.
			if ( cmplz_wp_privacy_version() && cmplz_get_value( 'privacy-statement' ) === 'generated'
			) {
				$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
				WP_Privacy_Policy_Content::_policy_page_updated( $policy_page_id );
				//check again, to update the cache.
				WP_Privacy_Policy_Content::text_change_check();
			}

			//copy cookies and services
			$new_table_name_cookies = $wpdb->prefix . 'cmplz_cookies';
			$new_table_name_services = $wpdb->prefix . 'cmplz_services';
			$new_table_name_cookiebanners = $wpdb->prefix . 'cmplz_cookiebanners';

			//create new, and copy
			$wpdb->query("Drop TABLE if exists $new_table_name_cookies");
			$wpdb->query("CREATE TABLE $new_table_name_cookies LIKE $table_name_cookies");
			$wpdb->query("INSERT $new_table_name_cookies SELECT * FROM $table_name_cookies;");

			$wpdb->query("Drop TABLE if exists $new_table_name_services");
			$wpdb->query("CREATE TABLE $new_table_name_services LIKE $table_name_services");
			$wpdb->query("INSERT $new_table_name_services SELECT * FROM $table_name_services;");

			$wpdb->query("Drop TABLE if exists $new_table_name_cookiebanners");
			$wpdb->query("CREATE TABLE $new_table_name_cookiebanners LIKE $table_name_cookiebanners");
			$wpdb->query("INSERT $new_table_name_cookiebanners SELECT * FROM $table_name_cookiebanners;");

			//generate css for each banner
			$banners = cmplz_get_cookiebanners();
			if ( $banners ) {
				foreach ( $banners as $banner_item ) {
					$banner = new CMPLZ_COOKIEBANNER( $banner_item->ID );
					$banner->save();
				}
			}

			cmplz_update_option('settings', 'disable_notifications', true);
			COMPLIANZ::$cookie_admin->reset_cookies_changed();
			update_option( 'cmplz_wizard_completed_once', true );

			restore_current_blog(); //switches back to previous blog, not current, so we have to do it each loop
			update_site_option('cmplz_siteprocessing_progress', $offset+$nr_of_sites);
		}
	}
}
add_action('admin_init', 'cmplz_run_copy_settings');



/**
 * Notice when copy process is running
 */

add_action('cmplz_notice_copy_settings_multisite', 'cmplz_notice_copy_settings_multisite');
function cmplz_notice_copy_settings_multisite(){

	$active = get_site_option('cmplz_copy_settings_active');
	$progress = get_site_option('cmplz_siteprocessing_progress');
	$start = $progress - CMPLZ_SITES_PER_BATCH;
	if ($start < 0) $start = 0;

	$total = get_blog_count();
	if ($active){
		$next = $progress+CMPLZ_SITES_PER_BATCH;
		if ($next>$total) $next = $total;
		cmplz_sidebar_notice(sprintf(__("Complianz is currently copying settings of site %s to %s of %s sites. Each pageload will run a batch.", 'complianz-gdpr'), $start, $next, $total),'warning');
	}
}
