fgc-add-to-gtm.php 29.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
<?php
/**
 * Plugin Name: Fgc Add To Google Tag Manager
 * Plugin URI: http://fgc.vn
 * Description: Fgc Add To Google Tag Manager
 * Author: Phuong An.
 * Author URI: http://fgc.vn
 * Version: 1.0
 *
 * Copyright 2016 Prospress, Inc.  (email : freedoms@prospress.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package		WooCommerce
 * @author		Phuong An
 * @since		1.0
 */
if (!class_exists('FgcRequest')) {
    require( 'request.class.php' );
}

add_action('admin_menu', 'fgc_add_to_gtm_plugin_setup_menu');

function fgc_add_to_gtm_plugin_setup_menu() {
//create new top-level menu
    add_menu_page('Custom Google Analytics Page', 'Custom GA', 'manage_options', 'fgc-add-to-gtm', 'fgc_add_to_gtm_plugin_init');
//call register settings function
    add_action('admin_init', 'register_fgc_add_to_gtm_plugin_settings');
}

function register_fgc_add_to_gtm_plugin_settings() {
//register our settings
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_buy_subscription_product');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_buy_onetime_product');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_upgrade_successful');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_downgrade_successful');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_take_month_off_successful');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_cancelled_subscription');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_user_register_enabled');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_login_by_email');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_login_by_facebook');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_deadpan_guy_videos');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_share_video_icon_on_homepage');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_share_icon_on_challenge_results_page');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_share_icon_on_thankyou_page');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_share_icon_on_myaccount_page');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_play_video_homepage');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_click_pause_video_homepage');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_purchase_complete');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_initiate_checkout');
    register_setting('fgc-add-to-gtm-plugin-settings-group', 'fgc_add_to_gtm_tracking_lead_submission');
}

function fgc_add_to_gtm_plugin_init() {
    ?>
    <div class="wrap">
        <h1>Custom Google Analytics Page</h1>

        <form method="post" action="options.php">
            <?php settings_fields('fgc-add-to-gtm-plugin-settings-group'); ?>
            <?php do_settings_sections('fgc-add-to-gtm-plugin-settings-group'); ?>
            <table class="form-table">
                <tbody>
                    <?php
                    $listOptions = array(
                        array(
                            "name" => "fgc_add_to_gtm_tracking_buy_subscription_product",
                            "label" => "Tracking Buy Subscription Product",
                            "description" => "Tracking Buy Subscription Product"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_buy_onetime_product",
                            "label" => "Tracking Buy One-Time Product",
                            "description" => "Tracking Buy One-Time Product"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_purchase_complete",
                            "label" => "Tracking Purchase Complete",
                            "description" => "Tracking Purchase Complete"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_initiate_checkout",
                            "label" => "Tracking Initiate Checkout",
                            "description" => "Tracking Initiate Checkout"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_upgrade_successful",
                            "label" => "Tracking Upgrade Successful",
                            "description" => "Tracking Upgrade Successful"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_downgrade_successful",
                            "label" => "Tracking Downgrade Successful",
                            "description" => "Tracking Downgrade Successful"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_take_month_off_successful",
                            "label" => "Tracking Take Month Off Successful",
                            "description" => "Tracking Take Month Off Successful"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_cancelled_subscription",
                            "label" => "Tracking Cancelled Subscription",
                            "description" => "Tracking Cancelled Subscription"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_user_register_enabled",
                            "label" => "Tracking User Register",
                            "description" => "Tracking User Register"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_login_by_email",
                            "label" => "Tracking Login By Email",
                            "description" => "Tracking Login By Email"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_login_by_facebook",
                            "label" => "Tracking Login By Facebook",
                            "description" => "Tracking Login By Facebook"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_lead_submission",
                            "label" => "Tracking Lead Submission",
                            "description" => "Tracking Lead Submission"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_deadpan_guy_videos",
                            "label" => "Tracking Click Deadpan Guy Videos",
                            "description" => "Tracking Click Deadpan Guy Videos"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_share_video_icon_on_homepage",
                            "label" => "Tracking Click Share Video Icon On Homepage",
                            "description" => "Tracking Click Share Video Icon On Homepage"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_share_icon_on_challenge_results_page",
                            "label" => "Tracking Click Share Icon On Challenge Results",
                            "description" => "Tracking Click Share Icon On Challenge Results"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_share_icon_on_thankyou_page",
                            "label" => "Tracking Click Share Icon On Thankyou Page",
                            "description" => "Tracking Click Share Icon On Thankyou Page"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_share_icon_on_myaccount_page",
                            "label" => "Tracking Click Share Icon On My Account Page",
                            "description" => "Tracking Click Share Icon On My Account Page"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_play_video_homepage",
                            "label" => "Tracking Click Play Video Homepage",
                            "description" => "Tracking Click Play Video Homepage"
                        ),
                        array(
                            "name" => "fgc_add_to_gtm_tracking_click_pause_video_homepage",
                            "label" => "Tracking Click Pause Video Homepage",
                            "description" => "Tracking Click Pause Video Homepage"
                        )
                    );
                    $isFirst = true;
                    foreach ($listOptions as $option) {
                        fgc_add_to_gtm_setting_field($option, $isFirst);
                        if ($isFirst) {
                            $isFirst = false;
                        }
                    }
                    ?>
                </tbody>


            </table>

            <?php submit_button(); ?>

        </form>
    </div>
    <?php
}

function fgc_add_to_gtm_setting_field($option, $isFirst) {
    ?>
    <tr valign="top">
        <th scope="row" class="titledesc">
            <?php if ($isFirst) { ?>
                <label for="<?php echo $option['name'] ?>">Tracking Options</label>
            <?php } ?>
        </th>
        <td class="forminp">
            <fieldset>
                <legend class="screen-reader-text"><span></span></legend>
                <label for="<?php echo $option['name'] ?>">
                    <input class="" type="checkbox" name="<?php echo $option['name'] ?>" id="<?php echo $option['name'] ?>" style="" value="1" <?php echo (get_option($option['name']) == '1') ? '   checked="checked" ' : '' ?> > <?php echo $option['label'] ?></label><br>
                <p class="description"><?php echo $option['description'] ?></p>
            </fieldset>
        </td>
    </tr>
    <?php
}

add_filter('wp_head', 'fgc_add_trackings_google_analytics');
add_action('init', 'fgc_add_trackings_google_analytics_code_to_session', 20);

function fgc_add_trackings_google_analytics($content) {
    echo $_SESSION['fgcGoogleAnalyticsCode'];
    return $content;
}

function fgc_add_trackings_google_analytics_code_to_session() {
    $html = '';
    $option_names = array(
        "fgc_add_to_gtm_tracking_buy_subscription_product",
        "fgc_add_to_gtm_tracking_buy_onetime_product",
        "fgc_add_to_gtm_tracking_upgrade_successful",
        "fgc_add_to_gtm_tracking_downgrade_successful",
        "fgc_add_to_gtm_tracking_take_month_off_successful",
        "fgc_add_to_gtm_tracking_cancelled_subscription",
        "fgc_add_to_gtm_tracking_user_register_enabled",
        "fgc_add_to_gtm_tracking_login_by_email",
        "fgc_add_to_gtm_tracking_login_by_facebook",
        "fgc_add_to_gtm_tracking_click_deadpan_guy_videos",
        "fgc_add_to_gtm_tracking_click_share_video_icon_on_homepage",
        "fgc_add_to_gtm_tracking_click_share_icon_on_challenge_results_page",
        "fgc_add_to_gtm_tracking_click_share_icon_on_thankyou_page",
        "fgc_add_to_gtm_tracking_click_share_icon_on_myaccount_page",
        "fgc_add_to_gtm_tracking_click_play_video_homepage",
        "fgc_add_to_gtm_tracking_click_pause_video_homepage",
        "fgc_add_to_gtm_tracking_purchase_complete",
        "fgc_add_to_gtm_tracking_initiate_checkout",
        "fgc_add_to_gtm_tracking_lead_submission"
    );
    $html .= '<script type="text/javascript">'
            . '/* Google Analytics Custom Tracking */'
            . 'jQuery(document).ready(function ($) { ';
    foreach ($option_names as $option_name) {
        if (fgc_check_tracking_setting($option_name)) {
            $html .= fgc_add_tracking_google_analytics($option_name);
        }
    }
    $html .= ' });</script>';
    $_SESSION['fgcGoogleAnalyticsCode'] = $html;
}

function fgc_add_tracking_google_analytics($name) {
    switch ($name) {

        //    Add track page view: /virtual/order-confirmation/subscription/ after user buy subscription product
        case 'fgc_add_to_gtm_tracking_buy_subscription_product':
            return fgc_script_tracking('TRACKING_BUY_SUBSCRIPTION_PRODUCT', "dataLayer.push({'event':'VirtualPageview','virtualPageURL':'/virtual/order-confirmation/subscription/'});\n");

        //    Add track page view: /virtual/order-confirmation/one-time/ after user buy one-time product
        case 'fgc_add_to_gtm_tracking_buy_onetime_product':
            return fgc_script_tracking('TRACKING_BUY_ONETIME_PRODUCT', "dataLayer.push({'event':'VirtualPageview','virtualPageURL':'/virtual/order-confirmation/one-time/'});\n");

        //    Add event after upgrade is successful
        case 'fgc_add_to_gtm_tracking_upgrade_successful':
            return fgc_script_tracking('isUpgradeSubscriptionGA', "
                //    Add event after upgrade is successful \n
                dataLayer.push({'eventCategory': 'Modify Subscription', 'eventAction': 'Upgrade', 'eventLabel': 'Upgrade'}); \n
                 ");

        case 'fgc_add_to_gtm_tracking_downgrade_successful':
            return fgc_script_tracking('isDowngradeSubscriptionGA', "
                 //    Add event after downgrade is successful \n
                 dataLayer.push({'eventCategory': 'Modify Subscription', 'eventAction': 'Downgrade', 'eventLabel': 'Downgrade'});  \n");
        case 'fgc_add_to_gtm_tracking_take_month_off_successful':
            return fgc_script_tracking('isSetTakeMonthOff', "
                 //    Add event after set take month off is successful
                  dataLayer.push({'eventCategory': 'Modify Subscription', 'eventAction': 'Skip Month', 'eventLabel':'Skip Month'});  \n ");

        case 'fgc_add_to_gtm_tracking_cancelled_subscription':
            return fgc_script_tracking('isCancelled', "
                 //    Add pageview after cancelled subscription
                 dataLayer.push({'event':'VirtualPageview','virtualPageURL':'/virtual/account-cancellation/'});\n
                 dataLayer.push({'eventCategory': 'Modify Subscription', 'eventAction': 'Cancelled Subscription', 'eventLabel':'Cancelled Subscription'});  \n  ");

        case 'fgc_add_to_gtm_tracking_user_register_enabled':
            return fgc_script_tracking('isNewUser', "
                 //    Add track page view: /virtual/account-confirmation/ when user register
                    dataLayer.push({'event':'VirtualPageview','virtualPageURL':'/virtual/account-confirmation/'});\n");

        case 'fgc_add_to_gtm_tracking_login_by_email':
            return fgc_script_tracking('loginByEmail', "dataLayer.push({'eventCategory': 'Login', 'eventAction': 'emailLogin', 'eventLabel': 'Login with email and password'}); \n");

        case 'fgc_add_to_gtm_tracking_login_by_facebook':
            return fgc_script_tracking('loginByFacebook', "dataLayer.push({'eventCategory': 'Login', 'eventAction': 'facebookLogin', 'eventLabel': 'Login with Facebook'}); \n");

        //    Add event play video with title of the video
        case 'fgc_add_to_gtm_tracking_click_deadpan_guy_videos':
            return "$(document).on('click', '.list-video .thumb-video', function () {
                                 dataLayer.push({'eventCategory': 'Deadpan Guy Videos', 'eventAction': 'play', 'eventLabel': $(this).find('.the-title-video .video-title').text().trim()});
                    });\n";

        case 'fgc_add_to_gtm_tracking_click_share_video_icon_on_homepage':
            ob_start();
            ?>
            //    Add onClick event on share video Twitter icon on Homepage to send Event to GA
            $('.home.page .tvshare a.share-twitter').attr("onClick", " dataLayer.push({'eventCategory': 'Share Home Video', 'eventAction': 'click', 'eventLabel':'Twitter'});   ");
            //    Add onClick event on share video Facebook icon on Homepage to send Event to GA
            $('.home.page .tvshare a.share-facebook').attr("onClick", " dataLayer.push({'eventCategory': 'Share Home Video', 'eventAction': 'click', 'eventLabel':'FB'});   });");
            <?php
            $return = ob_get_contents();
            ob_end_clean();
            return $return;

        case 'fgc_add_to_gtm_tracking_click_share_icon_on_challenge_results_page':
            ob_start();
            ?>
            //    Add onClick event on Twitter icon of Changllenge Results page to send Event to GA
            $('.page-template-challenge_results a.share-twitter').attr("onClick", "dataLayer.push({'eventCategory': 'Share REIZE Challenge', 'eventAction': 'click', 'eventLabel':'Twitter'});sendAjaxAddACTag('eventClickToShareChallenge');");
            //    Add onClick event on Facebook icon of Changllenge Results page to send Event to GA
            $('.page-template-challenge_results a.share-facebook').attr("onClick", "dataLayer.push({'eventCategory': 'Share REIZE Challenge', 'eventAction': 'click', 'eventLabel':'FB'});sendAjaxAddACTag('eventClickToShareChallenge');");
            //    Add onClick event on Email icon of Changllenge Results page to send Event to GA
            $('.page-template-challenge_results a.share-email').attr("onClick", "dataLayer.push({'eventCategory': 'Share REIZE Challenge', 'eventAction': 'click', 'eventLabel':'Email'});sendAjaxAddACTag('eventClickToShareChallenge');");
            <?php
            $return = ob_get_contents();
            ob_end_clean();
            return $return;

        case 'fgc_add_to_gtm_tracking_click_share_icon_on_thankyou_page':
            ob_start();
            ?>
            //    Add onClick evemt on Twitter icon on Thankyou page to send Event to GA
            $('.woocommerce-order-received a.share-twitter').attr("onClick", " dataLayer.push({'eventCategory': 'Share Affiliate URL - Order Summary', 'eventAction': 'click', 'eventLabel':'Twitter (" + $('#id_affiliates').val() + ")'});");
            //    Add onClick evemt on Facebook icon on Thankyou page to send Event to GA
            $('.woocommerce-order-received a.share-facebook').attr("onClick", " dataLayer.push({'eventCategory': 'Share Affiliate URL - Order Summary', 'eventAction': 'click', 'eventLabel':'FB (" + $('#id_affiliates').val() + ")'});");
            //    Add onClick evemt on Email icon on Thankyou page to send Event to GA
            $('.woocommerce-order-received a.share-email').attr("onClick", " dataLayer.push({'eventCategory': 'Share Affiliate URL - Order Summary', 'eventAction': 'click', 'eventLabel':'Email (" + $('#id_affiliates').val() + ")'});");

            <?php
            $return = ob_get_contents();
            ob_end_clean();
            return $return;

        case 'fgc_add_to_gtm_tracking_click_share_icon_on_myaccount_page':
            ob_start();
            ?>
            //    Add onClick evemt on Twitter icon on MyAccount page to send Event to GA
            $('.woocommerce-account a.share-twitter').attr("onClick", "dataLayer.push({'eventCategory': 'Share Affiliate URL - My Account', 'eventAction': 'click', 'eventLabel':'Twitter (" + $('#id_affiliates').val() + ")'}); ");
            //    Add onClick evemt on Facebook icon on MyAccount page to send Event to GA
            $('.woocommerce-account a.share-facebook').attr("onClick", "dataLayer.push({'eventCategory': 'Share Affiliate URL - My Account', 'eventAction': 'click', 'eventLabel':'FB (" + $('#id_affiliates').val() + ")'}); ");
            //    Add onClick evemt on Email icon on MyAccount page to send Event to GA
            $('.woocommerce-account a.share-email').attr("onClick", "dataLayer.push({'eventCategory': 'Share Affiliate URL - My Account', 'eventAction': 'click', 'eventLabel':'Email (" + $('#id_affiliates').val() + ")'}); ");
            <?php
            $return = ob_get_contents();
            ob_end_clean();
            return $return;

        case 'fgc_add_to_gtm_tracking_click_play_video_homepage':
            return fgc_update_cookie_tracking_video_homepage('enableTrackingPlay', 'fgc_add_to_gtm_tracking_click_play_video_homepage');

        case 'fgc_add_to_gtm_tracking_click_pause_video_homepage':
            return fgc_update_cookie_tracking_video_homepage('enableTrackingPause', 'fgc_add_to_gtm_tracking_click_pause_video_homepage');

        case 'fgc_add_to_gtm_tracking_purchase_complete':
            $return = '';
            if (isset($_COOKIE['purchaseComplete'])) {
                $purchase_complete_value = $_COOKIE['purchaseComplete'];
                setcookie('purchaseComplete', '', time() - 3600, '/');
                if ($purchase_complete_value == '81') {
                    $return = ""
                            . "//   Tracking Purchase Complete \n "
                            . "dataLayer.push({'eventCategory': 'purchase', 'eventName': 'subscription', 'eventValue': '81'}); \n";
                } else if ($purchase_complete_value == '35') {
                    $return = ""
                            . "//   Tracking Purchase Complete \n "
                            . "dataLayer.push({'eventCategory': 'purchase', 'eventName': 'one-time', 'eventValue': '35'}); \n";
                }
            }
            return $return;

        case 'fgc_add_to_gtm_tracking_initiate_checkout':
            $_uri = $_SERVER['REQUEST_URI'];
            $return = '';
            if (isset($_COOKIE['initiateCheckout'])) {
                if (strpos($_uri, 'login-page')) {
                    if ($_COOKIE['initiateCheckout'] != 'step1') {
                        setcookie('initiateCheckout', '', time() - 3600, '/');
                    } else {
                        setcookie('initiateCheckout', 'step2', time() + 3600, '/');
                    }
                } else if (strpos($_uri, 'checkout') && !isset($_REQUEST['action'])) {
                    if ($_COOKIE['initiateCheckout'] == 'step2') {
                        $return = "
                            // Tracking Initiate Checkout
                             dataLayer.push({'eventCategory': 'checkout', 'eventName': 'initiate'});
                             \n";
                    }
                    setcookie('initiateCheckout', '', time() - 3600, '/');
                } else {
                    setcookie('initiateCheckout', '', time() - 3600, '/');
                }
            }
            return $return;

        case 'fgc_add_to_gtm_tracking_lead_submission':
            return fgc_script_tracking("message_free_sample", "
                dataLayer.push({'eventCategory': 'lead-submission', 'eventName': 'free-sample'});
                \n");

        default:
            return "";
    }
}

function fgc_check_tracking_setting($name) {
    if (!$name) {
        return false;
    }
    return (get_option($name) == '1') ? true : false;
}

function fgc_script_tracking($cookie_name, $script) {
    if (isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name] != '') {
        if ($cookie_name != 'isUpgradeSubscriptionGA' && $cookie_name != 'isDowngradeSubscriptionGA' && $cookie_name != 'isSetTakeMonthOff' && $cookie_name != 'TRACKING_BUY_SUBSCRIPTION_PRODUCT' && $cookie_name != 'TRACKING_BUY_ONETIME_PRODUCT' && $cookie_name != 'isCancelled') {
            setcookie($cookie_name, '', time() - 999999, '/');
        }
        return $script;
    }
    return '';
}

//
//function fgc_script_tracking_fb($cookie_name, $script) {
////    if (isset($_COOKIE[$cookie_name]) && is_woocommerce()) {
//    if (isset($_COOKIE[$cookie_name])) {
////        setcookie($cookie_name, '', time() - 3600, '/');
//        return $script;
//    }
//    return '';
//}

function fgc_update_cookie_tracking_video_homepage($cookie_name, $setting_name) {
    if (fgc_check_tracking_setting($setting_name)) {
        setcookie($cookie_name, '1', time() + 3600, '/');
    } else {
        setcookie($cookie_name, '', time() - 3600, '/');
    }
    return '';
}

//add_action('woocommerce_payment_complete', 'fgc_add_trackings_bought_product', 10);

function fgc_add_trackings_bought_product($order_id) {
    if (WC_Subscriptions_Order::order_contains_subscription($order_id)) {
        if (fgc_check_tracking_setting('fgc_add_to_gtm_tracking_buy_subscription_product')) {
            if (get_post_meta($order_id, '_subscription_switch', true) == '') {
                setcookie("TRACKING_BUY_SUBSCRIPTION_PRODUCT", '1', time() + 3600, '/');
            }
        }
    } else {
        if (fgc_check_tracking_setting('fgc_add_to_gtm_tracking_buy_onetime_product'))
            setcookie("TRACKING_BUY_ONETIME_PRODUCT", '1', time() + 3600, '/');
    }
}

add_action('cancelled_subscription', 'fgc_add_trackings_cancelled_subscription', 10, 2);

function fgc_add_trackings_cancelled_subscription($user_id, $subscription_key) {
    if (fgc_check_tracking_setting('fgc_add_to_gtm_tracking_cancelled_subscription')) {
        setcookie("isCancelled", '1', time() + 3600, '/');
    }
}

add_action('user_register', 'fgc_add_cookie_is_new_user', 10, 1);

function fgc_add_cookie_is_new_user($user_id) {
    if (fgc_check_tracking_setting('fgc_add_to_gtm_tracking_user_register_enabled')) {
        setcookie('isNewUser', '1', time() + 3600, '/');
    }
}

add_action('woocommerce_order_status_completed', 'fgc_add_cookie_is_upgrade_or_downgrade');

//add_action('woocommerce_payment_complete', 'fgc_add_cookie_is_upgrade_or_downgrade');

function fgc_add_cookie_is_upgrade_or_downgrade($order_id) {
    if (fgc_check_tracking_setting('fgc_add_to_gtm_tracking_upgrade_successful') || fgc_check_tracking_setting('fgc_add_to_gtm_tracking_downgrade_successful')) {
        $subscription_id = get_post_meta($order_id, '_subscription_switch', true);
        if ($subscription_id != '') {
            global $wpdb;
            $orderItemsTable = $wpdb->prefix . 'woocommerce_order_items';
            $query = "SELECT * FROM `$orderItemsTable` WHERE  `order_item_type` = 'line_item_switched'  AND `order_id` = $subscription_id ORDER BY `order_item_id` DESC ";
            $result = $wpdb->get_results($query);
            if (!empty($result)) {
                $oldItemID = $result[0]->order_item_id;
                if ($oldItemID != '') {
                    $query = "SELECT * FROM `$orderItemsTable` WHERE   `order_item_type` = 'line_item'  AND `order_id` = $subscription_id ORDER BY `order_item_id` DESC ";
                    $result = $wpdb->get_results($query);
                    if (!empty($result)) {
                        $newItemID = $result[0]->order_item_id;
                    }
                    if ($newItemID != '') {
                        $oldDrink = (int) wc_get_order_item_meta($oldItemID, 'drinks');
                        $newDrink = (int) wc_get_order_item_meta($newItemID, 'drinks');
                        if ($oldDrink > $newDrink) {
                            setcookie('isDowngradeSubscriptionGA', '1', time() + 3600, '/');
//                        FGC_ActiveCampaign::
                        } else if ($oldDrink < $newDrink) {
                            setcookie('isUpgradeSubscriptionGA', '1', time() + 3600, '/');
                        }
                    }
                }
            }
        }
    }
}

add_action('wp_login', 'fgc_add_cookie_after_login_successful', 10, 2);

function fgc_add_cookie_after_login_successful($user_login, $user) {
    if (fgc_check_tracking_setting('fgc_add_to_gtm_tracking_login_by_email')) {
        setcookie('loginByEmail', '1', time() + 3600, '/');
    }
}

add_action('woocommerce_payment_complete', 'fgc_add_cookie_purchase_complete', 10);

function fgc_add_cookie_purchase_complete($order_id) {
    $order = new WC_Order($order_id);
    foreach ($order->get_items() as $key => $value) {
        if ($value['variation_id'] > 0) {
            setcookie('purchaseComplete', '81', time() + 3600, '/');
        } else {
            setcookie('purchaseComplete', '35', time() + 3600, '/');
        }
    }
}

add_action('woocommerce_payment_complete', 'fgc_set_session_gtm_after_purchase_complete', 10);

function fgc_set_session_gtm_after_purchase_complete($order_id) {
    $_SESSION['addGtmAfterPurchaseComplete'] = $order_id;
    fgc_add_trackings_bought_product($order_id);
//    FgcRequest::request(get_bloginfo('url') . '/?action=checkGtmAfterPaymentComplete');
}

//add_action('plugins_loaded', 'fgc_send_ajax_gtm_after_load_page', 10);

function fgc_send_ajax_gtm_after_load_page() {
    if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'checkGtmAfterPaymentComplete') {
        if (!session_id()) {
            session_start();
        }
        if (isset($_SESSION['addGtmAfterPurchaseComplete']) && $_SESSION['addGtmAfterPurchaseComplete'] != '') {
            $order_id = $_SESSION['orderId'];
            fgc_add_cookie_purchase_complete($order_id);
            fgc_add_cookie_is_upgrade_or_downgrade($order_id);
        }

        exit();
    }
}