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

/**
 * Premium should respect Do Not Track settings in browsers, if the user has enabled this setting.
 *
 *
 * */
add_filter('cmplz_dnt_enabled', 'cmplz_dnt_enabled');
function cmplz_dnt_enabled()
{
	//only if the user has explicitly enabled this
	if (cmplz_get_value('respect_dnt')!=='no') return false;

	return (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] == 1);
}

add_filter('cmplz_user_consenttype', 'cmplz_user_consenttype');
function cmplz_user_consenttype($consenttype)
{
	if (COMPLIANZ::$geoip->geoip_enabled()) {
		$user_consenttype = COMPLIANZ::$geoip->consenttype();

		//we should only return the detected consenttype if the website is configured to use it
		if (in_array($user_consenttype, cmplz_get_used_consenttypes())){
			$consenttype = $user_consenttype;
		} else {
			$consenttype = 'other';
		}
	}

	return $consenttype;
}


/**
 * ADMIN ONLY FUNCTIONS
 */


/**
 * Override labels in document field
 * @param $label
 * @param $nicename
 *
 * @return string
 */
function cmplz_generate_document_label($label, $nicename){
	return sprintf(__("Generated by Complianz", "complianz-gdpr"), $nicename);
}
add_filter('cmplz_generate_document_label', 'cmplz_generate_document_label', 10, 2);


add_filter('cmplz_shepherd_steps', 'cmplz_add_shepherd_steps_premium');
function cmplz_add_shepherd_steps_premium($steps){
	if (COMPLIANZ::$license->license_is_valid()) {
		$license_text = __( "Great, your license is activated and valid! Let's take a look at the dashboard.", 'complianz-gdpr' );
	} else {
		$license_text = __( "To unlock the wizard and future updates, please enter and activate your license.", 'complianz-gdpr' );
	}
	if (is_multisite()){
		$steps[0]['link'] =  network_admin_url( "settings.php?page=complianz");
	} else {
		$steps[0]['link'] =  admin_url( "admin.php?page=cmplz-license");
	}

	$steps[1] = array(
		'title' => __( 'Activate your license', 'complianz-gdpr' ),
		'text'  => $license_text,
		'link'  => admin_url( "admin.php?page=complianz" ),
		'attach' => '.description [bottom right]',
	);
	return $steps;
}


add_filter('cmplz_api_data', 'cmplz_api_data');
function cmplz_api_data($data){
    $license = false;
    if (is_multisite()){
	    $license = get_site_option('cmplz_license_key');
    }

    //fallback for multisite as well
    if (!$license) $license = get_option('cmplz_license_key');

	$data["license"] = trim($license);
    return $data;
}

add_action('admin_init', 'cmplz_change_free_actions');
function cmplz_change_free_actions()
{
    remove_action("cmplz_documents_footer", array(COMPLIANZ::$admin, 'documents_footer'));
    remove_action("cmplz_documents", array(COMPLIANZ::$admin, 'documents'));

    remove_action("cmplz_dashboard_second_block", array(COMPLIANZ::$admin, 'dashboard_second_block'));
    add_action("cmplz_dashboard_second_block", 'cmplz_pro_dashboard_second_block');

    remove_action('cmplz_dashboard_elements_error', array(COMPLIANZ::$admin, 'dashboard_elements'));
}

add_filter('cmplz_user_region', 'cmplz_user_region');
function cmplz_user_region($region)
{
    if (COMPLIANZ::$geoip->geoip_enabled()) {
        $user_region = COMPLIANZ::$geoip->region();
	    //we should only return the detected region if the website is configured to use it
	    if (is_string($user_region) && array_key_exists($user_region, cmplz_get_regions())){
		    $region = $user_region;
	    } else {
		    $region = 'other';
	    }
    }

    return $region;
}

add_filter('cmplz_user_force_enable_stats', 'cmplz_user_force_enable_stats');
function cmplz_user_force_enable_stats($force_enable_stats)
{
    //not applicable if geo ip is not enabled.
    if (!cmplz_geoip_enabled()) return false;

	//if there's only one region it does not apply
	if (!cmplz_multiple_regions()) return false;

    //an optinstats region should never get force enabled.
	$consenttype = COMPLIANZ::$geoip->consenttype();
    if ($consenttype === 'optinstats') return false;

    //if region = uk, or eu only, do nothing
    //if region = eu, and we also have at least one optinstats region, and eu does not require consent for stats, autoenable stats
    if (!COMPLIANZ::$cookie_admin->cookie_warning_required_stats('eu') && cmplz_uses_consenttype('optinstats')) {
        $force_enable_stats = true;
    }

    return $force_enable_stats;
}

function cmplz_add_dashboard_elements_error()
{
    //page required checks EU region
    //if US only, the privacy statement EU is not required.
    if (cmplz_has_region('eu') && !COMPLIANZ::$document->page_required('privacy-statement', 'eu')) {
        COMPLIANZ::$admin->task_count++;
        COMPLIANZ::$admin->get_dashboard_element(__("You haven't enabled the privacy statement, so we can't determine if you need consent checkboxes", 'complianz-gdpr'), 'warning');
    }
}
add_action("cmplz_dashboard_elements_error", 'cmplz_add_dashboard_elements_error');


/**
 * Add some notices in the dashboard regarding the consentboxes
 */

function cmplz_add_dashboard_elements_success()
{
    //page required checks EU region
    if (COMPLIANZ::$document->page_required('privacy-statement', 'eu')) {
        if (cmplz_forms_used_on_sites()) {
            if (cmplz_consent_box_required_on_form()) {
                return; //handled by warnings array.
            } else {
                COMPLIANZ::$admin->get_dashboard_element(__('Your contact forms do not require a consent checkbox', 'complianz-gdpr'), 'success');
            }
        } else {
            COMPLIANZ::$admin->get_dashboard_element(__('You have indicated no contact forms are used on the website', 'complianz-gdpr'), 'success');
        }
    }

}
add_action("cmplz_dashboard_elements_success", 'cmplz_add_dashboard_elements_success');

/*
 * For premium, check if the license is valid before showing the wizard.
 *
 *
 * */

add_filter('cmplz_show_wizard_page', 'cmplz_show_wizard_page');
function cmplz_show_wizard_page($show)
{
    if (!COMPLIANZ::$license->license_is_valid()) {
        $show = false;
    }
    return $show;
}



//Pro dashboard second block
function cmplz_pro_dashboard_second_block()
{
    ?>

    <div class="cmplz-header-top cmplz-dashboard-text">
        <div class="cmplz-dashboard-title"> <?php echo __('Tools', 'complianz-gdpr'); ?> </div>
    </div>
    <?php
    cmplz_notice(COMPLIANZ::$admin->error_message, 'warning');
    cmplz_notice(COMPLIANZ::$admin->success_message, 'success', true);
    COMPLIANZ::$admin->error_message = "";
    COMPLIANZ::$admin->success_message = "";
    ?>
    <div class="cmplz-dashboard-support-content cmplz-dashboard-text">
        <ul>
            <?php do_action('cmplz_tools') ?>
            <?php
                $regions = cmplz_get_regions();
                foreach ($regions as $region => $label) {
                    ?>
                    <li><i class="fas fa-plus"></i><a
                                href="<?php echo admin_url("admin.php?page=cmplz-dataleak-$region") ?>"><?php printf(__("Create dataleak report (%s)", 'complianz-gdpr'), $label); ?></a>
                    </li>
                    <li><i class="fas fa-plus"></i><a
                                href="<?php echo admin_url("admin.php?page=cmplz-processing-$region") ?>"><?php printf(__("Create processing agreement (%s)", 'complianz-gdpr'), $label); ?></a>
                    </li>
            <?php }?>

            <?php
            //prepare support data
            $email = sanitize_email(get_option('admin_email'));
            $license = get_option('cmplz_license_key');
            $user_info = get_userdata(get_current_user_id());
            $nicename = $user_info->user_nicename;
            ?>
            <li><i class="fas fa-plus"></i><a href="<?php echo add_query_arg(array('email'=>esc_html($email), 'license'=>$license, 'user'=>$nicename,'website'=>esc_url(site_url())),'https://complianz.io/support')?>" target="_blank"><?php _e("Need help? Quickly submit your support ticket", 'complianz-gdpr'); ?></a>
            </li>
        </ul>
    </div>

    <?php
}


/*
 * Override logo text
 * */

add_filter('cmplz_logo_extension', 'cmplz_logo_extension');
function cmplz_logo_extension($str)
{
    $str = __("Premium", 'complianz-gdpr');
    return $str;
}


/*
 * Add some warnings which are only needed in the premium plugin
 *
 *
 * */

add_filter('cmplz_warnings', 'cmplz_pro_warnings');
function cmplz_pro_warnings($warnings)
{

    if (cmplz_wp_privacy_version() && WP_Privacy_Policy_Content::text_change_check()) {
        $warnings[] = 'suggested-policy-text-changed';
    }

    if (cmplz_has_region('eu') && COMPLIANZ::$processing->missing_agreements_for_processors() > 0) {
        $warnings[] = 'missing-processing-agreements';
    }

    if (COMPLIANZ::$geoip->geoip_library_error()) {
        $warnings[] = 'geoip-database-error';
    }

    return $warnings;
}



add_filter('cmplz_get_banners', 'cmplz_get_banners_filter');
function cmplz_get_banners_filter($banners){
    $banners = cmplz_get_cookiebanners();
    return $banners;
}





/**
 * Check if the plugin was just upgraded from free to premium, and if so, handle some migration
 * @hooked admin_init
 * @return void
 */

function cmplz_check_upgrade_from_free(){

    if (get_option('cmplz_run_premium_install')){
        //we don't use geo location yet, (upgrading from free)
        // so we don't need to upgrade the region yet. We can do that on the enabling of the geoip

        //remove free language files on upgrade to premium
        if (cmplz_has_free_translation_files()){
            cmplz_remove_free_translation_files();
        }

        //default, privacy statement and disclaimer are set to disabled in free, but we might want them to be enabled by default
        //the disadvantage would be that pages would be generated as well. We'll leave it for now
//        COMPLIANZ::$field->save_field('privacy-statement', 'yes');
//        COMPLIANZ::$field->save_field('disclaimer', 'yes');

        //enable Geo IP
        cmplz_update_option('settings', 'use_country', true);
        //start download of geo db.
        update_option('cmplz_import_geoip_on_activation', true);

        //set the region as the new array type
        $regions = cmplz_get_value('regions', false, 'wizard');

        if (!empty($regions) && !is_array($regions)) {
            $regions = array($regions => 1);
            cmplz_update_option('wizard', 'regions', $regions);
        }

        delete_option('cmplz_run_premium_install');
    }
}
add_action('admin_init', 'cmplz_check_upgrade_from_free');

/**
 * Hooks in on the free plugin upgrade function
 * Runs when the plugin is updated in the dashboard.
 * @param $prev_version
 * @hooked cmplz_upgrade
 * @return void
 */

function cmplz_upgrade_premium($prev_version)
{
    if (version_compare($prev_version, '2.0.6', '<')) {
        //add category eu existing dataleaks and processing agreements.
        $posts = get_posts(array('post_type' => array('cmplz-dataleak', 'cmplz-processing'), 'post_status'=> array('publish', 'pending', 'draft', 'auto-draft'), 'posts_per_page'=>-1));
        foreach ($posts as $post){
            if (!COMPLIANZ::$document->get_region($post->ID)){
                COMPLIANZ::$document->set_region($post->ID, 'eu');
            }
        }
    }

    /*
    * To prevent the free from overriding the shipped premium translations, we rename the free translations.
    * remove free translation files, if existent.
    */
    if (version_compare($prev_version, '2.1.1', '<')) {
        //remove free language files
        if (cmplz_has_free_translation_files()){
            cmplz_remove_free_translation_files();
        }
    }

    //set a default region if this is an upgrade:
    if ($prev_version && version_compare($prev_version, '2.0.1', '<')) {
        $regions = cmplz_get_value('regions');
        if (empty($regions)) {
            $country =  cmplz_get_value('use_country');
            if (defined('cmplz_premium')) {
                if ($country){
                    cmplz_update_option('wizard', 'regions', array('eu'));
                } else {
                    cmplz_update_option('wizard', 'regions', 'eu');
                }
            }
        }
    }

    //make sure the maxmind db is downloaded on upgrade
    if ($prev_version && version_compare($prev_version, '2.0.2', '<') && cmplz_get_value('use_country')) {
        update_option('cmplz_import_geoip_on_activation', true);
    }

    if (version_compare($prev_version, '3.0.0', '<')) {
        $variations = COMPLIANZ::$statistics->get_variations();

        if (is_array($variations) && !count($variations)==0) {
            foreach ($variations as $variation_id) {
                COMPLIANZ::$cookie_admin->migrate_legacy_cookie_settings($variation_id);
            }
        }
    }

	if ($prev_version && version_compare($prev_version, '4.0.4', '<')) {
		update_option('cmplz_show_cookiedatabase_optin',false);
		cmplz_update_option('wizard', 'use_cdb_api', 'yes');
	}

}
add_action('cmplz_upgrade',  'cmplz_upgrade_premium', 10);
