<?php
/** @var string $current_country */
/** @var string $current_region */
/** @var array $countries */
/** @var array $regions */
/** @var string $path */

?>

(function(){
    //GEOIP VALUES
    const country = "<?php echo $current_country ?>";
    const region  = "<?php echo $current_region ?>";
    const blockedCountries = [<?php echo implode(',', array_map(function($element){return "'$element'";}, $countries)) ?>];
    const blockedRegions = [<?php echo implode(',', array_map(function($element){return "'$element'";}, $regions)) ?>];
    const ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";

    function validateClick(){
        let targetElement = event.target || event.srcElement;

        //if the clicked element is not an anchor, bail
        if (!targetElement.matches('a')) return;

        //check if the a element has the href attribute
        if (targetElement.hasAttribute('href')){

            //lets capture the value of href attribute
            let hrefAttr = targetElement.getAttribute("href");

            //verify this is an affiliate link
            let isAffLink = /<?php echo addcslashes ($path, '/') ?>/.test(hrefAttr);

            //don't redirect the user to the site if is not allowed
            if(((blockedRegions.includes(region+'_'+country)) && isAffLink == true) || ((blockedCountries.includes(country)) && isAffLink == true) ){
                event.preventDefault();
                trackLink(hrefAttr, targetElement.innerText);
                return false;
            }else{
                return true;
            }

        }
    }

    function trackLink(destination, link_text) {
        let data = {
            'action': 'ftm_geo_track',
            'destination': destination,
            'link_text': link_text
        };
        jQuery.post(ajax_url, data, function(data) {
        });
    }

}())
