<?php

$aid = "";
$tid = "";
$Checkboxs = array();

//ini_set('error_log', WP_CONTENT_DIR . '/debugging.log');
//ini_set('display_errors', 'Off');
//ini_set('error_reporting', E_ALL);

//define('WP_DEBUG_DISPLAY', false);


/**
 * Plugin Name: Gameball
 * Plugin URI: https://www.gameball.co/
 * Description: Game-like Loyalty & Rewards : Challenge your customer & boost engagement with a game-like experience of earning points, collecting badges, and leveling up. Customers can then exchange these points with rewards and discount coupons. 
 * Version: 1.43.0
 * Author: Gameball
 * Author URI:  https://www.gameball.co/
 */

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'gb_salcode_add_plugin_page_settings_link');
function gb_salcode_add_plugin_page_settings_link($links)
{
    /*
	$links[] = '<a href="' .
		admin_url( 'options-general.php?page=gameball' ) .
		'">' . __('Settings') . '</a>';
	return $links;
	*/
    $links = array_merge(array(
        '<a href="' . esc_url(admin_url('admin.php?page=GameballPlugin')) . '">' . __('Settings', 'textdomain') . '</a>'
    ), $links);

    return $links;
}

add_filter('plugin_row_meta', 'gb_plugin_row_meta', 10, 2);

function gb_plugin_row_meta($links, $file)
{

    //to pass only on GB
    if ($file === 'gameball/Gameball.php') {
        $new_links = array(
            '<a href="https://app.gameball.co" target="_blank">Dashboard</a>',
            '<a href="https://help.gameball.co" target="_blank">Help Center</a>'
        );

        $links = array_merge($links, $new_links);
    }
    //}

    return $links;
}



add_filter('query_vars', function ($query_vars) {
    $query_vars[] = 'gbtarget';
    $query_vars[] = 'ReferralCode';
    return $query_vars;
});

add_action('init', 'gb_pmg_rewrite_add_rewrites_77817688');
function gb_pmg_rewrite_add_rewrites_77817688()
{
    add_rewrite_rule(
        'gb-wp-woocom/?$',
        'index.php?gbtarget=1',
        'top'
    );
    if (!defined('ABSPATH')) {
        //  die;
        exit;
    }

    if (!session_id()) {
        $pre_fix_ask = 'gb_c_ask_about_points';
        // setcookie($pre_fix_ask, 'block', time() + (86400 * 30), "/");
    }
}

add_action('template_redirect', function () {
    $custom = intval(get_query_var('gbtarget'));
    $referral = get_query_var('ReferralCode');

    if (isset($referral) && $referral != '') {

        $referral_code = sanitize_text_field($referral);
        setcookie('ReferralCode', $referral_code, time() + (86400 * 30), "/");
    }

    if ($custom == 1) {
        if ($_POST['target'] == 'function') {
            gameball_rewrite_function_json_feed();
        } else if ($_POST['target'] == 'timestamp') {
            gameball_rewrite_timestamp_json_feed();
        }
    }
});

register_activation_hook(__FILE__, 'gb_pmg_rewrite_activation');
function gb_pmg_rewrite_activation()
{
    gb_pmg_rewrite_add_rewrites_77817688();
    flush_rewrite_rules();
    // error_log("Flushhh");
}


function gameball_rewrite_function_json_feed()
{   //error_log("SETTING HOLD REFERENCE");
    header('Content-Type: text/plain');
    if (isset($_POST['hold_reference'])) {
        $external_id = get_current_user_id();
        $pre_fix = 'gb_c_' . $external_id . '_hold_reference';
        $hold_ref = sanitize_text_field($_POST['hold_reference']);
        // error_log($hold_ref);
        setcookie($pre_fix,  $hold_ref,  time() + (600), "/");
    }
    die;
}

function gameball_rewrite_timestamp_json_feed()
{
    header('Content-Type: text/plain');
    $result = array();
    $hashed_time = gmdate("ymdHis");
    $transaction_time = gmdate("Y-m-d") . "T" . gmdate("H:i:s");
    $result['transactionTime'] = $transaction_time;
    $external_id = sanitize_text_field($_POST['external_id']);
    $transaction_key = sanitize_key($GLOBALS['tid']);

    if (!is_numeric($_POST['amount'])) {
        return;
    } else {
        $amount =  sanitize_text_field($_POST['amount']);
    }
    $result['hashedBodyHold'] = sha1($external_id . ":" . $hashed_time . ":" . $amount . ":" . $transaction_key);
    $result['hashedBodyOTP'] = sha1($external_id . ":" . $hashed_time . "::" . $transaction_key);
    // error_log("TIMESTAMP FUNCTION");
    // error_log($amount);
    // error_log(json_encode($result));
    echo json_encode($result);
    die;
}



if (isset($_GET['ReferralCode'])) {
    $referral_code = sanitize_text_field($_GET['ReferralCode']);
    setcookie('ReferralCode', $referral_code, time() + (86400 * 30), "/");
}




class Gameball
{

    //methods
    function __construct()
    {


        // add_action('admin_menu',  array($this, 'gameball_register_default_options'));
        add_action('admin_menu',  array($this, 'gameball_register_options_page'));
        //  add_action('admin_head', array($this, 'gameball_js'));
        add_action('wp_head', array($this, 'gameball_js'));
    }

    function gameball_register_options_page()
    {


        add_menu_page('GameballData', 'Gameball', 'manage_options', 'GameballPlugin', array($this, 'GameballPlugin_options_page'), 'https://assets.gameball.co/wp_logo.png', 4);
        if (isset($_POST['submit'])) {


            $list = array(sanitize_key($_POST["APIID"]), sanitize_key($_POST["TID"]));

            /*******INSIDE SAVE TO UPDATE TASK COMPLETED*********/



            if (isset($_POST['view_product_page'])) {
                array_push($list, sanitize_key($_POST['view_product_page']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['add_to_cart'])) {
                array_push($list, sanitize_key($_POST['add_to_cart']) == '1');
            } else {
                array_push($list, sanitize_key($_POST['add_to_cart']) == '1');
            }

            if (isset($_POST['review'])) {
                array_push($list, sanitize_key($_POST['review']) == '1');
            } else {
                array_push($list, false);
            }

            if (isset($_POST['place_order'])) {
                array_push($list, sanitize_key($_POST['place_order']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['remove_from_cart'])) {
                array_push($list, sanitize_key($_POST['remove_from_cart']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['referral'])) {
                array_push($list, sanitize_key($_POST['referral']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['wallet_points_reward'])) {
                array_push($list, sanitize_key($_POST['wallet_points_reward']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['wallet_points_redemption'])) {
                array_push($list, sanitize_key($_POST['wallet_points_redemption']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['view_cart'])) {
                array_push($list, sanitize_key($_POST['view_cart']) == '1');
            } else {
                array_push($list, false);
            }
            if (isset($_POST['GOLIVE'])) {
                array_push($list, sanitize_key($_POST['GOLIVE']) == '1');
            } else {
                array_push($list, false);
            }


            if (isset($_POST['wallet_points_redemption_otp'])) {



                $metadata_file = (__DIR__ . '/GameballData.txt');


                $handle = fopen($metadata_file, 'w') or die('Cannot open file:  ' . $metadata_file);
                $content = serialize($list);
                file_put_contents($metadata_file, $content);
                if (isset($_POST["APIID"])) {

                    gameball_post_request($GLOBALS['gb_api_prefix'] . "v1.0/Bots/Task?code=install_wp_plugin", []);
                }
            }
        }
    }

    function GameballPlugin_options_page()
    {
        try {
            $src = esc_url("load-styles.php?c=1&amp;dir=ltr&amp;load%5B%5D=dashicons,wp-jquery-ui-dialog,admin-bar,common,forms,admin-menu,dashboard,list-tables,edit,revisions,media,themes,about,nav-menu&amp;load%5B%5D=s,wp-pointer,widgets,site-icon,l10n,buttons,wp-auth-check,wp-color-picker&amp;ver=5.2.2");
            wp_enqueue_style("options_page", $src);
            $metadata_file = (__DIR__ . '/GameballData.txt');
            $handle = @fopen($metadata_file, "r");
            if (!$handle)
                throw new Exception('Failed to open file');
            $content = unserialize(file_get_contents($metadata_file));
            $GLOBALS['aid'] = $content[0];
            $GLOBALS['tid'] = $content[1];
            $GLOBALS['Checkboxs'] = array();
            array_push($GLOBALS['Checkboxs'], $content[2] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[3] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[4] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[5] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[6] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[7] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[8] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[9] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[10] == '1' ? 'checked' : '');
            array_push($GLOBALS['Checkboxs'], $content[11] == '1' ? 'checked' : '');
        } catch (Exception $e) {
        }

?>

        <!DOCTYPE html>
        <html>

        <head>


            <script type="text/javascript">
                function init() {

                    if (document.getElementById('referral').checked) {
                        document.getElementById('referal_status').innerHTML = "Active";
                    } else {
                        document.getElementById('referal_status').innerHTML = "Inactive";
                    }
                    if (document.getElementById('api_text').value.length == 0 && document.getElementById('tid_text').value.length == 0) {
                        document.getElementById("add_to_cart").checked = true;
                        document.getElementById("place_order").checked = true;
                        document.getElementById("view_product_page").checked = true;
                        document.getElementById('referral').checked = true;
                        document.getElementById('referal_status').innerHTML = "Active";
                    }
                }

                function Changing() {
                    if (document.getElementById('wallet_points_reward').checked) {
                        document.getElementById("wallet_points_redemption").disabled = false;
                    } else {
                        document.getElementById("wallet_points_redemption").disabled = true;
                        document.getElementById("wallet_points_redemption").checked = false;
                    }

                    if (document.getElementById('wallet_points_redemption').checked) {
                        document.getElementById("wallet_points_redemption_otp").disabled = false;
                    } else {
                        document.getElementById("wallet_points_redemption_otp").disabled = true;
                        document.getElementById("wallet_points_redemption_otp").checked = false;
                    }
                }

                function ChangeStatus(labelText) {
                    if (document.getElementById('referral').checked) {
                        document.getElementById(labelText).innerHTML = "Active";
                    } else {
                        document.getElementById(labelText).innerHTML = "Inactive";
                    }
                }
            </script>

            <style>
                .switch {
                    position: relative;
                    display: inline-block;
                    width: 30px;
                    height: 17px;
                }

                /* Hide default HTML checkbox */
                .switch input {
                    opacity: 0;
                    width: 0;
                    height: 0;
                }

                /* The slider */
                .slider {
                    position: absolute;
                    cursor: pointer;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: #ccc;
                    -webkit-transition: .4s;
                    transition: .4s;
                }

                .slider:before {
                    position: absolute;
                    content: "";
                    height: 13px;
                    width: 13px;
                    left: 2px;
                    bottom: 2px;
                    background-color: white;
                    -webkit-transition: .4s;
                    transition: .4s;
                }

                input:checked+.slider {
                    background-color: #2196F3;
                }

                input:focus+.slider {
                    box-shadow: 0 0 1px #2196F3;
                }

                input:checked+.slider:before {
                    -webkit-transform: translateX(13px);
                    -ms-transform: translateX(13px);
                    transform: translateX(13px);
                }

                /* Rounded sliders */
                .slider.round {
                    border-radius: 17px;
                }

                .slider.round:before {
                    border-radius: 50%;
                }

                .golive {
                    border-bottom: 1px solid black;
                }
            </style>


            <title></title>
        </head>

        <body onload="init()">
            <div class="wrap">
                <h1 id="gameball">Gameball</h1>
                <form method="post" novalidate="novalidate">
                    <table class="form-table">
                        <tbody>
                            <tr style="display:none;" class="golive">
                                <th scope="row">
                                    <label for="blogname">GO LIVE</label>
                                </th>
                                <td>
                                    <label class="switch">
                                        <input type="checkbox" name="GOLIVE" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][9]); ?>>
                                        <span class="slider round"></span>
                                    </label>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">
                                    <label for="blogname">API Key</label>
                                </th>
                                <td>
                                    <input type="text" placeholder="Enter API Key" name="APIID" id="api_text" value="<?php echo esc_attr(htmlentities($GLOBALS['aid'])); ?>" required />
                                    <p id="tagline-description" class="description">This is your Gameball account key. This is mandatory to connect with your Gameball account. Get it from your Gameball admin dashboard under Settings/Account Integration.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="blogdescription">Transaction key</label>
                                </th>
                                <td>
                                    <input id="tid_text" type="text" placeholder="Enter transaction key" name="TID" value="<?php echo esc_attr(htmlentities($GLOBALS['tid'])); ?>" required />
                                    <p id="tagline-description" class="description">This is your Gameball account transactions key. This is mandatory to enable your customers earn Wallet Points upon purchases and redeem their points. Get it from your Gameball admin dashboard under Settings/Account Integration.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Events</th>
                                <td>
                                    <fieldset>
                                        <legend class="screen-reader-text"><span>Events</span></legend>
                                        <input name="view_product_page" type="checkbox" id="view_product_page" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][0]); ?>> View Product Page</label>
                                        <br>
                                        <input name="add_to_cart" type="checkbox" id="add_to_cart" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][1]); ?>> Add to Cart</label>
                                        <br>
                                        <input name="view_cart" type="checkbox" id="view_cart" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][8]); ?>> View Cart</label>
                                        <br>
                                        <input name="review" type="checkbox" id="review" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][2]); ?>> Review
                                        </label>
                                        <br>
                                        <input name="place_order" type="checkbox" id="place_order" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][3]); ?>> Place Order</label>
                                        <br>
                                        <input name="remove_from_cart" type="checkbox" id="remove_from_cart" value="1" <?php echo esc_attr($GLOBALS['Checkboxs'][4]); ?>> Remove From Cart</label>
                                        <p id="tagline-description" class="description">These are the available events that can be sent to Gameball. You must configure these events on Gameball with the corresponding metadata of every event. You can configure these events through Gameball Woocommerce Events template inside your Gameball admin dashboard under settings/events.</p>
                                    </fieldset>
                                </td>
                            <tr hidden>
                                <th scope="row">Referral status</th>
                                <td>
                                    <fieldset>
                                        <legend class="screen-reader-text"><span>Referral status</span></legend>
                                        <input name="referral" type="checkbox" id="referral" value="1" onclick="ChangeStatus('referal_status')" <?php echo esc_attr($GLOBALS['Checkboxs'][5]); ?>><label for="referal_status" name="referal_status" id="referal_status"></label>
                                    </fieldset>
                                </td>
                            <tr hidden>
                                <th scope="row">Wallet points</th>
                                <td>
                                    <fieldset>
                                        <legend class="screen-reader-text"><span>Wallet Points</span></legend>
                                        <input name="wallet_points_reward" type="checkbox" id="wallet_points_reward" value="1" onclick="Changing()" <?php echo esc_attr($GLOBALS['Checkboxs'][6]); ?>>Enable wallet points reward upon paid transactions</label>
                                        <br>
                                        <input name="wallet_points_redemption" type="checkbox" id="wallet_points_redemption" value="1" onclick="Changing()" <?php echo esc_attr($GLOBALS['Checkboxs'][7]); ?>>Enable wallet points redemption while placing an order</label>
                                        <br>
                                        <input name="wallet_points_redemption_otp" type="hidden" id="wallet_points_redemption_otp" value="1" onclick="Changing()"></label>
                                    </fieldset>
                                </td>
                            </tr>
                            </tr>
                        </tbody>
                    </table>
                    <button class="button button-primary" type="submit" name='submit'>Submit</button>
                </form>

        <!--Weglot 3.9.2--><aside data-wg-notranslate="" class="country-selector weglot-inline weglot-default" tabindex="0" aria-expanded="false" role="listbox" aria-activedescendant="weglot-language-fr" aria-label="Language selected: French"><input id="wg1695490833650f23116f2a9541" class="weglot_choice" type="checkbox" name="menu"/><label data-l="fr" tabindex="-1" id="weglot-language-fr" role="none" for="wg1695490833650f23116f2a9541" class="wgcurrent wg-li weglot-lang weglot-language weglot-flags flag-3 fr" data-code-language="fr" data-name-language=""><span class="wglanguage-name"></span></label><ul role="none"><li data-l="en" class="wg-li weglot-lang weglot-language weglot-flags flag-3 en" data-code-language="en" role="none"><a title="Language switcher : English" id="weglot-language-en" role="option" data-wg-notranslate="" href="https://www.digitalmaster.be/en/php-snippet-golden/"></a></li></ul></aside> </body>

        </html>

<?php

    }

    function gameball_js()
    {
        gameball_read_API_ID();
        $ap = '';
        try {
            $main_file = (__DIR__ . '/GameballData.txt');
            $handle = @fopen($main_file, "r");
            if (!$handle)
                throw new Exception('Failed to open uploaded file');
            $content = unserialize(file_get_contents($main_file));
            $ap = $content[0];
        } catch (Exception $e) {
        }
        $current_user = wp_get_current_user();
        $display_name = '';
        $first_name = '';
        $last_name = '';
        $email = '';
        $user_login = '';
        $id = '';
        $gameball_key = '';
        $locale = get_locale();
        $locale = (strpos($locale, 'en') !== false) ? 'en' : $locale;
        $registered_date = $current_user->user_registered;
        $join_date = substr($registered_date, 0, 10);
        if (0 <> $current_user->ID) {
            $email = $current_user->user_email;
            $display_name = $current_user->display_name;
            $first_name = $current_user->user_firstname;
            $last_name = $current_user->user_lastname;
            $id = $current_user->ID;
            $user_login = $current_user->user_login;
            $gameball_key = $gameball_key . wp_get_current_user()->gameball_key;
        }

        wp_register_script("Gameball", false);

        $script = "
           
            json = {
                playerUniqueId: '$user_login',
                wp: true,
                playerAttributes: {
                    displayName: '$display_name',
                    FirstName: '$first_name',
                    LastName: '$last_name',
                    email: '$email',
                   
                    joinDate: '$join_date',
                    custom: {
                        gameball_key: '$gameball_key',
                        user_id: '$id' 
                    }
                }
            }
            if (document.getElementsByTagName('html')[0].getAttribute('dir') === 'rtl')
                json.lang = 'ar'
            else
			{
				var gb_lang=document.getElementsByTagName('html')[0].getAttribute('lang');
				if (gb_lang&&gb_lang!='')
					json.lang=gb_lang;
				else
					json.lang='en'
			}
               // json.lang='en'
            json.APIKey= '$ap'
            window.GbLoadInit = function() {
            GbSdk.init(json);
            };
           
            ";

        //   if (strcmp($GLOBALS['Checkboxs'][9], 'checked') == 0){
        
        wp_register_script('gb_script', $GLOBALS['gb_widget_url'].'gameball-init.min.js',array('jquery'));
        wp_enqueue_script('gb_script');

    //    wp_register_script('gb_widget_script', $GLOBALS['gb_widget_url'].'gameball.widget.min.js',array('jquery'));
    //    wp_enqueue_script('gb_widget_script');

        $success = wp_add_inline_script("Gameball", $script);

        wp_print_scripts("Gameball");
        //  }
    }
}
if (class_exists('Gameball')) {
    $gameball = new Gameball();
}

//register_activation_hook(__FILE__, array($gameball, 'activate'));
//deactivation
//register_deactivation_hook(__FILE__, array($gameball, 'deactivate'));
//uninstall


///////////////////////// Webhooks code //////////////////////////////////////


function gameball_get_hashed_time()
{
    return gmdate("ymdHis");
}

function gameball_read_API_ID()
{
    try {
        $metadata_file = (__DIR__ . '/GameballData.txt');
        $handle = @fopen($metadata_file, "r");
        if (!$handle)
            throw new Exception('Failed to open  file');
        $content = unserialize(file_get_contents($metadata_file));
        $GLOBALS['aid'] = $content[0];
        $GLOBALS['tid'] = $content[1];
        $GLOBALS['Checkboxs'] = array();
        array_push($GLOBALS['Checkboxs'], $content[2] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[3] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[4] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[5] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[6] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[7] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[8] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[9] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[10] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[11] == '1' ? 'checked' : '');

        loadEnv();
    } catch (Exception $e) {
    }
}
function gameball_read_API_Key()
{
    try {
        $metadata_file = (__DIR__ . '/GameballData.txt');
        $handle = @fopen($metadata_file, "r");
        if (!$handle)
            throw new Exception('Failed to open  file');
        $content = unserialize(file_get_contents($metadata_file));
        $GLOBALS['aid'] = $content[0];
        $GLOBALS['tid'] = $content[1];
        $GLOBALS['Checkboxs'] = array();
        array_push($GLOBALS['Checkboxs'], $content[2] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[3] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[4] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[5] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[6] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[7] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[8] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[9] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[10] == '1' ? 'checked' : '');
        array_push($GLOBALS['Checkboxs'], $content[11] == '1' ? 'checked' : '');

        //load env setting 
        loadEnv();
    } catch (Exception $e) {
    }
}

function loadEnv()
{
    $api_prefix = "";
    //$GLOBALS $gb_widget_url;
    //$GLOBALS $gb_api_prefix;

    //set env is prod or uat
    $is_prod = true;
    $widget_url = '';
  //  $widget_url_prod = 'https://assets.gameball.co/widget/s/js/';
  $widget_url_prod = 'https://assets.gameball.co/widget/js/';
    $widget_url_uat = 'https://assets.gameball.co/uat/widget/js/';
    $api_prod = 'https://api.gameball.co/api/';
    $api_uat = 'https://gb-api.azurewebsites.net/api/';



    if ($is_prod) {
        $GLOBALS['gb_widget_url'] = $widget_url_prod;
        $GLOBALS['gb_api_prefix']  = $api_prod;
    } else {
        $GLOBALS['gb_widget_url'] = $widget_url_uat;
        $GLOBALS['gb_api_prefix']  = $api_uat;
    }
}
/**USED to get the GB Enabled status */
function gameball_gb_settings()
{
    try {
        $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Bots/BotSettings');

        //setup request to send json via POST

        $result = gameball_get_request($url, false);

        if ($result && $result->response) {
            $value = $result->response;


            return $value;
        }
        return null;
    } catch (Exception $e) {
        return null;
    }
}
function gameball_hash_string($string_to_hash)
{
    return sha1($string_to_hash);
}
function gameball_add_to_cart_hook($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data)
{
    gameball_read_API_ID();
    $current_user = wp_get_current_user();
    $product = wc_get_product($product_id);
    $categories = $product->get_category_ids();
    $tags = $product->get_tag_ids();
    $tags_names = array();
    $categories_names = array();
    foreach ($categories as $value) {
        $term = get_term_by('id', $value, 'product_cat', 'ARRAY_A');
        array_push($categories_names, $term['name']);
    }
    foreach ($tags as $value) {
        $term = get_term_by('id', $value, 'product_tag', 'ARRAY_A');
        array_push($tags_names, $term['name']);
    }
    $vendor_id = get_post_field('post_author', $product_id);
    $vendor_shop_name = get_userdata($vendor_id)->display_name;
    $stock = get_post_meta($product_id, '_stock', true);
    if ($product->get_price() == $product->get_regular_price()) {
        $discounted = false;
    } else {
        $discounted = true;
    }

    //API URL
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Action');

    //setup request to send json via POST
    $data = array(

        "events" => array(
            "add_to_cart" => array(
                'category' => $categories_names,
                'discounted' => $discounted,
                'tag' => $tags_names,
                'weight' => ($product->get_weight() == '') ? 0 : $product->get_weight(),
                'vendor' => $vendor_shop_name,
                'price' => $product->get_price()
            )
        ),
        "playerUniqueId" => ($current_user->user_email == false) ? '' : wp_get_current_user()->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email
    );

    $result = gameball_post_request($url, $data);
}

function gameball_put_request($url, $body)
{

    gameball_read_API_Key();




    $payload = json_encode($body);

    $headers = array('Content-Type' => 'application/json', 'APIKey' => $GLOBALS['aid']);
    $args = array(
        'body' => $payload,
        'method'    => 'PUT',
        'sslverify' => false,
        'timeout' => '5',
        'redirection' => '5',
        'httpversion' => '1.0',
        'blocking' => false,
        'headers' => $headers
    );

    $result = wp_remote_request($url, $args);

    
    if (!is_wp_error($result))
        return $result['body'];
    else
        return null;
}

function gameball_post_request($url, $body)
{

    gameball_read_API_Key();

    $payload = json_encode($body);

    $headers = array('Content-Type' => 'application/json', 'APIKey' => $GLOBALS['aid']);
    $args = array(
        'body' => $payload,
        'sslverify' => false,
        'timeout' => '5',
        'redirection' => '5',
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => $headers
    );
    $result = wp_remote_post($url, $args);
    
    if (!is_wp_error($result)){
        return $result['body'];
     //   error_log( 'done post');
    //    error_log(print_r($payload, TRUE)  );
     //   error_log(print_r($result, TRUE)  );
    }
    else
    //    error_log( 'error post');
    //    error_log(print_r($url, TRUE)  );
    //    error_log(print_r($headers, TRUE)  );
    //    error_log(print_r($payload, TRUE)  );
   //     error_log(print_r($result, TRUE)  );
        return null;
   
}
function gameball_get_request($url, $blocking)
{

    gameball_read_API_Key();



    $headers = array('Content-Type' => 'application/json', 'APIKey' => $GLOBALS['aid']);
    $args = array(

        'sslverify' => false,
        'timeout' => '5',
        'redirection' => '5',
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => $headers
    );
    $result = wp_remote_get($url, $args);

    
    if (is_wp_error($result))
        {
            return null;
        }
    else
        $body = wp_remote_retrieve_body($result);

        $data = json_decode($body);

        return $data;

    
}



function gameball_view_meta()
{
	error_log('gameball_view_meta start');
    gameball_read_API_ID();
    global $wp_query;
    $product_id = $wp_query->post->ID;
    $current_user = wp_get_current_user();
    $product = wc_get_product($product_id);
    $categories = $product->get_category_ids();
    $tags = $product->get_tag_ids();
    $tags_names = array();

    $all_ids = array();
    array_push($all_ids, $product_id);

    $categories_names = array();
    foreach ($categories as $value) {
        $term = get_term_by('id', $value, 'product_cat', 'ARRAY_A');
        array_push($categories_names, $term['name']);
    }
    foreach ($tags as $value) {
        $term = get_term_by('id', $value, 'product_tag', 'ARRAY_A');
        array_push($tags_names, $term['name']);
    }
    $vendor_id = get_post_field('post_author', $product_id);
    $vendor_shop_name = get_userdata($vendor_id)->display_name;
    $stock = get_post_meta($product_id, '_stock', true);
    if ($product->get_price() == $product->get_regular_price()) {
        $discounted = false;
    } else {
        $discounted = true;
    }
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Action');


    //setup request to send json via POST

    $data = array(
        "events" => array(
            "view_product" => array(
                'category' => $categories_names,
                'price' => $product->get_price(),
                'discounted' => $discounted,
                'stock' => $stock,
                'tag' => $tags_names,
                'weight' => ($product->get_weight() == '') ? 0 : $product->get_weight(),
                'vendor' => $vendor_shop_name,
                'product_id' => $all_ids
            )
        ),
        "playerUniqueId" => ($current_user->user_email == false) ? '' : wp_get_current_user()->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
        "isPositive" => true
    );

    $result = gameball_post_request($url, $data);
}


function redeem_gameball_points($order)
{
   // error_log( 'inside coupon check');
    //error_log("INSIDE redeem_gameball_points");
    //  gameball_read_API_ID();

    //  $order = wc_get_order($order_id);
    //  error_log( 'coupjn check');


    if ($order == false) {
        //  error_log( 'order false');
        return;
    }

    $used_coupons = $order->get_coupon_codes();
    

    if ($used_coupons == false ||  count($used_coupons) == 0) {
        //  error_log( 'coupons 0');
        return;
    }

    $email='';

    $customer_user=$order->get_user();
    if(!$customer_user)
    {
        $email = $order-> get_billing_email();
    }
    else
    {
        $email = $customer_user->user_email;
    }

    //setup request to send json via POST
    $data = array();


    foreach ($used_coupons as $c) {
        $item= array(

       
            "discountCode" => $c,
            "email" => $email
        );
        array_push($data,  $item);
    }

    

    

    /*
    */

  //  error_log( 'coupon found');
 //   error_log(print_r($used_coupons, TRUE)  );
 //   error_log(print_r($data, TRUE)  );
  //  error_log( $email);

    
    
    //  error_log( 'coupjn ok');

    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v2.0/Integrations/DiscountCode/Guest');


    $result = gameball_put_request($url, $data);
 //    $json_result = json_decode($result);
//    error_log( $json_result);

}
function reward_gameball_points($order_id)
{
    //Reward Points  
    $order = wc_get_order($order_id);

    if ($order == false)
        return;

    $amount = $order->get_total();

    $current_user = $order->get_user();

    if ($current_user == false || $current_user->user_login == false)
        return;


    if ($amount > 0) {
        $url = esc_url($GLOBALS['gb_api_prefix'] . "v1.0/Integrations/Transaction/Reward");
        $transaction_time = gmdate("Y-m-d") . "T" . gmdate("H:i:s");
        $timestamp = gmdate("ymdHis");
        $hashed_body = sha1($current_user->user_login . ":" . $timestamp . ":" . $amount . ":" . $GLOBALS['tid']);

        //  error_log("REWARD AMOUNT: ".$amount);

        //setup request to send json via POST
        $data = array(
            'playerUniqueId' =>  $current_user->user_login,
			"email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
            'transactionOnClientSystemId' => $GLOBALS['aid'] . "" . $order_id,
            'amount' => $amount,
            'transactionTime' => $transaction_time,
            'bodyHashed' => $hashed_body
        );

        //execute the POST request
        $result = gameball_post_request($url, $data);
       // $json_result = json_decode($result);
        //  error_log("REWARD RESULT: ");
        //  error_log($result);
    }
}
function gameball_comment_meta($comment_id)
{
    gameball_read_API_ID();
    $current_user = wp_get_current_user();
    $comment = get_comment($comment_id);
    $product_id = $comment->comment_post_ID;
    echo $product_id;
    $product = wc_get_product($product_id);
    $tags = $product->get_tag_ids();
    $categories = $product->get_category_ids();
    $tags_names = array();
    $categories_names = array();
    foreach ($categories as $value) {
        $term = get_term_by('id', $value, 'product_cat', 'ARRAY_A');
        array_push($categories_names, $term['name']);
    }
    foreach ($tags as $value) {
        $term = get_term_by('id', $value, 'product_tag', 'ARRAY_A');
        array_push($tags_names, $term['name']);
    }
    $vendor_id = get_post_field('post_author', $product_id);
    $vendor_shop_name = get_userdata($vendor_id)->display_name;
    $stock = get_post_meta($product_id, '_stock', true);
    if ($product->get_price() == $product->get_regular_price()) {
        $discounted = false;
    } else {
        $discounted = true;
    }
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Action');


    //setup request to send json via POST
    $data = array(

        "events" => array(
            "review" => array(
                'category' => $categories_names,
                'discounted' => $discounted,
                'tag' => $tags_names,
                'weight' => ($product->get_weight() == '') ? 0 : $product->get_weight(),
                'vendor' => $vendor_shop_name
            )
        ),
        "playerUniqueId" => ($current_user->user_email == false) ? '' : wp_get_current_user()->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
        "isPositive" => true
    );

    $result = gameball_post_request($url, $data);
}

function gameball_before_removing_cart($cart_item_key, $cart)
{
    gameball_read_API_ID();
    $current_user = wp_get_current_user();
    $product_id = $cart->cart_contents[$cart_item_key]['product_id'];
    $product = wc_get_product($product_id);
    $categories = $product->get_category_ids();
    $tags = $product->get_tag_ids();
    $tags_names = array();
    $categories_names = array();
    foreach ($categories as $value) {
        $term = get_term_by('id', $value, 'product_cat', 'ARRAY_A');
        array_push($categories_names, $term['name']);
    }
    foreach ($tags as $value) {
        $term = get_term_by('id', $value, 'product_tag', 'ARRAY_A');
        array_push($tags_names, $term['name']);
    }
    $vendor_id = get_post_field('post_author', $product_id);
    $vendor_shop_name = get_userdata($vendor_id)->display_name;
    $stock = get_post_meta($product_id, '_stock', true);
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Action');


    //setup request to send json via POST
    $data = array(

        "events" => array(
            "remove_from_cart" => array(
                'category' => $categories_names,
                'tag' => $tags_names,
                'weight' => ($product->get_weight() == '') ? 0 : $product->get_weight(),
                'price' => $product->get_price()
            )
        ),
        "playerUniqueId" => ($current_user->user_email == false) ? '' : wp_get_current_user()->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
        "isPositive" => true
    );

    $result = gameball_post_request($url, $data);
}

function gameball_create_order_meta($order_id)
{
    $settings = gameball_gb_settings();
   	error_log('gameball_create_order_meta start');

    if ($settings->redemptionEnabled) {
        // error_log('start reward');
        reward_gameball_points($order_id);
        //	 error_log('end reward');
    }
    //  error_log('start place');
    gameball_read_API_ID();
    $current_user = wp_get_current_user();

    $order = new WC_Order($order_id);

    $current_user = $order->get_user();
    //	error_log(' checks');
    //	error_log($current_user->user_login);
    if ($current_user == false || $current_user->user_login == false)
        return;

    //	error_log($current_user->user_login);
    $items = $order->get_items();
    $all_categories = array();
    $all_tags = array();
    $all_ids = array();
    $all_vendors = array();
    $all_weight = 0;
    foreach ($items as $item) {
        $product_id = $item->get_product_id();

        array_push($all_ids, $product_id);

        $product = wc_get_product($product_id);
        $categories = $product->get_category_ids();
        $tags = $product->get_tag_ids();
        foreach ($categories as $value) {
            $term = get_term_by('id', $value, 'product_cat', 'ARRAY_A');
            if (!in_array($term['name'], $all_categories)) {
                array_push($all_categories, $term['name']);
            }
        }
        foreach ($tags as $value) {
            $term = get_term_by('id', $value, 'product_tag', 'ARRAY_A');
            if (!in_array($term['name'], $all_tags)) {
                array_push($all_tags, $term['name']);
            }
        }
        $vendor_id = get_post_field('post_author', $product_id);
        $vendor_shop_name = get_userdata($vendor_id)->display_name;
        if (!in_array($vendor_shop_name, $all_vendors)) {
            array_push($all_vendors, $vendor_shop_name);
        }
        $all_weight += ($product->get_weight() == '') ? 0 : $product->get_weight();
    }

    //	error_log('passed checks');
    //API URL
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Action');


    //setup request to send json via POST
    $data = array(
        "events" => array(
            "order_completed" => array(
                'category' => $all_categories,
                'price' => $order->get_total(),
                'discounted' => ($order->get_total_discount() == 0) ? false : true,
                'tag' => $all_tags,
                'weight' => $all_weight,
                'vendor' => $all_vendors,
                'product_id' => $all_ids
            )
        ),
		"playerUniqueId" => $current_user->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
        "isPositive" => true
    );
    //	error_log(json_encode($data));
   $order = wc_get_order($order_id);
$amount = $order->get_total();
$current_user = $order->get_user();

if ($current_user == false || $current_user->user_login == false)
    return;

$transaction_time = gmdate("Y-m-d") . "T" . gmdate("H:i:s");
$timestamp = gmdate("ymdHis");
$hashed_body = sha1($current_user->user_login . ":" . $timestamp . ":" . $amount . ":" . $GLOBALS['tid']);
$url = esc_url($GLOBALS['gb_api_prefix'] . "v1.0/Integrations/Transaction/Reward");

// Setup request to send JSON via POST
$data = array(
    'playerUniqueId' => $current_user->user_login,
    "email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
    'transactionOnClientSystemId' => $GLOBALS['aid'] . "" . $order_id,
    'amount' => $amount,
    'transactionTime' => $transaction_time,
    'bodyHashed' => $hashed_body
);

// Execute the POST request
$result = gameball_post_request($url, $data);

}
function gameball_Referral($user_id)
{

    gameball_read_API_ID();
    $playerCode = '';
    if (isset($_GET['ReferralCode']))
        $playerCode = sanitize_text_field($_GET['ReferralCode']);

    else if (!isset($_GET['ReferralCode'])) {

        if (isset($_COOKIE['ReferralCode'])) {

            $playerCode = sanitize_text_field($_COOKIE['ReferralCode']);
            unset($_COOKIE['ReferralCode']);

            setcookie('ReferralCode', '', time() - 3600, '/');
        }
    }
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Referral');


    //setup request to send json via POST
    $data = array(
        "playerCode" => $playerCode,
        "playerUniqueId" => get_user_by("ID", $user_id)->user_login

    );
    //$result = gameball_post_request($url, $data);
    unset($_COOKIE['ReferralCode']);
    setcookie('ReferralCode', '', time() - 3600, '/');
}



function change_status_to_refund($order_id)
{
    gameball_read_API_ID();

    error_log($order_id);


    $order = wc_get_order($order_id);

    if ($order == false)
        return;


    $order_refunds = $order->get_refunds();
    $amount = 0;
    error_log(json_encode($order_refunds));
    foreach ($order_refunds as $refund) {
        // Loop through the order refund line items
        $amount = $refund->get_amount();
     //   error_log(json_encode($amount));
     //   error_log('---------------------------------');
        break;
    }


    $current_user = $order->get_user();

    if ($current_user == false || $current_user->user_login == false)
        return;


    $transaction_time = gmdate("Y-m-d") . "T" . gmdate("H:i:s");
    $timestamp = gmdate("ymdHis");
    $hashed_body = sha1($current_user->user_login . ":" . $timestamp . ":" . $amount . ":" . $GLOBALS['tid']);
    $url = esc_url($GLOBALS['gb_api_prefix'] . "v1.0/Integrations/Transaction/Cancel");
    //setup request to send json via POST
    $data = array(
        'playerUniqueId' => $current_user->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email,
        'transactionOnClientSystemId' =>  $GLOBALS['aid'] . "" . $timestamp,
        "reversedTransactionOnClientSystemId" => $GLOBALS['aid'] . "" . $order_id,
        'transactionTime' => $transaction_time,
        'amount' => $amount,
        'bodyHashed' => $hashed_body
    );

    //execute the POST request
    $result = gameball_post_request($url, $data);
  //  $json_result = json_decode($result);
}


add_action('user_register', 'gameball_Referral', 10, 1);
function gameball_register_default_options()
{

    $list = array("", "");
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);
    array_push($list, false);

    $metadata_file = (__DIR__ . '/GameballData.txt');
    $handle = @fopen($metadata_file, "r");
    if (!$handle) {
        $metadata_file = (__DIR__ . '/GameballData.txt');
        $handle = fopen($metadata_file, 'w') or die('Cannot open file:  ' . $metadata_file);
        $content = serialize($list);
        file_put_contents($metadata_file, $content);
    }
}
function gameball_your_login_function()
{

    gameball_register_default_options();
    // add_action('admin_menu',  array($this, 'gameball_register_default_options'));

    gameball_read_API_ID();


    $settings = gameball_gb_settings();
    if ($settings && $settings->gbEnabled) {
        add_action('woocommerce_checkout_create_order', 'redeem_gameball_points', 10, 1);

        if (is_user_logged_in() == true) {
            //if (strcmp($GLOBALS['Checkboxs'][9], 'checked') == 0){
            if (strcmp($GLOBALS['Checkboxs'][0], 'checked') == 0)
                add_action('woocommerce_before_single_product', 'gameball_view_meta', 10, 1);

            if (strcmp($GLOBALS['Checkboxs'][1], 'checked') == 0)
                add_action('woocommerce_add_to_cart', 'gameball_add_to_cart_hook', 10, 6);

            if (strcmp($GLOBALS['Checkboxs'][2], 'checked') == 0)
                add_action('comment_post', 'gameball_comment_meta', 10, 2);
            //new order
            if (strcmp($GLOBALS['Checkboxs'][3], 'checked') == 0)
                add_action('woocommerce_order_status_completed', 'gameball_create_order_meta', 10, 2);

            if (strcmp($GLOBALS['Checkboxs'][4], 'checked') == 0)
                add_action('woocommerce_remove_cart_item', 'gameball_before_removing_cart', 10, 2);


            if ($settings->rewardEnabled) {
                // add_action('woocommerce_order_status_completed', 'reward_gameball_points', 10, 2);

                //   error_log("CHECKOUT WEBHOOK");
            }

            if (strcmp($GLOBALS['Checkboxs'][8], 'checked') == 0) {
                add_action('woocommerce_before_cart', 'gameball_view_cart_meta');
            }

            //remove commented line below to check refund
            add_action('woocommerce_order_refunded', 'change_status_to_refund', 10, 1);
        }

        $registered_date = wp_get_current_user()->user_registered;
        $timestamp = substr(str_replace(" ", "", str_replace(":", "", str_replace("-", "", $registered_date))), 0, 12);
        if (!wp_get_current_user()->gameball_key)
            update_user_meta(wp_get_current_user()->user_login, "gameball_key", wp_get_current_user()->user_login . "_" . $timestamp);
    }
}
add_action('init', 'gameball_your_login_function');



function gameball_view_cart_meta()
{
    gameball_read_API_ID();
    $current_user = wp_get_current_user();
    $cart = WC()->cart->get_cart();
    $cart_count = count($cart);
    $cart_total = WC()->cart->cart_contents_total;
    $url = esc_url($GLOBALS['gb_api_prefix'] . 'v1.0/Integrations/Action');


    //setup request to send json via POST
    $data = array(

        "events" => array(
            "view_cart" => array(
                'products_count' => $cart_count,
                'total' => $cart_total
            )
        ),//omar
        "playerUniqueId" => ($current_user->user_email == false) ? '' : wp_get_current_user()->user_login,
		"email" => ($current_user->user_email == false) ? '' : $current_user->user_email
    );

    $result = gameball_post_request($url, $data);
}
				
			

Demandez votre devis sur-mesure

Complétez le formulaire ci-dessous et nous vous contacterons pour en savoir plus sur votre projet. Nous vous remettrons une offre sur mesure qui correspond exactement à ce que vous souhaitez développer.