<?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.
 *
 *
 * */
function cmplz_dnt_enabled()
{
	//only if the user has explicitly enabled this
	if ( cmplz_get_value('respect_dnt') !== 'no' ) {
		return ( ( isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] == 1 ) || isset($_SERVER['HTTP_SEC_GPC']) );
	}
	return false;
}
add_filter('cmplz_dnt_enabled', 'cmplz_dnt_enabled');

/**
 * Get consent type for a user
 * @param $consenttype
 *
 * @return string
 */
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;
}
add_filter('cmplz_user_consenttype', 'cmplz_user_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() && defined('cmplz_premium_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;
}

/**
* @param array $warnings
* @return array $warnings
*/

function cmplz_pro_warnings_types($warnings)
{
	if ( cmplz_get_value('privacy-statement')!=='generated' ) {
		unset ($warnings['missing-processing-agreements']);
	}

	return $warnings;
}
add_filter('cmplz_warnings_types', 'cmplz_pro_warnings_types');

/*
 * 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') === 'start' ){
        //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

        //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);
        }

        update_option('cmplz_run_premium_install' , 'completed' );
    }
}
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 ($prev_version && version_compare($prev_version, '4.0.4', '<')) {
		update_option('cmplz_show_cookiedatabase_optin',false);
		cmplz_update_option('wizard', 'use_cdb_api', 'yes');
	}

	if ($prev_version && version_compare($prev_version, '5.0.0', '<')) {
		global $wpdb;
		//clean up a/b testing table
		$wpdb->delete(
				$wpdb->prefix."cmplz_statistics",
				array( 'time' => '')
		);
	}

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