<?php

add_action('admin_enqueue_scripts', 'themoneytizer_load_js_css_files');
add_action('admin_menu', 'themoneytizer_register_submenu_page');
add_action('admin_init', 'themoneytizer_init_settings');
add_action('admin_init', 'themoneytizer_init_settings_two');
add_action('admin_init', 'themoneytizer_init_settings_three');
add_action('admin_init', 'themoneytizer_init_settings_four');
add_action('admin_init', 'themoneytizer_init_settings_five');
add_action('admin_init', 'themoneytizer_init_settings_six');


function themoneytizer_load_js_css_files(){
    wp_enqueue_script('jquery_ui', $src ='https://code.jquery.com/ui/1.12.1/jquery-ui.min.js',$deps = array(), $ver = false, $in_footer = false);
	wp_enqueue_style( 'jquery_ui_style', $src ='https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
	wp_enqueue_script('jquery_validate',  plugins_url( '/js/jquery.validate.min.js', __FILE__ ),$deps = array(), $ver = false, $in_footer = false);
	wp_enqueue_script('google_charts', $src ='https://www.google.com/jsapi',$deps = array(), $ver = false, $in_footer = false);
	wp_enqueue_script('sweet_alert',  plugins_url( '/js/sweetalert.min.js', __FILE__ ),$deps = array(), $ver = false, $in_footer = false);
	wp_register_script( 'lang_option', plugins_url( '/js/charts.js', __FILE__ ),$deps = array(), $ver = false, $in_footer = false);
	wp_register_script( 'custom_script', plugins_url( '/js/custom-script.js', __FILE__ ),$deps = array(), $ver = false, $in_footer = true);

	$lang_array = array(
		'themoney_lang' => __(strtolower(substr(get_bloginfo("language"), 3, 2)), 'plugin-domain' ),
	);

	wp_localize_script( 'lang_option', 'trad', $lang_array );

	$lang_array = array(
		'themoney_lang' => __(strtolower(substr(get_bloginfo("language"), 3, 2)), 'plugin-domain' ),
	);

	wp_localize_script( 'custom_script', 'trad', $lang_array );

	wp_enqueue_script( 'lang_option' );

	wp_enqueue_style ( 'css_style', plugins_url( '/css/style.css', __FILE__ ));

	wp_enqueue_script( 'custom_script' );
}

function themoneytizer_register_submenu_page(){
	add_submenu_page( 'options-general.php', 'The Moneytizer', 'The Moneytizer', 'manage_options', 'themoneytizer', 'themoneytizer_submenu_page' );
}

function themoneytizer_submenu_page() {
	if(!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.'));
    }
    include(sprintf("%s/themoneytizer-config-page.php", dirname(__FILE__)));
}

function themoneytizer_init_settings(){
    register_setting('themoneytizer_settings_group', 'themoney_is_registered');
	register_setting('themoneytizer_settings_group', 'nom_money');
	register_setting('themoneytizer_settings_group', 'prenom_money');
	register_setting('themoneytizer_settings_group', 'mail_money');
	register_setting('themoneytizer_settings_group', 'tel_money');
	register_setting('themoneytizer_settings_group', 'currency_money');
	register_setting('themoneytizer_settings_group', 'password_money');
	register_setting('themoneytizer_settings_group', 'adresse_money');
	register_setting('themoneytizer_settings_group', 'cp_money');
	register_setting('themoneytizer_settings_group', 'ville_money');
	register_setting('themoneytizer_settings_group', 'country_money');
    register_setting('themoneytizer_settings_group', 'type_structure_money');
    register_setting('themoneytizer_settings_group', 'parrainage_money');
	register_setting('themoneytizer_settings_group', 'raison_ajout_money');
	register_setting('themoneytizer_settings_group', 'raison_ajout_autre_money');
}

function themoneytizer_init_settings_two(){
	register_setting('themoneytizer_settings_group_two', 'themoney_is_registered');
	register_setting('themoneytizer_settings_group_two', 'url_money');
	register_setting('themoneytizer_settings_group_two', 'theme_money');
	register_setting('themoneytizer_settings_group_two', 'sub_theme_money');
	register_setting('themoneytizer_settings_group_two', 'lang_money');
    register_setting('themoneytizer_settings_group_two', 'vu_money');
	register_setting('themoneytizer_settings_group_two', 'pv_money');
	register_setting('themoneytizer_settings_group_two', 'newsletter_money');
}

function themoneytizer_init_settings_three(){
	register_setting('themoneytizer_settings_group_three', 'themoney_is_registered');
}

function themoneytizer_init_settings_four(){
	register_setting('themoneytizer_settings_group_four', 'themoney_is_registered');
	register_setting('themoneytizer_settings_group_four', 'themoneytizer_setting_siteid');
}

function themoneytizer_init_settings_five(){
  register_setting('themoneytizer_settings_group_five', 'themoney_is_registered');
  register_setting('themoneytizer_settings_group_five', 'bankChoice_money');
}

function themoneytizer_init_settings_six(){
    register_setting('themoneytizer_settings_group_six', 'themoney_is_registered');
    register_setting('themoneytizer_settings_group_six', 'themoneytizer_setting_mail_connexion');
    register_setting('themoneytizer_settings_group_six', 'themoneytizer_setting_password_connexion');
}

function themoneytizer_test_ajax_load_scripts() {
	wp_enqueue_script('jquery_ui', $src ='https://code.jquery.com/ui/1.11.4/jquery-ui.js',$deps = array(), $ver = false, $in_footer = false);
	wp_enqueue_script('jquery_validate',  plugins_url( '/js/jquery.validate.min.js', __FILE__ ),$deps = array(), $ver = false, $in_footer = false);
	wp_enqueue_script('sweet_alert',  plugins_url( '/js/sweetalert.min.js', __FILE__ ),$deps = array(), $ver = false, $in_footer = false);
	wp_enqueue_script( "ajax-test", plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
	wp_localize_script( 'ajax-test', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}



/*===== Registration Start =====*/

function themoneytizer_check_registration_validity() {
    $url='https://www.themoneytizer.com/plugin/verify_account';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array('mail' => get_option('mail_money'), 'url' =>$_POST['url_money']),
        'cookies' => array()
    ));
    $response = wp_remote_retrieve_body($response);
    echo $response;
}



function themoneytizer_retrieve_cmp() {
    $response_cmp = wp_remote_get('https://www.themoneytizer.com/cmp.php?lang='.$_POST['lang']);
    if (is_array($response_cmp)) {
        $body = $response_cmp['body'];
        echo $body;
    }
    else {
        echo '';
    }
}



function themoneytizer_register_user_and_site() {
    $url='https://www.themoneytizer.com/plugin/register_user_and_site';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array("lastname" =>get_option('nom_money'), "firstname" =>get_option('prenom_money'),"mail" =>get_option('mail_money'),"tel" =>get_option('tel_money'),"currency" =>get_option('currency_money'),"password" =>get_option('password_money'),"url" =>$_POST['url_money'],"theme" =>$_POST['theme_money'],"vu" =>$_POST['vu_money'],"newsletter" =>$_POST['newsletter_money'],"country"=>get_option('country_money'),"raison_ajout"=>get_option('raison_ajout_money'),"raison_ajout_autre"=>get_option('raison_ajout_autre_money'),"parrainage" =>get_option('parrainage_money'),"wordpress" =>"wordpress", "adresse"=>get_option('adresse_money'), "ville"=>get_option('ville_money'), "cp"=>get_option('cp_money'),"lang"=>$_POST['lang_money'], "lang_wordpress"=>get_option('WPLANG'), "type_structure"=>get_option('type_structure_money')),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}



function themoneytizer_register_site() {
    $url='https://www.themoneytizer.com/plugin/register_site';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array("login" =>$_POST['credentials'][0], "password" =>$_POST['credentials'][1], "url" =>$_POST['url_money'],"theme" =>$_POST['theme_money'],"vu" =>$_POST['vu_money'],"country"=>$_POST['country_money']),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}

function themoneytizer_login_user() {
    $url='https://www.themoneytizer.com/plugin/login_user';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array("login" =>$_POST['credentials'][0], "password" =>$_POST['credentials'][1]),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}



/*===== Registration End =====*/


/*===== Ads.txt & Cmp Start =====*/

function themoneytizer_get_ads_txt_file(){
    $response_ads_txt = wp_remote_get('https://www.themoneytizer.com/ads.txt');
    if (is_array($response_ads_txt)) {
        $body = $response_ads_txt['body'];
        echo $body;
    }
    else {
        echo '';
    }
}


function themoneytizer_check_ads_txt() {
    $url='https://www.themoneytizer.com/plugin/check_ads_txt';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array("site_id" =>$_POST['siteId']),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}


function add_cmp() {
    if(get_option('themoney_auto_cmp')==1){
        wp_enqueue_script( 'cmp', plugins_url( '/js/cmp.js', __FILE__ ), array(), '2.0', true );
    }
}

function themoneytizer_auto_ads_txt() {
    $response = new stdClass();
    if ($_POST['value']=='auto') {
        $response_ads_tm = wp_remote_get('https://www.themoneytizer.com/wp_ads_tm.txt');
        if (is_array($response_ads_tm)) {
            $tm_auto = $response_ads_tm['body'];
            $fp = fopen('../ads_tm.php', 'w+');
            fwrite($fp, $tm_auto);
            fclose($fp);

            $content = file_get_contents('../.htaccess');

            $htaccess = '#TheMoneytizer_ads_txt_start'.PHP_EOL;
            $htaccess .= '#/!\Don\'t place anything before these lines/!\ '.PHP_EOL;
            $htaccess .= '#/!\Ne rien mettre avant ces lignes/!\ '.PHP_EOL;
            $htaccess .= 'RewriteEngine on'.PHP_EOL;
            $htaccess .= 'RewriteRule ^ads.txt$ ads_tm.php'.PHP_EOL;
            $htaccess .= '#TheMoneytizer_ads_txt_end'.PHP_EOL;
            $htaccess .= $content;
            $fp = fopen('../.htaccess', 'w+');
            fwrite($fp, $htaccess);
            fclose($fp);

            update_option('themoney_auto_ads_tm', '1');

            $response->status = 'success';
            $response->message = __('Placement automatique de l\'ads.txt activé avec succès','themoneytizer');
        } else {
            $response->status = 'error';
        }
    } else {
        $htaccess = file_get_contents('../.htaccess');

        $htaccess = str_replace('#TheMoneytizer_ads_txt_start'.PHP_EOL, '', $htaccess);
        $htaccess = str_replace('#/!\Don\'t place anything before these lines/!\ '.PHP_EOL, '', $htaccess);
        $htaccess = str_replace('#/!\Ne rien mettre avant ces lignes/!\ '.PHP_EOL, '', $htaccess);
        $htaccess = str_replace('RewriteEngine on'.PHP_EOL, '', $htaccess);
        $htaccess = str_replace('RewriteRule ^ads.txt$ ads_tm.php'.PHP_EOL, '', $htaccess);
        $htaccess = str_replace('#TheMoneytizer_ads_txt_end'.PHP_EOL, '', $htaccess);

        $fp = fopen('../.htaccess', 'w+');
        fwrite($fp, $htaccess);
        fclose($fp);

        update_option('themoney_auto_ads_tm', '0');

        $response->status = 'success';
    }

    echo json_encode($response);
}

function themoneytizer_auto_cmp() {
    $response = new stdClass();
    if($_POST['value']=='auto'){
        $response_cmp = wp_remote_get('https://www.themoneytizer.com/cmp.php?code=1');
        if (is_array($response_cmp)) {
            $body = $response_cmp['body'];
            $plugin_name = get_plugin_data( __FILE__ )['TextDomain'];
            $fp = fopen('../wp-content/plugins/'.$plugin_name.'/js/cmp.js', 'w+');
            fwrite($fp, $body);
            update_option('themoney_auto_cmp', '1');
            $response->status = 'success';
            $response->message = __('Placement automatique de la CMP activé avec succès', 'themoneytizer');
        } else {
            $response->status = 'error';
        }
    } else {
        $plugin_name = get_plugin_data( __FILE__ )['TextDomain'];
        $fp = fopen('../wp-content/plugins/'.$plugin_name.'/js/cmp.js', 'w+');
        fwrite($fp, '');
        update_option('themoney_auto_cmp', '0');

        $response->status = 'success';
    }
    echo json_encode($response);
}

function themoneytizer_check_cmp() {
    $url='https://www.themoneytizer.com/plugin/check_cmp';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array("site_id" =>$_POST['siteId']),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}

function themoneytizer_get_cmp(){
    $response_cmp = wp_remote_get('https://www.themoneytizer.com/cmp.php?lang='.$_POST['code']);
    if (is_array($response_cmp)) {
        $body = $response_cmp['body'];
        echo $body;
    }
    else {
        echo '';
    }
}


function themoneytizer_reset_plugin(){
	update_option('themoneytizer_setting_siteid', '');

    $response = new stdClass();
    $response->status = 'success';
}


/*===== Ads.txt & Cmp End =====*/


/*===== Format Delivery Start =====*/

function themoneytizer_generate_tag() {
    $url='https://www.themoneytizer.com/plugin/generate_tag';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array('ad_id' => $_POST['adID'], 'site_id' => $_POST['siteID']),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}



function themoneytizer_put_format_on_pending() {
    $url='https://www.themoneytizer.com/plugin/putFormatOnPending';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array('ad_id' => $_POST['adID'], 'site_id' => $_POST['siteID']),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}



function themoneytizer_reactivate_tag() {
    $url='https://www.themoneytizer.com/plugin/reactivate_tag';

    $response = wp_remote_post($url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'sslverify' => false,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array("tag_id" =>$_POST['tagID']),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}



/*===== Format Delivery End =====*/


/*===== Profile & bank editing Start =====*/

function themoneytizer_update_bank_data() {
    $url='https://www.themoneytizer.com/plugin/update_bank_data';
    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'sslverify' => false,
        'blocking' => true,
        'headers' => array(),
        'body' => array("user_id"=>get_option('user_id_money'), "bank_name"=>$_POST["bank_name"], "bank_iban"=>$_POST["bank_iban"], "bank_bic"=>$_POST["bank_bic"], "bank_name_bank"=>$_POST["bank_name_bank"], "bank_adress_bank"=>$_POST["bank_adress_bank"], "bank_country_bank"=>$_POST["bank_country_bank"], "bank_city_bank"=>$_POST["bank_city_bank"], "bank_zip_bank"=>$_POST["bank_zip_bank"], "paypal"=>$_POST["paypal_money"]),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}


function themoneytizer_update_process_request() {
    $url='https://www.themoneytizer.com/plugin/update_personal_data';
    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'sslverify' => false,
        'blocking' => true,
        'headers' => array(),
        'body' => array("user_id"=>get_option('user_id_money'), "prenom"=>$_POST["prenom"], "nom"=>$_POST["nom"], "mail"=>$_POST["mail"], "tel"=>$_POST["tel"], "adresse"=>$_POST["adresse"], "ville"=>$_POST["ville"], "cp"=>$_POST["cp"], "pays"=>$_POST["pays"], "user_type_structure" => $_POST["structure"],"user_entreprise"=>$_POST["entreprise"], "user_siren"=>$_POST["siren"], "user_tva"=>$_POST["tva"]),

        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body($response);
    echo $response;
}


/*===== Profile & bank editing End =====*/


/*===== Statistics Start =====*/

function themoneytizer_get_stats_process_request() {
    $url='https://www.themoneytizer.com/plugin/getStats';
    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'sslverify' => false,
        'blocking' => true,
        'headers' => array(),
        'body' => array("site_id"=>get_option('id_site_money'), "periode"=>$_POST["periode"], "lang"=>get_option('WPLANG'), "date_from"=>$_POST["date_from"], "date_to"=>$_POST["date_to"], "format"=>$_POST["format"], "imp_yes"=>$_POST["imp_yes"] ),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body( $response );

    if ( is_wp_error( $response ) ) {
       $error_message = $response->get_error_message();
       echo "Something went wrong: $error_message";
    }
    else {
       print_r( $response );
       die();
    }
}


function themoneytizer_get_stats_vanilla() {
    $url='https://www.themoneytizer.com/plugin/get_stats_vanilla';
    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'sslverify' => false,
        'blocking' => true,
        'headers' => array(),
        'body' => array("site_id"=>get_option('id_site_money'), "date_from"=>$_POST["date_from"], "date_to"=>$_POST["date_to"]),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body( $response );

    if ( is_wp_error( $response ) ) {
        $error_message = $response->get_error_message();
        echo "Something went wrong: $error_message";
    }
    else {
        print_r( $response );
        die();
    }
}


function themoneytizer_get_stats_visibility() {
    $url='https://www.themoneytizer.com/plugin/get_stats_visibility';
    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'sslverify' => false,
        'blocking' => true,
        'headers' => array(),
        'body' => array("site_id"=>get_option('id_site_money'), "date_from"=>$_POST["date_from"], "date_to"=>$_POST["date_to"]),
        'cookies' => array()
    ));

    $response = wp_remote_retrieve_body( $response );

    if ( is_wp_error( $response ) ) {
        $error_message = $response->get_error_message();
        echo "Something went wrong: $error_message";
    }
    else {
        print_r( $response );
        die();
    }
}

/*====== Add actions ====== */

add_action('wp_ajax_retrieve_cmp', 'themoneytizer_retrieve_cmp');
add_action('wp_ajax_check_registration_validity', 'themoneytizer_check_registration_validity');
add_action('wp_ajax_register_user_and_site', 'themoneytizer_register_user_and_site');
add_action('wp_ajax_register_site', 'themoneytizer_register_site');
add_action('wp_ajax_login_user', 'themoneytizer_login_user');
add_action('wp_ajax_get_ads_txt', 'themoneytizer_get_ads_txt_file');
add_action('wp_ajax_check_ads_txt', 'themoneytizer_check_ads_txt');
add_action('wp_print_scripts', 'themoneytizer_test_ajax_load_scripts');
add_action('wp_enqueue_scripts', 'add_cmp');
add_action('wp_ajax_auto_ads_txt', 'themoneytizer_auto_ads_txt');
add_action('wp_ajax_auto_cmp', 'themoneytizer_auto_cmp');
add_action('wp_ajax_check_cmp', 'themoneytizer_check_cmp');
add_action('wp_ajax_get_cmp', 'themoneytizer_get_cmp');
add_action('wp_ajax_reset_plugin', 'themoneytizer_reset_plugin');
add_action('wp_ajax_generate_tag', 'themoneytizer_generate_tag');
add_action('wp_ajax_put_format_on_pending', 'themoneytizer_put_format_on_pending');
add_action('wp_ajax_reactivate_tag', 'themoneytizer_reactivate_tag');
add_action('wp_ajax_update_bank_data', 'themoneytizer_update_bank_data');
add_action('wp_ajax_update', 'themoneytizer_update_process_request');
add_action('wp_ajax_get_stats', 'themoneytizer_get_stats_process_request');
add_action('wp_ajax_get_stats_vanilla', 'themoneytizer_get_stats_vanilla');
add_action('wp_ajax_get_stats_visibility', 'themoneytizer_get_stats_visibility');