<?php
    // prevent direct file access
	if( !defined( 'ABSPATH' ) ) exit;
    
    // add popup to enqueue at footer
    function pixe_add_popup($popup_id){
        global $pixe_popup;
        if( empty($pixe_popup) ){
            $pixe_popup = array($popup_id);
        }else if( !in_array($popup_id, $pixe_popup) ){
            $pixe_popup[] = $popup_id;
        }
    }

    // basic rules
    function pixe_get_popup_data($popup_id, $template_settings){
        $data = array(
            'popup-id' => $popup_id
        );

        if( !empty($template_settings['trigger']) ){
            if( !empty($template_settings['trigger']['advance']) ){
                unset($template_settings['trigger']['advance']);
            }
            $data['trigger'] = $template_settings['trigger'];
        }
        if( !empty($template_settings['popup']['page-scroll']) ){
            $data['scroll'] = 1;
        }

        return $data;
    }

    // advance popup rules
    function pixe_check_popup_rules($popup_id, $template_settings){
        if( empty($template_settings['trigger']['advance']) ) return true;

        $display = true;
        $rules = $template_settings['trigger']['advance'];

        foreach( $rules as $rule ){
            if( empty($rule[0]) ) continue;

            switch($rule[0]){
                case 'arriving-from':
                    $pattern = empty($rule[1])? '': '|' . $rule[1] . '|';
                    $status = empty($rule[2])? 'show': $rule[2];
                    $match = false;
                    $referer = empty($_SERVER['HTTP_REFERER'])? '': sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER']));

                    if( empty($referer) ){
                        if( empty($pattern) ){
                            $match = true;
                        }
                    }else if( preg_match($pattern, $referer) ){
                        $match = true;
                    }   

                    if( $match && $status == 'hide' || !$match && $status == 'show' ){
                        $display &= false;
                    }
                    break;

                case 'hide-for':
                    $role = empty($rule[1])? '': $rule[1];
                    if( is_user_logged_in() && $role ){
                        $user = wp_get_current_user();
                        if( in_array($role, $user->roles) ){
                            $display &= false;
                        }
                    }
                    break;

                case 'os':
                    $status = empty($rule[1])? 'is': $rule[1];
                    $os = empty($rule[2])? '': $rule[2];

                    if( !empty($os) ){
                        $ua = empty($_SERVER['HTTP_USER_AGENT'])? '': sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']));
                        if( ($os == 'android' && preg_match('/android/i', $ua)) ||
                            ($os == 'ios' && preg_match('/iphone|ipad|ipod/i', $ua)) ||
                            ($os == 'macos' && preg_match('/macintosh|mac os x/i', $ua)) || 
                            ($os == 'window' && preg_match('/windows/i', $ua)) ){
                            if( $status == 'not' ) $display &= false; 
                        }else{
                            if( $status == 'is' ) $display &= false;
                        }
                    }
                    break;

                case 'browser':
                    $status = empty($rule[1])? 'is': $rule[1];
                    $browser = empty($rule[2])? '': $rule[2];

                    if( !empty($browser) ){
                        $ua = empty($_SERVER['HTTP_USER_AGENT'])? '': sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']));
                        if( ($browser == 'brave' && strpos($ua, 'Brave') !== false) ||
                            ($browser == 'edge' && strpos($ua, 'Edg') !== false) ||
                            ($browser == 'chrome' && strpos($ua, 'Chrome') !== false) ||
                            ($browser == 'firefox' && strpos($ua, 'Firefox') !== false) ||
                            ($browser == 'safari' && strpos($ua, 'Safari') !== false && strpos($ua, 'Chrome') === false) ){
                            if( $status == 'not' ) $display &= false; 
                        }else{
                            if( $status == 'is' ) $display &= false;
                        }
                    }
                    break;

                case 'last-visit':
                    $cookie_name = 'pixe-last-visit-' . $popup_id;
                    $status = empty($rule[1])? '': $rule[1]; // match, before, after
                    $date = empty($rule[2])? '': strtotime($rule[2]);
                    
                    if( !empty($_COOKIE[$cookie_name]) ){
                        $last_visit = intval(wp_unslash($_COOKIE[$cookie_name]));

                        if( ($status == 'match' && $date == $last_visit) ||
                            ($status == 'before' && $last_visit < $date ) ||
                            ($status == 'after' && $last_visit > $date ) ){
                            // match do nothing
                        }else{
                            $display &= false;
                        }
                    }

                    // update last visit cookie using javascript
                    $cookie_path = defined('COOKIEPATH')? COOKIEPATH : '/';
                    $cookie_domain = defined('COOKIE_DOMAIN')? COOKIE_DOMAIN : '';

                    $current_time = strtotime(gmdate('Y-m-d'));
                    $expire_date = $current_time + 31536000; // 1 year
                    $expire_date_js = gmdate('D, d M Y H:i:s T', $expire_date);
                    
                    $cookie_js = "{$cookie_name}={$current_time}; expires={$expire_date_js}; path={$cookie_path}; domain={$cookie_domain}";
                    wp_add_inline_script('pixe-inline', 'document.cookie = \'' . esc_js($cookie_js) . '\';');

                    break;

                case 'current-date':
                    $today = strtotime(current_time('Y-m-d'));
                    $status = empty($rule[1])? '': $rule[1]; // match, before, after
                    $date = empty($rule[2])? '': strtotime($rule[2]);

                    if( ($status == 'match' && $date == $today) ||
                        ($status == 'before' && $today < $date ) ||
                        ($status == 'after' && $today > $date ) ){
                        // match do nothing
                    }else{
                        $display &= false;
                    }
                    break;

                case 'cookie':
                    $name = empty($rule[1])? '': $rule[1];
                    $status = empty($rule[2])? '': $rule[2]; // match, contain, not-match, not-contain
                    $value = empty($rule[3])? '': $rule[3];
                    $cookie_val = empty($_COOKIE[$name])? '': sanitize_text_field(wp_unslash($_COOKIE[$name]));

                    $is_match = ($cookie_val == $value);
                    $is_contain = (strpos($cookie_val, $value) !== false);

                    if( $status == 'match' ){
                        if( !$is_match ) $display &= false;
                    }else if( $status == 'contain' ){
                        if( !$is_contain ) $display &= false;
                    }else if( $status == 'not-match' ){
                        if( $is_match ) $display &= false;
                    }else if( $status == 'not-contain' ){
                        if( $is_contain ) $display &= false;
                    }
                    break;
            }
        }

        return $display;
    }

    // enqueue popup
    function pixe_print_popup_close($template_settings){
        echo '<div class="pixe-close-popup" >';
        if( !empty($template_settings['close']['icon']) ){
            pixe_get_icon($template_settings['close']['icon'], array(), true);
        }else{
            pixe_icon_preset('close', array(), true);
        }
        echo '</div>';
    }
    function pixe_get_popup(){
        global $pixe_popup;

        if( !empty($pixe_popup) ){
            foreach( $pixe_popup as $popup_id ){
                $template = pixe_get_template($popup_id, 'popup');
                $template_content = empty($template->content)? '': json_decode($template->content, true);
                $template_settings = empty($template->settings)? '': json_decode($template->settings, true);

                $rules = pixe_check_popup_rules($popup_id, $template_settings);
                if( !$rules ) continue; 

                if( !empty($template_content) ){
                    
                    $close_position = empty($template_settings['close']['position'])? 'inside': $template_settings['close']['position'];

                    // translate content
                    pixe_translate_multilingual_strings('popup', $popup_id, $template_content);

                    $close_button = '';
                    if( empty($template_settings['close']['enable']) ){
                        $close_button  = '<div class="pixe-close-popup" >';
                        if( !empty($template_settings['close']['icon']) ){
                            $close_button .= pixe_get_icon($template_settings['close']['icon']);
                        }else{
                            $close_button .= pixe_icon_preset('close');
                        }
                        $close_button .= '</div>';
                    }

                    
                    pixe_print_div_open(array(
                        'class' => 'pixe-popup-lb pixe-popup-wrap',
                        'data-atts' => pixe_get_popup_data($popup_id, $template_settings)
                    ));
                    if( $close_position == 'outside' ) pixe_print_popup_close($template_settings);
                    
                    echo '<div class="pixe-popup-bg" ></div>';
                    echo '<div class="pixe-popup-container" >';
                    echo '<div class="pixe-editor pixe-box-sizing" >';
                    if( $close_position == 'inside' ) pixe_print_popup_close($template_settings);
                    pixe_get_builder_content($template_content, false, true);
                    echo '</div>'; // pixe editor
                    echo '</div>'; // popup container
                    echo '</div>'; // pixe-popup-lb
                }
            }
        }
    }

    // popup script
    function pixe_popup_script(){
?>
$(document).ready(function(){
    var popupLb = $(document.body).children('.pixe-popup-lb');

    popupLb.each(function(){
        var popup = $(this);
        var popupId = $(this).attr('data-popup-id');
        var trigger = popup.data('trigger')? popup.data('trigger'): {};

        // show time hide day variables
        var sthd = false;
        var shownCount, lastShown;
        var shownCountKey = 'pixe-sthd-count' + popupId;
        var lastShownKey = 'pixe-sthd-last' + popupId;
        var currentTime = Date.now();

        function openTriggerPopup(popup, trigger){

            // do not display on specific device
            if( trigger && trigger['ignore-devices'] && trigger['ignore-devices'].indexOf(pixeDisplay) >= 0 ){
                return;
            }

            // display popup
            if( popup.length ){
                var scroll = popup.attr('data-scroll');
                popup.fadeIn(200).css({ display: 'flex' });

                if( !scroll ){
                    $(document.body).css('overflow', 'hidden');
                }
            }

            // increase show time hide day
            if( sthd ){
                shownCount++;
                localStorage.setItem(shownCountKey, shownCount);
                localStorage.setItem(lastShownKey, currentTime);
            }
        }
        
        // show time hide day
        if( trigger['show-time-hide-day'] ){
            sthd = true;

            var showTime = trigger['show-time-hide-day'][0]? parseInt(trigger['show-time-hide-day'][0]): 1;
            var hideDay = trigger['show-time-hide-day'][1]? parseInt(trigger['show-time-hide-day'][0]): 0;
                hideDay = hideDay * 24 * 60 * 60 * 1000;

            shownCount = parseInt(localStorage.getItem(shownCountKey) || '0');
            lastShown = parseInt(localStorage.getItem(lastShownKey) || '0');

            if( shownCount >= showTime ){
                if( currentTime - lastShown >= hideDay ){
                    shownCount = 0;
                    localStorage.setItem(shownCountKey, shownCount);
                    localStorage.setItem(lastShownKey, currentTime);
                }else{
                    return;
                }
            }
        }

        // on page load
        if( trigger['on-page-load'] ){
            var delay = parseFloat(trigger['on-page-load'][0]) * 1000;
            setTimeout(function(){
                openTriggerPopup(popup, trigger);
            }, delay);
        }

        // on scroll
        if( trigger['on-scroll'] ){
            var lastScroll = window.scrollY;

            $(window).on('scroll', function(e) {
                var scrollTop = window.scrollY;
                var docHeight = $(document).height();

                var triggerDirection = trigger['on-scroll'][0]? trigger['on-scroll'][0]: 'down';
                var triggerPoint = trigger['on-scroll'][1]? parseFloat(trigger['on-scroll'][1]): 0;

                var scrollDirection = lastScroll <= scrollTop? 'down': 'up'; 
                var scrollPercent = (scrollTop + (window.innerHeight / 2)) * 100 / docHeight;

                if( triggerDirection == scrollDirection && scrollPercent >= triggerPoint ){
                    openTriggerPopup(popup, trigger);
                    $(this).off(e);
                }

                lastScroll = scrollTop;
            });
        }

        // on scroll to
        if( trigger['on-scroll-to'] && trigger['on-scroll-to'][0] ){
            $('#' + trigger['on-scroll-to'][0]).each(function(){
                var targetItem = $(this);
                $(window).on('scroll', function(e){
                    var itemPos = targetItem.offset().top;
                    var scrollPos = window.scrollY + window.innerHeight;
                    if( scrollPos > itemPos ){
                        openTriggerPopup(popup, trigger);
                        $(this).off(e);
                    }
                });
            });
        }

        // on click
        if( trigger['on-click'] ){
            var clickAmount = trigger['on-click'][0]? parseInt(trigger['on-click'][0]): 1;
            var clickCount = 0;
            $(document.body).on('click', function(e){
                clickCount++;
                if( clickCount >= clickAmount ){
                    openTriggerPopup(popup, trigger);
                    $(this).off(e);
                }
            });
        }

        // inactivity
        if( trigger['after-inactivity'] && trigger['after-inactivity'][0] ){
            var duration = parseFloat(trigger['after-inactivity'][0]) * 1000;

            if( duration ){
                var inactivityTimeout;

                function inactivityPopup(){
                    clearTimeout(inactivityTimeout);
                    inactivityTimeout = setTimeout(function(){
                        openTriggerPopup(popup, trigger);
                    }, duration);
                }
                $(document).on('mousemove keydown scroll click', inactivityPopup);
                inactivityPopup();
            }
        }

        // page views
        if( trigger['after-page-view'] && trigger['after-page-view'][0] ){
            var pageViewAmount = parseInt(trigger['after-page-view'][0]);

            if( pageViewAmount > 0 ){
                var pageViews = parseInt(localStorage.getItem('pixe-page-views') || '0') + 1;
                localStorage.setItem('pixe-page-views', pageViews);
                if( pageViews > pageViewAmount ){
                    openTriggerPopup(popup, trigger);
                }
            }
        }

        // session amount
        if( trigger['after-session'] && trigger['after-session'][0] ){
            var sessionAmount = parseInt(trigger['after-session'][0]);
            
            if( sessionAmount > 0 ){
                if( !sessionStorage.getItem('pixe-session-count') ){
                    sessionStorage.setItem('pixe-session-count', 'true');

                    var sessions = parseInt(localStorage.getItem('pixe-session-count') || '0') + 1;
                    localStorage.setItem('pixe-session-count', sessions);
                    if( sessions > sessionAmount ){
                        openTriggerPopup(popup, trigger);
                    }
                }
            }
        }

        if( trigger['on-exit-intent'] ){
            $(document.body).on('mouseleave', function(e){
                openTriggerPopup(popup, trigger);
                $(this).off(e);
            });
        }
        
    });
    
    // display popup
    function openPopup(popup){
        if( popup.length ){
            var scroll = popup.attr('data-scroll');
            popup.fadeIn(200).css({ display: 'flex' });

            if( !scroll ){
                $(document.body).css('overflow', 'hidden');
            }
        }
    }
    
    let touched = false;

    // open from button
    $(document).on('click touchstart', '.pixe-popup-button', function(e){
        if( e.type == 'touchstart' ){
            touched = true;
        }else{
            if( touched ){
                touched = false;
                return false;
            }                       
        }

        var popupId = $(this).attr('data-popup-id');
        var targetPopup = popupLb.filter('[data-popup-id="' + popupId + '"]');
        openPopup(targetPopup);
        return false;
    });

    // close event
    popupLb.on('click touchstart', '.pixe-close-popup, .pixe-popup-bg', function(e){
        if( e.type == 'touchstart' ){
            touched = true;
        }else{
            if( touched ){
                touched = false;
                return false;
            }                       
        }

        var targetPopup = $(this).closest('.pixe-popup-lb');
        targetPopup.fadeOut(200);  
        $(document.body).css('overflow', '').trigger('pixeclosepopup');
    });
    
});
<?php
    }
    Pixe_Dependency::get()->register_script('popup', 'pixe_popup_script');