<?php
/**
 * Plugin Name: FTM Geo Target Plugin
 * Plugin URI: http://www.ftmedia.com
 * Description: This plugin handles all Geo Targeting tables on the website
 * Author: Full Throttle Media
 * Version: 1.0.7
 */

//Uncomment the lines below to get errors to show up no matter what
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

//Security measure to avoid exposing important data
defined('ABSPATH') or die('The mighty FTM Geo-Target plugin shall not let you pass!');

/**
 * Plugin Version
 **/
define("FTM_GT_VERSION","1.0.7");

/**
 * Database Version
 **/
define("FTM_GT_DB_VERSION","1.1");

GLOBAL $wpdb;

$GLOBALS['cc'] = '';
$GLOBALS['rc'] = '';

$wordpress_installation_type = get_option( 'ftmgt_bedrock_installation', '0' );

if($wordpress_installation_type === '1'){//Bedrock install
    define('FTM_WP_INSTALL_PREFIX', '/wp');
}
else //Regular install
{
    define('FTM_WP_INSTALL_PREFIX', '');
}

$ftm_geo_target_plugin_url     = WP_PLUGIN_URL . '/ftm-geo-target';
$ftm_geo_target_plugin_path    = WP_PLUGIN_DIR . '/ftm-geo-target';

require_once $ftm_geo_target_plugin_path . '/core/database-migrations.php';
require_once $ftm_geo_target_plugin_path . '/core/asset-files.php';
require_once $ftm_geo_target_plugin_path . '/core/admin-menu.php';
require_once $ftm_geo_target_plugin_path . '/core/shortcodes.php';

define("FTM_GEO_TARGET_SITE_OPTIONS_TBL", $wpdb->prefix . "ftm_geo_target_site_options");

register_activation_hook( __FILE__, 'ftm_geo_target_install' );

if (file_exists($ftm_geo_target_plugin_path . '/vendor/autoload.php')) {
    require_once $ftm_geo_target_plugin_path . '/vendor/autoload.php';
} else {
    require_once base_dir() . '/vendor/autoload.php';
}
use GeoIp2\Database\Reader;

if (is_readable('/var/www/GeoIP/GeoIP2-City.mmdb')) {
    //reader object from shared location for all websites in the server
    //January 28th 2020 - Ticket GP-2
    $reader = new Reader('/var/www/GeoIP/GeoIP2-City.mmdb');
}elseif (is_readable($ftm_geo_target_plugin_path . '/geo/GeoIP2-City.mmdb')) {
    // This creates the Reader object, which should be reused across lookups.
    $reader = new Reader($ftm_geo_target_plugin_path . '/geo/GeoIP2-City.mmdb');
} else {
    $reader = null;
    function ftm_gt_db_missing_notice() {
            ?>
    <div class="error notice">
        <p><?php _e( 'The Geo IP database is missing!!', 'ftm_geo_target' ); ?></p>
    </div>
    <?php
    }
    add_action( 'admin_notices', 'ftm_gt_db_missing_notice' );
}

if ( get_option( 'ftmgt_database_version' ) != FTM_GT_DB_VERSION && !isset($_POST["v6_update"]) ) {
    function ftm_gt_db_outdated() {
        ?>
        <div class="error notice postbox">
            <h2><?php _e( 'The database for FTM Geo Target is outdated!!', 'ftm_geo_target' ); ?></h2>
            <form action="<?php echo FTM_WP_INSTALL_PREFIX; ?>/wp-admin/admin.php?page=ftm-geo-target-settings"  method="get">
                    <div class="inside">
                        <div>To update the database to the last version click here.</div>
                        <br>
                        <input type="submit" value="Update Now" class="btn btn-primary" name="v6_update">
                        <br>
                    </div>
            </form>
        </div>
        <?php
    }
    add_action( 'admin_notices', 'ftm_gt_db_outdated' );
}

// get least specific subdivision isocode
// $record->subdivisions[0]->isoCode;

function ftm_gt_getGeoCodesFromIP($userIP){
    global $reader;
    if (!$reader) {
        return array('', '');
    }
    try {
        $record = $reader->city($userIP);
        $curr_cc = $record->country->isoCode;
        $regionCode = ftm_gt_select_region_code($record->subdivisions, $curr_cc);

        $cc_and_rc = array(
            $curr_cc, // cc, country code
            $regionCode //rc, region code
        );
    } catch (\GeoIp2\Exception\AddressNotFoundException $e) {
        $cc_and_rc = array(
            '',
            '',
        );

    }


    return $cc_and_rc;
}

/**
 * Get the pair of geo codes from either the Nginx server parameters or the database and considers the debug IP.
 *
 * @param string $_deprecated Don't use, is here for backward compatibility.
 * @param string $set_globals Set to true if you need the $_GLOBALS variables set with the codes
 */
function ftm_gt_getGeoCodes($_deprecated="", $set_globals = false) {
    $should_use_cache_info = get_option( 'ftmgt_use_cache_info', 1 );

    if ($should_use_cache_info && isset($_SERVER["CITY_CODE"]) && isset($_SERVER["COUNTRY_CODE"])) {
        $cc = $_SERVER["COUNTRY_CODE"];
        $rc = $_SERVER["CITY_CODE"];
    } else {
        $rsGeoData = ftm_gt_getGeoCodesFromIP(isset($_GET['debug_ip'])?$_GET['debug_ip']:$_SERVER['REMOTE_ADDR']);
        $cc = $rsGeoData[0];
        $rc = $rsGeoData[1];
    }
    if ($set_globals) {
        $GLOBALS['cc'] = $cc;
        $GLOBALS['rc'] = $rc;
    }
    return [$cc, $rc];
}

function ftm_gt_select_region_code($subdivisions, $curr_cc){
    //subdivisions is an array of subdivision objects ordered from most general (largest) to most specific (smallest).

    $regionCode = '';
    $region_has_code = false;

    if ($subdivisions) {

        if (count($subdivisions) > 1) {
            //starting with the most specific, check if the subdivision has a code
            $most_to_least_subdivisons = array_reverse($subdivisions);
            $regionCode = ftm_gt_set_region_code_by_name($most_to_least_subdivisons);
        } else {
            //we only have one subdivision
            $regionCode = ftm_gt_set_region_code_by_name($subdivisions);
        }
    }

    return $regionCode;
}

function ftm_gt_set_region_code_by_name($subs_array){
    $regionCode = '';
    $region_has_code = false;

    //check if the subdivision has a code or just a name
    foreach ($subs_array as $subdivision) {
        if ($subdivision->isoCode !== ''){
            //this subdivision has a regioncode, we will use and return it
            $regionCode = $subdivision->isoCode;
            $region_has_code = true;
            break;
        }
    }
    //if subdivision does not have a region code, look up the region by name
    if (!$region_has_code){
        foreach ($subs_array as $subdivision) {
            if ($subdivision->name !== ''){
                $region_by_name = ftm_gt_get_region_by_name($subdivision->name, $curr_cc);
                if ($region_by_name) {
                    //if we found a matching region in the country, use the region code we have in our db
                    $regionCode = $region_by_name->regioncode;
                    break;
                }
            }
        }
    }
    return $regionCode;
}

function ftm_gt_get_recomendation_for_ip($ip, $groups = '*') {
    list($cc, $rc) = ftm_gt_getGeoCodes("", true);

    if (strlen($groups) <= 0) {
        $groups = '*';
    }
    $groups_list = explode(',', $groups);
    // If no group selected we return empty
    $group_id_selected = ftm_gt_find_match_group($groups_list, $cc, $rc);
    $group_data = ftm_geo_target_getGroupById($group_id_selected);
    $group_sites = ftm_geo_target_getGroupSites($group_id_selected);
    if (!empty($group_sites)) {
        $site_data = ftm_gt_process_site_data_to_array($group_sites[0]->siteid, $group_sites[0]->name);
        return $site_data;
    }
    return null;
}

function ftm_gt_get_region_by_name($subdivision_name, $curr_cc){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT r.* FROM " . $wpdb->prefix . "ftm_geo_target_regions_v6 WHERE r.regionname = " . $subdivision_name . " AND r.countrycode = " . $curr_cc);

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_gt_register_for_nginx_cache_plugin($filters = []) {
    $filters[] = "ftm_geo_target_update_site";
    $filters[] = "ftm_geo_target_add_site";
    $filters[] = "ftm_geo_target_update_group";
    $filters[] = "ftm_geo_target_add_group";
    $filters[] = "ftm_geo_target_update_content";
    $filters[] = "ftm_geo_target_add_content";
    return $filters;
}
add_filter("nginx_cache_purge_actions", "ftm_gt_register_for_nginx_cache_plugin");


function ftm_gt_format_outdated_regions($outdated_regions){

    $outdated_msg = '<div><strong>The following groups had outdated regions that were removed:</strong></div>';

    foreach ($outdated_regions as $region) {
        $outdated_msg .= '<div>Group Name: ';
        $outdated_msg .= $region->groupName;
        $outdated_msg .= ' - Outdated Region: ';
        $outdated_msg .= $region->old_region_name;
        $outdated_msg .= '</div>';
    }

    $outdated_msg .= '<div><strong>Please save this list so the groups that were changed can be updated as necessary!</strong></div>';

    return $outdated_msg;
}

// AJAX BLOCK REGISTRATION OF ACTIVITY
add_action('wp_ajax_ftm_geo_track', 'ftm_geo_target_track_block');
add_action('wp_ajax_nopriv_ftm_geo_track', 'ftm_geo_target_track_block');
function ftm_geo_target_track_block() {
    global $wpdb;

    $destination = $_POST['destination'];
    $link_text = $_POST['link_text'];
    $referer = $_SERVER['HTTP_REFERER']??false;
    list($cc, $rc) = ftm_gt_getGeoCodes();
    $debug_ip = ftm_geo_target_get_debug_ip_from_url($referer);
    $user_ip = $debug_ip??$_SERVER['REMOTE_ADDR'];

    $ftmGeoThemes = $wpdb->prefix . "ftm_geo_blocked_links";
    $wpdb->insert($ftmGeoThemes,
        array(
            'clicked'  => date('Y-m-d H:i:s'),
            'IP'  => $user_ip,
            'Country'  => $cc,
            'Region'  => $rc,
            'Origin'  => $referer,
            'Destination'  => $destination,
            'LinkText'  => $link_text,
        ),
        array(
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
            '%s',
        )
    );
    return $wpdb->insert_id !== false;
}

function ftm_geo_target_get_debug_ip_from_url($url) {
    $debug_ip = false;
    if ($url) {
        $query = parse_url($url, PHP_URL_QUERY);
        if ($query) {
            parse_str($query);
        }
    }
    return strlen($debug_ip)>0?$debug_ip:null;
}

function ftm_geo_target_get_default_banned_configuration() {
    return  [
        'active' => false,
        'regions' => [],
        'countries' => [],
        'affiliate_folder' => '/go/',
    ];
}

add_action('wp_enqueue_scripts', 'ftm_geo_target_check_banned');
function ftm_geo_target_check_banned() {
    $default_configuration = ftm_geo_target_get_default_banned_configuration();
    $banned_configuration = get_option( 'ftmgt_banned_configuration', $default_configuration);
    if ($banned_configuration['active']) {
        list($cc, $rc) = ftm_gt_getGeoCodes();
        if (in_array($cc, $banned_configuration['countries'])
            || in_array($rc.'_'.$cc, $banned_configuration['regions'])) {


            $affiliate_folders = explode('/', $banned_configuration['affiliate_folder']);
            $affiliate_folders = array_filter($affiliate_folders, function ($folder){return strlen($folder)>0;});
            $affiliate_folders_string = implode('|', $affiliate_folders);
            $affiliate_regex = "/($affiliate_folders_string)/";

            // Set the data to pass to the template
            $data = [
                'countries' => $banned_configuration['countries'],
                'regions' => $banned_configuration['regions'],
                'path' => $affiliate_regex,
                'current_country' => $cc,
                'current_region' => $rc,
            ];

            // Find the available template to use or the default one
            $templates = [];
            $templates[] = 'ftm-geo-target-banned-script.php';
            $templates[] = 'geo-target-themes/banned-script.php';
            $template_path = locate_template( array_filter( $templates ) );
            if (!$template_path) {
                $template_path = plugin_dir_path(__FILE__) . 'templates/banned-script-template.php';
            }

            // Process the script template
            $process = function($template_path, $data) {
                extract($data);
                ob_start();
                include $template_path;
                $content = ob_get_contents();
                ob_end_clean();
                return $content;
            };
            $script = $process($template_path, $data);

            // Embed the script
            wp_register_script( 'ftm-geo-target-banned', '' );
            wp_enqueue_script( 'ftm-geo-target-banned' );
            wp_add_inline_script('ftm-geo-target-banned', $script, 'before');
        }
    }
}

add_action('wp_ajax_ftm_geo_report', 'ftm_geo_target_track_report');
function ftm_geo_target_track_report() {
    global $wpdb;

    $table = $wpdb->prefix . "ftm_geo_blocked_links";
    $page = intval($_POST['page']??0);
    $start = filter_var($_POST['start']??null,FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/\d{4}-\d{2}-\d{2}/', 'default' => null]]);
    $end = filter_var($_POST['end']??null,FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/\d{4}-\d{2}-\d{2}/', 'default' => null]]);
    $rows = 20;
    $offset = $rows * $page;

    $base_query = "FROM wp_ftm_geo_blocked_links t "
        ."INNER JOIN wp_ftm_geo_target_countries c ON t.Country = c.iso_3166_2 "
        ."LEFT OUTER JOIN wp_ftm_geo_target_regions r ON t.Region = r.regioncode AND t.Country = r.countrycode ";
    if ($start && $end) {
        $base_query = $base_query . "WHERE clicked >= '$start 00:00:00' AND clicked <= '$end 23:59:59' ";
    } elseif($start) {
        $base_query = $base_query . "WHERE clicked >= '$start 00:00:00' ";
    } elseif($end) {
        $base_query = $base_query . "WHERE clicked <= '$end 23:59:59' ";
    }

    $count_query = "SELECT COUNT(*) " . $base_query;
    $query = "SELECT t.clicked, t.IP, c.full_name as Country, IFNULL(r.regionname, '-') as Region, t.Origin, t.Destination, t.LinkText "
        .$base_query
        ."ORDER BY t.ID DESC "
        ."LIMIT $offset, $rows";

    $count = $wpdb->get_var($count_query);
    $pages = ceil($count / $rows);
    $prev = $page>0?$page-1:-1;
    $next = ($offset+$rows) < $count?$page+1:-1;

    $results = $wpdb->get_results($query);

    $data = [
        'total' => $count,
        'pages' => $pages,
        'page' => $page,
        'prev' => $prev,
        'next' => $next,
        'data' => $results,
    ];
    $response = json_encode($data);
    echo $response;
    die;
}

//PLUGIN UTILITY METHODS
function read_sql_file($filename){
    try {
        $main_sql_data_file = __DIR__ . '/sql_files/' . $filename;
        $sql_file = fopen($main_sql_data_file, "r");
        $main_sql_data_query = fread($sql_file, filesize($main_sql_data_file));
        fclose($sql_file);

        return $main_sql_data_query;
    }
    catch (Exception $e){
        return ("Error: " . $e->getMessage());
    }
}

function read_theme_render_file($theme_name, $type = 'group'){
    $theme_name = strtolower($theme_name);

    try {
        // Attempt to find the theme in the current template
        $template_path = get_template_directory();
        $in_template_themes = $template_path . ('cta'===$type?"/geo-cta-themes/":"/geo-target-themes/");
        $raw_data = ftm_read_theme_render_file_from_path($theme_name, $in_template_themes);
        if ($raw_data)
            return $raw_data;

        // No theme found, attempt to get it from the plugin directory
        $path = __DIR__ . '/themes/';
        $raw_data = ftm_read_theme_render_file_from_path($theme_name, $path);
        if ($raw_data)
            return $raw_data;
        return "Error: file doesn't exists or is not readable in path: " . $path;
    }
    catch (Exception $e){
        return ("Error: " . $e->getMessage());
    }
}

function ftm_read_theme_render_file_from_path($theme_name, $path) {
    $main_theme_data_file = $path . $theme_name . '/' .$theme_name . '-render.php' ;
    if (file_exists($main_theme_data_file) && is_readable($main_theme_data_file)) {
        $theme_file = fopen($main_theme_data_file, "r");
        $theme_raw_contents = fread($theme_file, filesize($main_theme_data_file));
        fclose($theme_file);

        return $theme_raw_contents;
    }
    return null;
}

function ftm_geo_target_jsLog($message){
    echo '<script type="text/javascript">
           console.log('.$message.');
      </script>';
}

function ftm_geo_target_htmlField($fieldType, $fieldname, $oldValue=""){

    if(strtolower($fieldType) == "textbox"){
        echo '<input size="70" class="ftm_geo_target_big_input" value="' . $oldValue .'" type="textbox" name="' . $fieldname . '"/>';
    }elseif (strtolower($fieldType) == "picture"){
        $control_id = rand();
        echo '<input id="upload_'. $control_id .'_image" type="text" size="70" class="upload_image" name="' . $fieldname . '" value="' . $oldValue .'" />
                <input id="upload_'. $control_id .'_image_button" class="upload_image_button" type="button" value="Upload Image" />';
    }elseif (strtolower($fieldType) == "wysiwyg"){
        $editorID = $fieldname;
        $content = $oldValue;//$content = get_option($oldValue);
        wp_editor( stripslashes($content), $editorID, $settings = array('textarea_rows'=> '10') );
    }elseif (strtolower($fieldType) == "geovalue"){
        $html = "";

        $valueFieldID = "geoValue_".$fieldname."_valuetxt";
        $valueDdl = "geoValue_".$fieldname."_value_country";
        $valueContainerID = "geoValue_".$fieldname."_container";
        $countries = ftm_geo_target_getCountries();

        $html .= '<div class="geo_value_wrapper">';
        $html .= '<div class="geo_value_top_fields">';
        $html .= '<label for="'.$valueDdl.'">Country:</label>';
        $html .= '<select name="'.$valueDdl.'" id="'.$valueDdl.'" title="Countries" data-placeholder="Choose a Country..." class="chosen_ddl">';
        foreach ($countries as $country){
            $html .= '<option value="'.$country->iso_3166_2.'">' . $country->name . '</option>';
        }
        $html .= '</select>';
        $html .= '</div>';
        $html .= '<div class="geo_value_top_fields">';
        $html .= '<label for="'.$valueFieldID.'">Value:</label>';
        $html .= '<textarea size="80" class="ftm_geo_target_big_input required_field" rows="10" cols="70" name="'.$valueFieldID.'" id="'.$valueFieldID.'"></textarea>&nbsp;&nbsp;';
        $html .= '<input type="button" onclick="add_geovalue_to_container(\''. $valueDdl .'\',\''. $valueFieldID .'\', \''. $valueContainerID .'\',\''.$fieldname.'\');" name="ftmgeo_add" class="btn btn-primary" value="Add">';
        $html .= '</div>';
        $html .= '<hr>';
        $html .= '<div class="geo_value_value_fields" id="'.$valueContainerID.'">';
        if($oldValue !== "") {
            $parsed_json_old_value = json_decode(stripcslashes($oldValue));
            if ($parsed_json_old_value !== null) {
                foreach ($parsed_json_old_value as $item) {
                    $html .= "<div class='gv_item' data-content='" . $item->value . "' data-text='" . $item->country . "'data-fieldname='".$fieldname."'><span><img src='/wp-content/plugins/ftm-geo-target/flags/" . $item->country . ".png' />"
                        ."<span class='ftm-country-item'>".$item->country."</span>"
                        ."<textarea>" . $item->value . "</textarea>"
                        ."<div class='btn btn-success btn-lg submit-geo-value'><span class='glyphicon glyphicon-save'></span></div>"
                        ."<code class='textarea textarea-display'>" . $item->value . "</code>"
                        ."</span>"
                        ."<div class='btn btn-info btn-lg edit-geo-value geo-button-display'><span class='glyphicon glyphicon-edit'></span></div>"
                        ."<div class='btn btn-danger btn-lg' onclick='remove_gv_item_output(jQuery(this)," . $fieldname . ");'><span class='glyphicon glyphicon-trash'></span></div></div>";
                }
            }
        }
        $html .= '</div>';
        $html .= '<textarea style="display:none;" name="'.$fieldname.'" id="'.$fieldname.'">' . str_replace("\\","", $oldValue) . '</textarea>';
        $html .= '</div>';


        echo $html;
    }

}

function ftm_geo_target_html_content_field($fieldname, $oldValue="") {
    $html = "";

    $valueFieldID = "geoValue_".$fieldname."_valuetxt";
    $valueDdl = "geoValue_".$fieldname."_value_country";
    $valueContainerID = "geoValue_".$fieldname."_container";
    $countries = ftm_geo_target_getCountries();

    $html .= '<div class="geo_value_wrapper">';
    $html .= '<div class="geo_value_top_fields">';
    $html .= '<label for="'.$valueDdl.'">Country:</label>';
    $html .= '<select name="'.$valueDdl.'" id="'.$valueDdl.'" title="Countries" data-placeholder="Choose a Country..." class="chosen_ddl">';
    foreach ($countries as $country){
        $html .= '<option value="'.$country->iso_3166_2.'">' . $country->name . '</option>';
    }
    $html .= '</select>';
    $html .= '</div>';
    $html .= '<div class="geo_value_top_fields">';
    $html .= '<label for="'.$valueFieldID.'">Value:</label>';
    $html .= '<textarea size="80" class="ftm_geo_target_big_input required_field" rows="10" cols="70" name="'.$valueFieldID.'" id="'.$valueFieldID.'"></textarea>&nbsp;&nbsp;';
    $html .= '<input type="button" onclick="add_geovalue_to_container(\''. $valueDdl .'\',\''. $valueFieldID .'\', \''. $valueContainerID .'\',\''.$fieldname.'\');" name="ftmgeo_add" class="btn btn-primary" value="Add">';
    $html .= '</div>';
    $html .= '<hr>';
    $html .= '<div class="geo_value_value_fields" id="'.$valueContainerID.'">';
    if($oldValue !== "") {
        $parsed_json_old_value = json_decode(str_replace("\\", "", $oldValue));
        if ($parsed_json_old_value !== null) {
            foreach ($parsed_json_old_value as $item) {
                $html .= "<div class='gv_item' data-content='" . $item->value . "' data-text='" . $item->country . "' data-fieldname='".$fieldname."'><span><img src='/wp-content/plugins/ftm-geo-target/flags/" . $item->country . ".png' />"
                    ."<span class='ftm-country-item'>".$item->country."</span>"
                    ."<textarea>" . $item->value . "</textarea>"
                    ."<div class='btn btn-success btn-lg submit-geo-value'><span class='glyphicon glyphicon-save'></span></div>"
                    ."<code class='textarea textarea-display'>" . $item->value . "</code>"
                    ."</span>"
                    ."<div class='btn btn-info btn-lg edit-geo-value geo-button-display'><span class='glyphicon glyphicon-edit'></span></div>"
                    ."<div class='btn btn-danger btn-lg' onclick='remove_gv_item_output(jQuery(this)," . $fieldname . ");'><span class='glyphicon glyphicon-trash'></span></div></div>";
            }
        }
    }
    $html .= '</div>';
    $html .= '<textarea style="display:none;" name="'.$fieldname.'" id="'.$fieldname.'">' . str_replace("\\","", $oldValue) . '</textarea>';
    $html .= '</div>';


    echo $html;
}

function ftm_geo_target_lookup_ip($ipaddress){
    $ftm_geo_target_plugin_url     = WP_PLUGIN_URL . '/ftm-geo-target';
    $ftm_geo_target_plugin_path    = WP_PLUGIN_DIR . '/ftm-geo-target';
    $settings = ftm_geo_target_getSettings();

    $rsGeoData = ftm_gt_getGeoCodesFromIP($ipaddress);
    $cc = $rsGeoData[0];
    $rc = $rsGeoData[1];

    return "Country code: " . $cc . " - Region: " . $rc;
}

//OPTION FIELDS
function ftm_geo_target_getFieldTypes(){

    GLOBAL $wpdb;

    $ftmGeoTypes = $wpdb->prefix . "ftm_geo_target_field_types";

    $tables  = $wpdb->get_results("SELECT * FROM " . $ftmGeoTypes);

    return $tables;

}

function ftm_geo_target_getCurrentFields(){

    GLOBAL $wpdb;

    $wizard_options  = $wpdb->get_results("SELECT o.*, t.typename FROM ".$wpdb->prefix."ftm_geo_target_site_options o INNER JOIN ".$wpdb->prefix."ftm_geo_target_field_types t ON o.fieldtypeid = t.typeid ORDER BY fieldorder");

    return $wizard_options;

}

function ftm_geo_target_getFieldValue($siteID, $optionID){

    GLOBAL $wpdb;

    $option_values  = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."ftm_geo_target_site_values WHERE siteid = " . $siteID . " AND siteoptionid = ". $optionID );

    if(sizeof($option_values) > 0){
        return $option_values[0]->siteoptionvalue;
    }
    else // No results found
    {
        return "";
    }

}

function ftm_geo_target_deleteOptionFieldValues($optionId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_site_values", array( 'siteoptionid' => $optionId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteOptionField($optionId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_site_options", array( 'optionid' => $optionId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

//SITES
function ftm_geo_target_currentSites(){

    GLOBAL $wpdb;

    $ftmGeoSites = $wpdb->prefix . "ftm_geo_target_sites";

    $sites  = $wpdb->get_results("SELECT * FROM " . $ftmGeoSites);

    return $sites;

}

function ftm_geo_target_sites_info($siteID){

    GLOBAL $wpdb;

    $ftmGeoSites = $wpdb->prefix . "ftm_geo_target_sites";

    $sites  = $wpdb->get_results("SELECT * FROM " . $ftmGeoSites . " WHERE siteid = " . $siteID );

    return $sites;

}

function ftm_geo_target_getSiteOptions($siteID){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ftm_geo_target_site_values sv INNER JOIN " . $wpdb->prefix . "ftm_geo_target_site_options so ON sv.siteoptionid = so.optionid INNER JOIN " . $wpdb->prefix . "ftm_geo_target_field_types ft ON so.fieldtypeid = ft.typeid WHERE sv.siteid = " . $siteID);

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_updateSiteOptionField($id, $name, $typeid){
    GLOBAL $wpdb;
    $result = false;

    $update = $wpdb->update($wpdb->prefix . "ftm_geo_target_site_options",
        array(
            'fieldname'  => $name,
            'fieldtypeid'=> $typeid
        ),
        array ('optionid' =>  $id),
        array(
            '%s',
            '%d'
        )
    );

    if($update !== false){
        $result = true;
    }
    else
    {
        $result = false;
        ftm_geo_target_jsLog("'Option Field Update Failed'");
    }

    return $result;
}

function ftm_geo_target_deleteSiteFromGroups($siteId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_sites_group", array( 'SiteId' => $siteId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteSiteOptionValues($siteId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_site_values", array( 'siteid' => $siteId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteSite($siteId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_sites", array( 'siteid' => $siteId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

//COUNTRIES
function ftm_geo_target_getCountries(){
    GLOBAL $wpdb;

    $ftmGeoCountries = $wpdb->prefix . "ftm_geo_target_countries";

    $countries  = $wpdb->get_results("SELECT DISTINCT * FROM " . $ftmGeoCountries . " ORDER BY name");

    return $countries;
}

function ftm_geo_target_getCountry($country_code){
    GLOBAL $wpdb;

    $ftmGeoCountries = $wpdb->prefix . "ftm_geo_target_countries";

    $result  = $wpdb->get_results("SELECT * FROM " . $ftmGeoCountries . " WHERE iso_3166_2 = '$country_code'");
    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    return null;
}

//REGIONS
function ftm_geo_target_getRegions(){
    GLOBAL $wpdb;

    $ftmGeoRegions = $wpdb->prefix . "ftm_geo_target_regions_v6";

    $regions  = $wpdb->get_results("SELECT * FROM " . $ftmGeoRegions);

    return $regions;
}

// CTAs
function ftm_geo_target_currentCtas() {
    GLOBAL $wpdb;
    $table = $wpdb->prefix . "ftm_geo_cta";
    return $wpdb->get_results("SELECT *  FROM ". $table . " order by CtaName asc");
}

function ftm_geo_target_currentCtasAuto() {
    GLOBAL $wpdb;
    $table = $wpdb->prefix . "ftm_geo_cta";
    return $wpdb->get_results("SELECT *  FROM ". $table . " WHERE UseAuto = 1 order by CtaOrder asc");
}

//GROUPS
function ftm_geo_target_currentGroups(){
    GLOBAL $wpdb;
    $ftmGeoGroups = $wpdb->prefix . "ftm_geo_target_groups";
    $groups  = $wpdb->get_results("SELECT pg.*, (SELECT GroupName FROM ". $ftmGeoGroups ." WHERE GroupId = pg.ParentGroupId)  as ParentName FROM ". $ftmGeoGroups ." pg");
    return $groups;
}

function ftm_geo_target_currentContent() {
    GLOBAL $wpdb;
    $ftmGeoContents = $wpdb->prefix . "ftm_geo_content";
    $contents  = $wpdb->get_results("SELECT * FROM " . $ftmGeoContents);
    return $contents;
}

function ftm_gt_expand_groups_wildcard($group_names) {
    GLOBAL $wpdb;
    $group_names = array_map(function($group_name){ return str_replace('-', ' ', str_replace('*', '%', $group_name));}, $group_names);
    $group_query = "";
    $first = true;
    foreach($group_names as $group_name) {
        // Make sure group name is clean
        $group_name = preg_replace('/[^a-z0-9_% ]/i', '', $group_name);
        if ($first) {
            if (is_numeric($group_name)) {
                $group_query .= " g.GroupId = $group_name ";
            } else {
                $group_query .= " g.GroupName like '$group_name' ";
            }
            $first = false;
        } else {
            if (is_numeric($group_name)) {
                $group_query .= " OR g.GroupId = $group_name ";
            } else {
                $group_query .= " OR g.GroupName like '$group_name' ";
            }
        }
    }

    $result = $wpdb->get_results("SELECT g.* FROM " . $wpdb->prefix . "ftm_geo_target_groups g WHERE $group_query");
    $result_list = [];
    if(sizeof($wpdb->last_result) > 0){
        foreach($result as $group_info) {
            $result_list[] = $group_info->GroupId;//$group_info->GroupName;
        }
    }
    return $result_list;
}

function ftm_gt_expand_ctas_wildcard($group_names) {
    GLOBAL $wpdb;
    $group_names = array_map(function($group_name){ return str_replace('-', ' ', str_replace('*', '%', $group_name));}, $group_names);
    $group_query = "";
    $first = true;
    foreach($group_names as $group_name) {
        // Make sure group name is clean
        $group_name = preg_replace('/[^a-z0-9_% ]/i', '', $group_name);
        if ($first) {
            if (is_numeric($group_name)) {
                $group_query .= " g.CtaId = $group_name ";
            } else {
                $group_query .= " g.CtaName like '$group_name' ";
            }
            $first = false;
        } else {
            if (is_numeric($group_name)) {
                $group_query .= " OR g.CtaId = $group_name ";
            } else {
                $group_query .= " OR g.CtaName like '$group_name' ";
            }
        }
    }

    $result = $wpdb->get_results("SELECT g.* FROM " . $wpdb->prefix . "ftm_geo_cta g WHERE $group_query");
    $result_list = [];
    if(sizeof($wpdb->last_result) > 0){
        foreach($result as $group_info) {
            $result_list[] = $group_info->CtaId;//$group_info->GroupName;
        }
    }
    return $result_list;
}

function ftm_gt_expand_content_wildcard($content_names) {
    GLOBAL $wpdb;
    $content_names = array_map(function($content_name){ return str_replace('-', ' ', str_replace('*', '%', $content_name));}, $content_names);
    $content_query = "";
    $first = true;
    foreach($content_names as $content_name) {
        // Make sure group name is clean
        $content_name = preg_replace('/[^a-z0-9_% ]/i', '', $content_name);
        if ($first) {
            $content_query .= " c.name like '$content_name' ";
            $first = false;
        } else {
            $content_query .= " OR c.name like '$content_name' ";
        }
    }
    $result = $wpdb->get_results("SELECT c.* FROM " . $wpdb->prefix . "ftm_geo_content c WHERE $content_query");
    $result_list = [];
    if(sizeof($wpdb->last_result) > 0){
        foreach($result as $content_info) {
            $result_list[] = $content_info->ContentId;
        }
    }
    return $result_list;
}

function ftm_geo_target_getGroup($groupName){
    GLOBAL $wpdb;

    $groupName = str_replace("-" ," ", $groupName);

    $result = $wpdb->get_results("SELECT g.*, t.ThemeName FROM " . $wpdb->prefix . "ftm_geo_target_groups g INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_themes t ON g.GroupThemeId = t.ThemeId WHERE g.GroupName = '" . $groupName . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_getGroupById($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT g.*, t.ThemeName FROM " . $wpdb->prefix . "ftm_geo_target_groups g INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_themes t ON g.GroupThemeId = t.ThemeId WHERE g.GroupId = '" . $groupId . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    return null;
}

function ftm_geo_target_getCtaById($ctaId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_cta';
    $theme_table_name = $wpdb->prefix . 'ftm_geo_target_themes';

    $result = $wpdb->get_results("SELECT c.*, t.ThemeName FROM " . $table_name . " c left outer join " . $theme_table_name . " t on c.CtaThemeId = t.ThemeId WHERE CtaId = '" . $ctaId . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    return null;
}

function ftm_geo_target_getCtaByName($name) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_cta';
    $theme_table_name = $wpdb->prefix . 'ftm_geo_target_themes';

    $result = $wpdb->get_results("SELECT c.*, t.ThemeName FROM " . $table_name . " c left outer join " . $theme_table_name . " t on c.CtaThemeId = t.ThemeId WHERE CtaName = '" . $name . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    return null;
}

function ftm_geo_target_getCtaSetById($ctaSetId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_auto_ctas';
    $theme_table_name = $wpdb->prefix . 'ftm_geo_target_themes';

    $result = $wpdb->get_results("SELECT s.*, t.ThemeName FROM " . $table_name . " s left outer join ". $theme_table_name." t on s.CtaThemeId = t.ThemeId WHERE CtaSetId = '" . $ctaSetId . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    return null;
}

function ftm_geo_target_getCtaSets($only_active = false) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_auto_ctas';
    $theme_table_name = $wpdb->prefix . 'ftm_geo_target_themes';

    if ($only_active) {
        $result = $wpdb->get_results("SELECT s.*, t.ThemeName FROM " . $table_name . " s left outer join ".$theme_table_name." t on s.CtaThemeId = t.ThemeId WHERE CtaActive = 1 ORDER BY CtaSetId");
    } else {
        $result = $wpdb->get_results("SELECT s.*, t.ThemeName FROM " . $table_name . " s left outer join ".$theme_table_name." t on s.CtaThemeId = t.ThemeId ORDER BY CtaSetId");
    }

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    return null;
}

function ftm_geo_target_getCTACountries($ctaId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_countries_cta';

    $result = $wpdb->get_results("SELECT DISTINCT c.* FROM " . $wpdb->prefix . "ftm_geo_target_countries c INNER JOIN " . $table_name . " cg ON c.iso_3166_2 = cg.CountryCode WHERE cg.CtaId = " . $ctaId );

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_getCTARegions($ctaId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_regions_cta';

    $result = $wpdb->get_results("SELECT r.* FROM " . $wpdb->prefix . "ftm_geo_target_regions_v6 r INNER JOIN " . $table_name . " rg ON r.regionid = rg.RegionId WHERE rg.CtaId = " . $ctaId);

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_getCtaSite($ctaId){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT s.* FROM " . $wpdb->prefix . "ftm_geo_target_sites s INNER JOIN ". $wpdb->prefix  ."ftm_geo_sites_cta sg ON s.siteid = sg.SiteId WHERE sg.CtaId = " . $ctaId );

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_deleteCta($ctaID) {
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_cta", array( 'CtaId' => $ctaID ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteCtaSites($ctaID) {
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_sites_cta", array( 'CtaId' => $ctaID ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteCtaCountries($ctaId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_countries_cta';

    $result = $wpdb->delete($table_name, array('CtaId' => $ctaId), array('%d') );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteCtaRegions($ctaId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_regions_cta';

    $result = $wpdb->delete($table_name, array('CtaId' => $ctaId), array('%d') );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_getContentById($contentId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_content';

    $result = $wpdb->get_results("SELECT * FROM " . $table_name . " WHERE ContentId = '" . $contentId . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    return null;
}

function ftm_geo_target_getContentByName($name) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_content';

    $result = $wpdb->get_results("SELECT * FROM " . $table_name . " WHERE name = '" . $name . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_getGroupCustomization($groupId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_customization';
    $values = [];

    $results = $wpdb->get_results("SELECT * FROM " . $table_name . " WHERE GroupId = '" . $groupId . "'");

    foreach ($results as $result) {
        $values[$result->key] = $result->value;
    }
    return $values;
}

function ftm_geo_target_getContentCountries($contentId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_content_countries';

    $result = $wpdb->get_results("SELECT DISTINCT c.* FROM " . $wpdb->prefix . "ftm_geo_target_countries c INNER JOIN " . $table_name . " cg ON c.iso_3166_2 = cg.CountryCode WHERE cg.ContentId = " . $contentId );

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}
function ftm_geo_target_getContentRegions($contentId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_content_regions';

    $result = $wpdb->get_results("SELECT r.* FROM " . $wpdb->prefix . "ftm_geo_target_regions_v6 r INNER JOIN " . $table_name . " rg ON r.regionid = rg.RegionId WHERE rg.ContentId = " . $contentId);

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_deleteContentCountries($contentId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_content_countries';

    $result = $wpdb->delete($table_name, array('ContentId' => $contentId), array('%d') );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteContentRegions($contentId) {
    GLOBAL $wpdb;
    $table_name = $wpdb->prefix . 'ftm_geo_content_regions';

    $result = $wpdb->delete($table_name, array('ContentId' => $contentId), array('%d') );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_get_group_for_country_or_region($country, $region){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT g.*, t.ThemeName FROM " . $wpdb->prefix . "ftm_geo_target_groups g INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_themes t ON g.GroupThemeId = t.ThemeId WHERE g.GroupId = '" . $groupId . "'");

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_getGroupSites($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT s.* FROM " . $wpdb->prefix . "ftm_geo_target_sites s INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_sites_group sg ON s.siteid = sg.SiteId WHERE sg.GroupId = " . $groupId . " ORDER BY sg.SiteOrder");

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_deleteGroupSites($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_sites_group", array( 'GroupId' => $groupId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_getGroupRegions($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT r.* FROM " . $wpdb->prefix . "ftm_geo_target_regions_v6 r INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_regions_group rg ON r.regionid = rg.RegionId WHERE rg.GroupId = " . $groupId );

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_deleteGroupRegions($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_regions_group", array( 'GroupId' => $groupId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_getGroupCountries($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT DISTINCT c.* FROM " . $wpdb->prefix . "ftm_geo_target_countries c INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_countries_group cg ON c.iso_3166_2 = cg.CountryCode WHERE cg.GroupId = " . $groupId );

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    else
    {
        return null;
    }
}

function ftm_geo_target_deleteGroupCountries($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_countries_group", array( 'GroupId' => $groupId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteGroup($groupId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_target_groups", array( 'GroupId' => $groupId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_deleteContent($contentId){
    GLOBAL $wpdb;

    $result = $wpdb->delete( $wpdb->prefix . "ftm_geo_content", array( 'ContentId' => $contentId ), array( '%d' ) );

    if($result !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_checkGroup($groupName){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ftm_geo_target_groups WHERE GroupName = '" . $groupName . "'");

    if(sizeof($wpdb->last_result) > 0){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_getParentGroup($groupId) {
    global $wpdb;

    $table_name = $wpdb->prefix . 'ftm_geo_target_groups';
    $result = $wpdb->get_results("SELECT p.* FROM " . $table_name . " c INNER JOIN " . $table_name ." p ON c.ParentGroupId = p.GroupId WHERE c.GroupId = " . $groupId);
    if(sizeof($wpdb->last_result) > 0){
        return $result[0];
    }
    return null;
}

function ftm_geo_target_getGroupChildren($groupId) {
    global $wpdb;

    $table_name = $wpdb->prefix . 'ftm_geo_target_groups';
    $result = $wpdb->get_results("SELECT * FROM " . $table_name . " WHERE ParentGroupId = " . $groupId);

    if(sizeof($wpdb->last_result) > 0){
        return $result;
    }
    return null;
}

function ftm_geo_target_checkGroupCountry($groupId,$country_to_check){
    GLOBAL $wpdb;

    //If the group has the default country ("00") it will show up no matter what.
    $result = $wpdb->get_results("SELECT c.* FROM " . $wpdb->prefix . "ftm_geo_target_countries c INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_countries_group cg ON c.iso_3166_2 = cg.CountryCode WHERE (cg.GroupId = " . $groupId . " AND cg.CountryCode = '" . $country_to_check . "') OR cg.CountryCode = '00'");

    if(sizeof($wpdb->last_result) > 0){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_checkGroupRegion($groupId,$region_to_check, $country_to_check){
    GLOBAL $wpdb;

    $result = $wpdb->get_results("SELECT r.* FROM " . $wpdb->prefix . "ftm_geo_target_regions_v6 r INNER JOIN ". $wpdb->prefix  ."ftm_geo_target_regions_group rg ON r.regionid = rg.RegionId WHERE rg.GroupId = " . $groupId . " AND r.regioncode = '" . $region_to_check . "' AND r.countrycode = '" . $country_to_check . "'");

    if(sizeof($wpdb->last_result) > 0){
        return true;
    }
    else
    {
        return false;
    }
}

//THEMES
function ftm_geo_target_themes($only_active, $type = 'target'){

    GLOBAL $wpdb;

    $ftmGeoThemes = $wpdb->prefix . "ftm_geo_target_themes";

    if($only_active) {
        $themes = $wpdb->get_results("SELECT DISTINCT * FROM " . $ftmGeoThemes . " WHERE ThemeActive = 1");
    }
    else
    {
        $themes = $wpdb->get_results("SELECT DISTINCT * FROM " . $ftmGeoThemes . " WHERE ThemeActive = 0");
    }
    $checked_themes = [];
    $template_path = get_template_directory();

    foreach($themes as $theme) {
        if (file_exists($template_path . "/geo-target-themes/" . $theme->ThemeName)) {
            $theme->type = 'target';
        } elseif (file_exists($template_path . "/geo-cta-themes/" . $theme->ThemeName)) {
            $theme->type = 'cta';
        } else {
            $theme->type = 'unknown';
        }
        if ('all' === $type || $type === $theme->type) {
            $checked_themes[] = $theme;
        }
    }

    return $checked_themes;

}

function ftm_geo_target_check_theme($themeName){

    GLOBAL $wpdb;

    $ftmGeoThemes = $wpdb->prefix . "ftm_geo_target_themes";

    $result = $wpdb->get_results("SELECT DISTINCT * FROM " . $ftmGeoThemes . " WHERE ThemeName = '" . $themeName . "'" );

    if(sizeof($wpdb->last_result) > 0){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_check_theme_is_active($themeName){

    GLOBAL $wpdb;

    $ftmGeoThemes = $wpdb->prefix . "ftm_geo_target_themes";

    $result = $wpdb->get_results("SELECT DISTINCT * FROM " . $ftmGeoThemes . " WHERE (ThemeName = '" . $themeName . "' AND ThemeActive = 1)" );

    if(sizeof($wpdb->last_result) > 0){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_geo_target_install_theme($themeName){
    GLOBAL $wpdb;

    if(ftm_geo_target_check_theme($themeName))
    {
        return false;
    }
    else
    {
        $ftmGeoThemes = $wpdb->prefix . "ftm_geo_target_themes";

        $insert = $wpdb->insert($ftmGeoThemes,
            array(
                'ThemeName'  => $themeName,
                'ThemeActive'  => 0
            ),
            array(
                '%s',
                '%d'
            )
        );


        return ($wpdb->insert_id !== false);
    }
}

function ftm_geo_target_activate_theme($themeID){
    GLOBAL $wpdb;

    $ftmGeoThemes = $wpdb->prefix . "ftm_geo_target_themes";

    $update = $wpdb->update($ftmGeoThemes,
        array(
            'ThemeActive'  => 1
        ),
        array(
            'ThemeId' => $themeID
        ),
        array(
            '%d'
        )
    );

    return ($update !== false);
}

function ftm_geo_target_deactivate_theme($themeID){
    GLOBAL $wpdb;

    $ftmGeoThemes = $wpdb->prefix . "ftm_geo_target_themes";

    $update = $wpdb->update($ftmGeoThemes,
        array(
            'ThemeActive'  => 0
        ),
        array(
            'ThemeId' => $themeID
        ),
        array(
            '%d'
        )
    );

    return ($update !== false);
}

//SETTINGS
function ftm_geo_target_getSettings(){

    GLOBAL $wpdb;

    $ftmGeoSettings = $wpdb->prefix . "ftm_geo_target_settings";

    $result = $wpdb->get_results("SELECT * FROM " . $ftmGeoSettings . "  LIMIT 1");

    return $result;
}

function ftm_geo_target_update_geoFile_updateDate(){

    GLOBAL $wpdb;
    $update = $wpdb->query( "UPDATE " . $wpdb->prefix . "ftm_geo_target_settings SET GeoFileLastUpdated = NOW() WHERE DebugStatus IS NOT NULL");

    if($update !== false){
        return true;
    }
    else
    {
        return false;
    }
}

function ftm_gt_extract_parameters_for_template($atts) {
    // Remove known non template parameters
    unset($atts['g']);
    unset($atts['s']);
    unset($atts['ctas']);
    unset($atts['groups']);
    unset($atts['theme']);
    $params = [];
    foreach ($atts as $param_name => $param_default_value) {
        $params[$param_name] = filter_var($param_default_value, FILTER_SANITIZE_STRING);
        // We store the upper case version too because WP always set parameters as lowercase and we are used to put the
        // geo target variables as upper case
        $params[strtoupper($param_name)] = filter_var($param_default_value, FILTER_SANITIZE_STRING);
    }
    return $params;
}

function ftm_gt_create_themes_structure($params) {
    $themes = [];
    $themes_text = isset($params['theme'])?explode(',', $params['theme']):[];
    $weights_text = isset($params['split_percentage'])?explode(',', $params['split_percentage']):[];
    for($current = 0; $current <=count($themes_text); $current++) {
        if ($themes_text[$current]) {
            $themes[] = [
                'theme' => $themes_text[$current],
                'weight' => isset($weights_text[$current])?$weights_text[$current]:100,
            ];
        }
    }
    return $themes;
}

function ftm_gt_find_match_group_cta($ctas, $cc, $rc) {
    // Create matrix of groups countries and zones
    $ctas = ftm_gt_expand_ctas_wildcard($ctas);
    $cta_matrix = [];

    foreach($ctas as $cta) {
        if (is_numeric($cta)) {
            $data = ftm_geo_target_getCtaById($cta);
        } else {
            $data = ftm_geo_target_getCtaByName($cta);
        }
        if(is_null($data) || empty($data) || !$data->CtaActive )
        {
            continue;
        }
        $ctaSite = ftm_geo_target_getCtaSite($data->CtaId);
        if (empty($ctaSite)) {
            continue;
        }
        $cta_regions = ftm_geo_target_getCTARegions($data->CtaId);
        $cta_countries = ftm_geo_target_getCTACountries($data->CtaId);

        $cta_matrix[$data->CtaId] = [
            'regions' => $cta_regions,
            'countries' => $cta_countries,
        ];
    }
    $cta_with_region_found = false;
    $cta_with_country_found = false;
    $cta_with_region_default = false;
    $cta_with_country_default = false;
    $cta_default = false;

    // Check regions
    $regions = array_combine(array_keys($cta_matrix), array_map(function($data){ return $data['regions']; }, $cta_matrix));

    // Check countries
    $countries = array_combine(array_keys($cta_matrix), array_map(function($data){ return $data['countries']; }, $cta_matrix));

    foreach ($countries as $group_id => $cta_countries) {
        //if (false === $group_with_country_default && is_null($group_countries)) {
        //    $group_with_country_default = $group_id;
        //}
        if ($cta_countries && is_array($cta_countries)) {
            foreach($cta_countries as $country_data) {
                if ($cc == $country_data->iso_3166_2) {
                    if(is_null($regions[$group_id])){ //If this group doesn't have regions, don't bother with them
                        $cta_with_country_found = $group_id;
                    }
                    else //If the group has regions, let's find the one with matching regions inside the matching country
                    {
                        foreach ($regions as $group_id => $cta_regions) {
                            if (false === $cta_with_region_default && is_null($cta_regions)) {
                                $cta_with_region_default = $group_id;
                            }
                            if($cta_regions) {
                                foreach ($cta_regions as $region_data) {
                                    if ($rc == $region_data->regioncode  && $cc == $region_data->countrycode ) {
                                        $cta_with_region_found = $group_id;
                                        $cta_with_country_found = $group_id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Find group with all default (none country nor region specified)
    foreach($cta_matrix as $group_id => $group_data) {
        // Default by selecting nothing in country nor regions
        if( is_null($group_data['regions']) && is_null($group_data['countries'])) {
            $cta_default = $group_id;
        } else {
            $cta_countries = $group_data['countries']?:[];
            foreach($cta_countries as $country_data) {
                // Default by selecting country 'Default'
                if ('00' === $country_data->iso_3166_2) {
                    $cta_default = $group_id;
                }
            }
        }
    }
    // Make a selection
    ($selected = $cta_with_region_found) || ($selected = $cta_with_country_found)
    || ($selected = $cta_default);
    //|| ($selected = $group_with_region_default) || ($selected = $group_with_country_default);
    if (isset($_GET['debug'])) {
        $content_debug_data = ftm_geo_target_getCtaById($selected);
        var_dump($content_debug_data->CtaName);
    }
    return $selected;
}

function ftm_gt_find_match_group($groups, $cc, $rc) {
    // Create matrix of groups countries and zones
    $groups = ftm_gt_expand_groups_wildcard($groups);
    $group_matrix = [];
    foreach($groups as $group) {
        if (is_numeric($group)) {
            $data = ftm_geo_target_getGroupById($group);
        } else {
            $data = ftm_geo_target_getGroup($group);
        }

        if(is_null($data) || empty($data) || !$data[0]->GroupActive )
        {
            continue;
        }
        $group_sites = ftm_geo_target_getGroupSites($data[0]->GroupId);
        if (empty($group_sites)) {
            continue;
        }

        $group_regions = ftm_geo_target_getGroupRegions($data[0]->GroupId);
        $group_countries = ftm_geo_target_getGroupCountries($data[0]->GroupId);

        $group_matrix[$data[0]->GroupId] = [
            'regions' => $group_regions,
            'countries' => $group_countries,
        ];
    }

    $group_with_region_found = false;
    $group_with_country_found = false;
    $group_with_region_default = false;
    $group_with_country_default = false;
    $group_default = false;

    // Check regions
    $regions = array_combine(array_keys($group_matrix), array_map(function($data){ return $data['regions']; }, $group_matrix));

    // Check countries
    $countries = array_combine(array_keys($group_matrix), array_map(function($data){ return $data['countries']; }, $group_matrix));

    foreach ($countries as $group_id => $group_countries) {
        //if (false === $group_with_country_default && is_null($group_countries)) {
        //    $group_with_country_default = $group_id;
        //}
        if ($group_countries && is_array($group_countries)) {
            foreach($group_countries as $country_data) {
                if ($cc == $country_data->iso_3166_2) {
                    if(is_null($regions[$group_id])){ //If this group doesn't have regions, don't bother with them
                        $group_with_country_found = $group_id;
                    }
                    else //If the group has regions, let's find the one with matching regions inside the matching country
                    {
                        foreach ($regions as $group_id => $group_regions) {
                            if (false === $group_with_region_default && is_null($group_regions)) {
                                $group_with_region_default = $group_id;
                            }
                            if($group_regions) {
                                foreach ($group_regions as $region_data) {
                                    if ($rc == $region_data->regioncode  && $cc == $region_data->countrycode ) {
                                        $group_with_region_found = $group_id;
                                        $group_with_country_found = $group_id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Find group with all default (none country nor region specified)
    foreach($group_matrix as $group_id => $group_data) {
        // Default by selecting nothing in country nor regions
        if( is_null($group_data['regions']) && is_null($group_data['countries'])) {
            $group_default = $group_id;
        } else {
            $group_countries = $group_data['countries']?:[];
            foreach($group_countries as $country_data) {
                // Default by selecting country 'Default'
                if ('00' === $country_data->iso_3166_2) {
                    $group_default = $group_id;
                }
            }
        }
    }

    // Make a selection
    ($selected = $group_with_region_found) || ($selected = $group_with_country_found)
    || ($selected = $group_default);
    //|| ($selected = $group_with_region_default) || ($selected = $group_with_country_default);
    if (isset($_GET['debug'])) {
        $content_debug_data = ftm_geo_target_getGroupById($selected);
        var_dump($content_debug_data[0]->name);
    }
    return $selected;
}

function ftm_gt_find_match_content($content_list, $cc, $rc) {
    // Create matrix of groups countries and zones
    $content_list = ftm_gt_expand_content_wildcard($content_list);
    $content_matrix = [];
    foreach($content_list as $content) {
        if (is_numeric($content)) {
            $data = ftm_geo_target_getContentById($content);
        } else {
            $data = ftm_geo_target_getContentByName($content);
        }

        if (is_array($data)) {
            $data = count($data)>=0?$data[0]:null;
        }
        if(is_null($data) || empty($data) || !$data->active )
        {
            continue;
        }

        $content_regions = ftm_geo_target_getContentRegions($data->ContentId);
        $content_countries = ftm_geo_target_getContentCountries($data->ContentId);

        $content_matrix[$data->ContentId] = [
            'regions' => $content_regions,
            'countries' => $content_countries,
        ];
    }

    $content_with_region_found = false;
    $content_with_country_found = false;
    $content_with_region_default = false;
    $content_with_country_default = false;
    $content_default = false;

    // Check regions
    $regions = array_combine(array_keys($content_matrix), array_map(function($data){ return $data['regions']; }, $content_matrix));

    // Check countries
    $countries = array_combine(array_keys($content_matrix), array_map(function($data){ return $data['countries']; }, $content_matrix));

    foreach ($countries as $content_id => $content_countries) {
        //if (false === $content_with_country_default && is_null($content_countries)) {
        //    $content_with_country_default = $content_id;
        //}
        if ($content_countries && is_array($content_countries)) {
            foreach($content_countries as $country_data) {
                if ($cc == $country_data->iso_3166_2) {
                    if(is_null($regions[$content_id])){ //If this group doesn't have regions, don't bother with them
                        $content_with_country_found = $content_id;
                    }
                    else //If the group has regions, let's find the one with matching regions inside the matching country
                    {
                        foreach ($regions as $content_id => $content_regions) {
                            if (false === $content_with_region_default && is_null($content_regions)) {
                                $content_with_region_default = $content_id;
                            }
                            if($content_regions) {
                                foreach ($content_regions as $region_data) {
                                    if ($rc == $region_data->regioncode  && $cc == $region_data->countrycode ) {
                                        $content_with_region_found = $content_id;
                                        $content_with_country_found = $content_id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Find group with all default (none country nor region specified)
    foreach($content_matrix as $content_id => $content_data) {
        // Default by selecting nothing in country nor regions
        if( is_null($content_data['regions']) && is_null($content_data['countries'])) {
            $content_default = $content_id;
        } else {
            $group_countries = $content_data['countries']?:[];
            foreach($group_countries as $country_data) {
                // Default by selecting country 'Default'
                if ('00' === $country_data->iso_3166_2) {
                    $content_default = $content_id;
                }
            }
        }
    }

    // Make a selection
    ($selected = $content_with_region_found) || ($selected = $content_with_country_found)
    || ($selected = $content_default);
    //|| ($selected = $group_with_region_default) || ($selected = $group_with_country_default);
    if (isset($_GET['debug'])) {
        $content_debug_data = ftm_geo_target_getContentById($selected);
        var_dump($content_debug_data[0]->name);
    }
    return $selected;
}

function ftm_gt_add_tracking_reference($script, $theme) {
    $mark = 'li='.urlencode($theme);
    return preg_replace(['/(href=[\'"][^\'"]+\?[^\'"]+)([\'"])/i','/(href=[\'"][^\'"?]+)([\'"])/i'], ['$1&'.$mark.'$2', '$1?'.$mark.'$2'], $script);
}

function ftm_gt_render_group($group, $theme_att, $params = [], $should_track = false, $process_single_site = false, $type = 'group') {
    if (is_array($group) && count($group)>0) {
        $group = $group[0];
    }
    if (is_numeric($group)) {
        if ('cta' === $type) {
            $data = ftm_geo_target_getCtaById($group);
        } else {
            $data = ftm_geo_target_getGroupById($group);
        }
    } elseif(is_string($group)) {
        if ('cta' === $type) {
            $data = ftm_geo_target_getCtaByName($group);
        } else {
            $data = ftm_geo_target_getGroup($group);
        }
    } else {
        if (property_exists($group, 'GroupId')) {
            $data = ftm_geo_target_getGroupById($group->GroupId);
        } else {
            $data = ftm_geo_target_getCtaById($group->CtaId);
        }
    }
    if (is_array($data) && count($data) > 0) {
        $data = $data[0];
    }
    if(is_null($data) )
    {
        return "";//"Please check group name";
    }
    $themeData = '';
    $has_php_code = stripos($themeData, '<?php') !== false;

    $theme = ftm_gt_choose_theme($theme_att, $data->ThemeName);

    $themeData = ftm_gt_get_theme_data($theme, $type);

    $themeData = ftm_gt_get_links_from_content($themeData);

    $themeData = ftm_gt_translate_words_in_template($themeData, $has_php_code, property_exists($group, 'GroupId')?$data->GroupId:$data->CtaId);

    $script = ftm_gt_replace_sites_data($themeData, property_exists($group, 'GroupId')?$data->GroupId:$data->CtaId, $has_php_code, $params, $process_single_site, property_exists($group, 'GroupId')?'group':'cta');

    $script = ftm_gt_clean_empty_tags($script);

    if ($should_track) {
        $script = ftm_gt_add_tracking_reference($script, $theme);
    }

    return $script;
}

function ftm_gt_render_content($content) {
    if (is_numeric($content)) {
        $data = ftm_geo_target_getContentById($content);
    } else {
        $data = ftm_geo_target_getContentByName($content);
    }

    if(is_null($data) )
    {
        return "";//"Please check group name";
    }

    $package = [
        'kind' => 'Geo Content Values',
        'name' => 'content_'.$data->ContentId,
        'title' => 'Content '.$data->name,
    ];
    $field_name = 'ftm_content_'.$data->ContentId;
    $value = apply_filters( 'wpml_translate_string', $data->value, $field_name, $package );
    $value = stripcslashes($value);

    // Common strings
    $matches = [];
    $found_common_strings = preg_match_all('/\[\[([^\[\]]+)\]\]/', $value, $matches);

    if ($found_common_strings) {
        foreach ($matches[1] as $common_text) {
            $translated = apply_filters( 'wpml_translate_single_string', $common_text, 'Geo Content Values', 'Common Text - '.$common_text);
            $value = strtr($value, ['[['.$common_text.']]' => $translated]);
        }
    }

    return $value;
}

function ftm_gt_get_links_from_content($content){
    $pattern = '/<img\s*(?:class\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|src\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|alt\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|width\s*\=\s*[\'\"](.*?)[\'\"].*?\s*|height\s*\=\s*[\'\"](.*?)[\'\"].*?\s*)+.*?>/si';
    preg_match_all($pattern, $content, $matches);
    foreach ($matches[2] as $key => $value) {
        $old_link = $matches[0][$key];
        $new_link = "";
        if(!empty($matches[3][$key])){ //Check if the image has already an ALT tag...
            $new_link = '<img class="'.$matches[1][$key].'" alt="' . $matches[3][$key] .'" src="'. $value .'"/>';
        }
        else
        {
            $new_alt = "[SITE_NAME] Logo";
            $new_link = '<img class="'.$matches[1][$key].'" alt="' . $new_alt .'" src="'. $value .'"/>';
        }
        $content = str_replace($old_link, $new_link, $content);
    }
    return $content;
}

function ftm_gt_choose_theme_from_array($themes) {
    if (count($themes) == 1)
        return $themes[0]['theme'];
    $stats = [];
    foreach($themes as $theme_information) {
        $stats = array_merge($stats, array_fill(0,$theme_information['weight'], $theme_information['theme']));
    }
    $selected = rand(0, count($stats) - 1);
    return  $stats[$selected];
}

function ftm_gt_choose_theme($themes, $theme_name) {
    if (!is_array($themes)) {
        $themes = ['theme' => $themes, 'weight' => 100];
    }
    $selected_theme = ftm_gt_choose_theme_from_array($themes);
    // If theme attribute is set in shortcode, and the theme is an existing active theme, override themes set in groups
    $theme_exists = ftm_geo_target_check_theme_is_active($selected_theme);
    if ($selected_theme === '' || !$theme_exists){
        return $theme_name;
    }
    return $selected_theme;
}

function ftm_gt_get_theme_data($theme_name, $type = 'group') {
    return read_theme_render_file($theme_name, $type);;
}

function ftm_gt_find_replaceable_in_template_content($template_content) {
    $matches = [];
    $found_translatable = preg_match_all('/\{\{([^\{\}]+)\}\}/', $template_content, $matches);
    if ($found_translatable) {
        return $matches[1];
    }
    return [];
}

function ftm_gt_translate_words_in_template($themeData, $has_php_code, $groupId = 0) {
    // Replace customized information
    $customized_values = ftm_geo_target_getGroupCustomization($groupId);
    $customized = [];
    foreach ($customized_values as $key => $value) {
        if (strlen($value) > 0) {
            $customized['{{'.$key.'}}'] = '{{'.$value.'}}';
        }
    }
    $themeData = strtr($themeData, $customized);
    // Translate words that show up inside {{}}
    $matches = [];
    $found_translatable = preg_match_all('/\{\{([^\{\}]+)\}\}/', $themeData, $matches);
    if ($found_translatable) {
        $translated = [];
        foreach ($matches[1] as $translatable) {
            if(strtolower($translatable) == "gambling site"){
                $translated_text = ftm_gt_replace_title($translatable);
            }else{
                $translated_text = __($translatable, 'Site Template');
            }
            //if ($has_php_code) {
            $translated_text = htmlspecialchars($translated_text, ENT_QUOTES|ENT_HTML5);
            //}
            $translated['{{'.$translatable.'}}'] = $translated_text;
        }
        $themeData = strtr($themeData, $translated);
    }
    return $themeData;
}

function ftm_gt_process_site_data_to_array($site_id, $site_name, $has_php_code = false, $site_count_position = 1) {
    $site_data = [];
    $package = [
        'kind' => 'Site Fields',
        'name' => 'site_'.$site_id,
        'title' => 'Site '.$site_name,
    ];

    // Site name and count
    $site_name = apply_filters( 'wpml_translate_string', $site_name, 'ftm_sitename_'.$site_id, $package );
    $site_data['SITE_NAME'] = $site_name;
    $site_data['COUNT'] = $site_count_position;

    // Process the rest of fields
    $site_options = ftm_geo_target_getSiteOptions($site_id);
    if ($site_options) {
        foreach ($site_options as $soption) {
            switch($soption->typename) {
                case 'textbox':
                    $field_name = 'ftm_site_'.$site_id.'_'.$soption->fieldname;
                    $optionValue = apply_filters( 'wpml_translate_string', $soption->siteoptionvalue, $field_name, $package );
                    break;
                case 'wysiwyg':
                    $field_name = 'ftm_site_'.$site_id.'_'.$soption->fieldname;
                    $optionValue = apply_filters( 'wpml_translate_string', $soption->siteoptionvalue, $field_name, $package );
                    break;
                case 'geoValue':
                    $geo_sets = json_decode(stripcslashes($soption->siteoptionvalue), false);
                    $result_value = "";

                    if(isset($geo_sets)) {
                        foreach ($geo_sets as $geo_set) {
                            if ($geo_set->country == $GLOBALS['cc']) {
                                $field_name = 'ftm_site_' . $site_id . '_' . $soption->fieldname . '_' . $geo_set->country;
                                $result_value = apply_filters('wpml_translate_string', $geo_set->value, $field_name, $package);
                            }
                        }
                    }

                    //If the geo value for the specific country is not found, then we search for a default value to fallback, if not present, a blank string is sent.
                    if($result_value === "" && isset($geo_sets)){
                        foreach($geo_sets as $geo_set) {
                            if($geo_set->country == "00"){
                                $field_name = 'ftm_site_'.$site_id.'_'.$soption->fieldname.'_'.$geo_set->country;
                                $result_value = apply_filters( 'wpml_translate_string', $geo_set->value, $field_name, $package );
                            }
                        }
                    }
                    $optionValue = $result_value;
                    break;
                default:
                    $optionValue = $soption->siteoptionvalue;
            }
            if ($has_php_code) {
                $optionValue = htmlspecialchars($optionValue, ENT_QUOTES|ENT_HTML5);
            }
            // Common strings
            $matches = [];
            $found_common_strings = preg_match_all('/\[\[([^\[\]]+)\]\]/', $optionValue, $matches);

            if ($found_common_strings) {
                foreach ($matches[1] as $common_text) {
                    $translated = apply_filters( 'wpml_translate_single_string', $common_text, 'Site Fields', 'Common Text - '.$common_text);
                    if ($has_php_code) {
                        $translated = htmlspecialchars($translated, ENT_QUOTES|ENT_HTML5);
                    }
                    $optionValue = strtr($optionValue, ['[['.$common_text.']]' => $translated]);
                }
            }

            $site_data[$soption->fieldname] = $optionValue;
        }

    }
    return $site_data;
}

function ftm_gt_process_group_data_to_array($groupId, $has_php_code = false) {
    $group_sites = ftm_geo_target_getGroupSites($groupId);
    $sites_data = [];
    $site_count = 0;
    foreach ($group_sites as $site) {
        $site_count++;
        $siteID = $site->siteid;
        $site_data = ftm_gt_process_site_data_to_array($siteID, $site->name, $has_php_code, $site_count);
        $sites_data[$siteID] = $site_data;
    }
    return $sites_data;
}

function ftm_gt_process_cta_data_to_array($ctaId, $has_php_code = false) {
    $group_sites = ftm_geo_target_getCtaSite($ctaId);
    $sites_data = [];
    $site_count = 0;
    foreach ($group_sites as $site) {
        $site_count++;
        $siteID = $site->siteid;
        $site_data = ftm_gt_process_site_data_to_array($siteID, $site->name, $has_php_code, $site_count);
        $sites_data[$siteID] = $site_data;
    }
    return $sites_data;
}

function ftm_gt_replace_sites_data($themeData, $groupId, $has_php_code, $params = [], $process_single_site = false, $type = 'group') {
    $pattern_begin = '[SITES-REPEATER]';
    $pattern_end = '[/SITES-REPEATER]';

    // Replaces the default values in the template with the values passed on the shortcode
    foreach ($params as $placeholder => $value) {
        $themeData = preg_replace('/\['.$placeholder.'\|([^\]]+)\]/', $value, $themeData);
    }
    // If placeholders with default are still remaining, replace them with the default value
    $themeData = preg_replace('/\[[0-9a-zA-Z_ -]+\|([^\]]+)\]/', '$1', $themeData);

    $sites_html_replacement =  strstr(strstr($themeData, $pattern_begin), $pattern_end, true) . $pattern_end;
    $sites_repeat_base_html = str_replace($pattern_begin,"", strstr(strstr($themeData, $pattern_begin), $pattern_end, true));
    $sites_repeat_result_html = "";

    $process_single_site = true;
    if (strlen($sites_repeat_base_html)) {
        $process_single_site = false;
    }

    if ('cta' === $type) {
        $sites_data = ftm_gt_process_cta_data_to_array($groupId, $has_php_code);
    } else {
        $sites_data = ftm_gt_process_group_data_to_array($groupId, $has_php_code);
    }
    if (count($sites_data) === 0)
        return '';
    if ($process_single_site) {
        $site_data = array_shift($sites_data);
        $site_data = array_merge($params, $site_data);
        foreach ($site_data as $field_name => $value) {
            $optionName = "[" . $field_name . "]";
            $themeData = str_replace($optionName, $value, $themeData);
        }
    } else {
        foreach ($sites_data as $site_id => $site_data) {
            $site_entry = $sites_repeat_base_html;
            $site_data = array_merge($params, $site_data);
            foreach ($site_data as $field_name => $value) {
                $optionName = "[" . $field_name . "]";
                $site_entry = str_replace($optionName, $value, $site_entry);
            }
            $sites_repeat_result_html .= $site_entry;
        }
        $themeData = str_replace($sites_html_replacement,$sites_repeat_result_html, $themeData);
    }

    $themeData = str_replace('\"','"',$themeData);
    return $themeData;
}

function ftm_gt_clean_empty_tags($script){
    $all_tags = ftm_geo_target_getCurrentFields();
    $matches = [];

    foreach ($all_tags as $tag){
        $found_common_strings = preg_match_all('['.$tag->fieldname.']', $script, $matches);

        if(false != $found_common_strings) {
            if ($found_common_strings > 0) {
                $option_field_name = "[" . $tag->fieldname . "]";
                $script = str_replace($option_field_name, "", $script);
            }
        }
    }


    return $script;
}

function ftm_gt_replace_title($content){

    $newTitle = $content;

    if(has_filter('wpml_current_language')){
        $my_current_lang = apply_filters( 'wpml_current_language', NULL );
        if($my_current_lang != 'en'){
            return $content;
        }
    }

    $codeReplace = "";
    $bettingSiteArr = ['/sports-betting/', '/football-betting/', '/esports-betting/', '/horse-racing/'];
    $casinoSiteArr = ['/online-casino/'];

    list($cc, $rc) = ftm_gt_getGeoCodes();

    if (!empty($rc) && $cc == "US"){
        $codeReplace = $rc;
    }else{
        if(!empty($cc) && $cc != "US"){
            $codeReplace = $cc;
        }
    }

    if(strposa($_SERVER["REQUEST_URI"], $bettingSiteArr)){
        $newTitle = $codeReplace . " Betting Site";
    }elseif(strposa($_SERVER["REQUEST_URI"], $casinoSiteArr)){
        $newTitle = $codeReplace . " Online Casino";
    }else{
        $newTitle = $codeReplace . " " . $content;
    }

    return $newTitle;

}

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
        if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
    }
    return false;
}

function ftm_geo_target_footer() {
    $is_auto_active = boolval(get_option( 'ftmgt_cta_active', 'false' ));
    $use_shortcode = get_option( 'ftmgt_cta_use_shortcode', 'auto-include' );
    if ($is_auto_active && $use_shortcode === 'auto-include') {
        echo ftm_cta_auto_shortcode([]);
    }
}
add_action( 'wp_footer', 'ftm_geo_target_footer' );

function base_dir() {
    return dirname(dirname(dirname(dirname(__DIR__))));
}

include_once ($ftm_geo_target_plugin_path . '/includes/plugin-service.php');
add_action( 'wp_ajax_check_group', 'check_group_by_name_handler' );
add_action( 'wp_ajax_nopriv_check_group', 'check_group_by_name_handler' );

