<?php

if ( ! defined( 'TM_POPUP_SLUG' ) ) {
	define( 'TM_POPUP_POST_TYPE', 'tm_popup' );
}

require_once( trailingslashit( dirname( __FILE__ ) ) . 'includes/CMB2_Type_Popup_Display.php' );

class ThemeMove_Popup {

	function __construct() {
		$this->tm_popup_hooks();
	}

	function tm_popup_hooks() {

		add_action( 'init', array( $this, 'tm_popup_register_post_type' ) );
		add_action( 'wp_head', array( $this, 'tm_popup_generate_vc_custom_css' ), 999 );
		add_action( 'wp_head', array( $this, 'tm_popup_frontend_scripts' ), 999 );
		add_action( 'admin_bar_menu', array( $this, 'tm_popup_remove_wp_bar_view' ), 999 );
		add_action( 'admin_footer', array( $this, 'tm_popup_remove_vc_frontend_editor' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'tm_popup_admin_scripts' ) );
		add_action( 'wp_footer', array( $this, 'tm_popup_render' ) );

		add_action( 'save_post', array( $this, 'tm_popup_save' ), 10, 3 );

		add_filter( 'post_row_actions', array( $this, 'tm_popup_remove_row_actions' ), 999, 2 );
		add_filter( 'cmb2_meta_boxes', array( $this, 'tm_popup_metabox' ) );
		add_filter( 'cmb2_select_attributes', array( $this, 'tm_popup_cmb_display_animation_options' ), 10, 4 );
		add_filter( 'cmb2_select_attributes', array( $this, 'tm_popup_cmb_closing_animation_options' ), 10, 4 );

	}

	function tm_popup_remove_vc_frontend_editor() {
		?>
		<style type="text/css">
			.post-type-tm_popup .wpb_switch-to-front-composer {
				display: none;
			}
		</style>
		<script type="text/javascript">
			jQuery(document).ready(function ($) {
				setTimeout(function () {
					$('.post-type-tm_popup .wpb_switch-to-front-composer').remove();
					$('.post-type-tm_popup .wpb_switch-to-composer').next('.vc_spacer').remove();
				}, 50);
			});
		</script>
		<?php
	}

	function tm_popup_register_post_type() {

		if ( current_theme_supports( 'tm-popup' ) ) {

			$labels = array(
				'name'               => _x( 'Popups', 'Post Type General Name', 'tm-core' ),
				'singular_name'      => _x( 'Popup', 'Post Type Singular Name', 'tm-core' ),
				'menu_name'          => __( 'Popup', 'tm-core' ),
				'name_admin_bar'     => __( 'Popup', 'tm-core' ),
				'parent_item_colon'  => __( 'Parent Popup:', 'tm-core' ),
				'all_items'          => __( 'All Popups', 'tm-core' ),
				'add_new_item'       => __( 'Add New Popup', 'tm-core' ),
				'add_new'            => __( 'Add New', 'tm-core' ),
				'new_item'           => __( 'New Popup', 'tm-core' ),
				'edit_item'          => __( 'Edit Popup', 'tm-core' ),
				'update_item'        => __( 'Update Popup', 'tm-core' ),
				'view_item'          => __( 'View Popup', 'tm-core' ),
				'search_items'       => __( 'Search Popup', 'tm-core' ),
				'not_found'          => __( 'Not found', 'tm-core' ),
				'not_found_in_trash' => __( 'Not found in Trash', 'tm-core' ),
			);
			$args   = array(
				'label'               => __( TM_POPUP_POST_TYPE, 'tm-core' ),
				'description'         => __( 'ThemeMove Popup', 'tm-core' ),
				'labels'              => $labels,
				'supports'            => array( 'title', 'editor', ),
				'hierarchical'        => false,
				'public'              => true,
				'show_ui'             => true,
				'show_in_menu'        => true,
				'menu_position'       => 20,
				'menu_icon'           => 'dashicons-welcome-widgets-menus',
				'show_in_admin_bar'   => true,
				'show_in_nav_menus'   => false,
				'can_export'          => true,
				'has_archive'         => false,
				'exclude_from_search' => true,
				'publicly_queryable'  => false,
				'rewrite'             => false,
				'capability_type'     => 'page'
			);
			register_post_type( TM_POPUP_POST_TYPE, $args );

		}
	}

	function tm_popup_generate_vc_custom_css() {
		$popups = get_posts(
			array(
				'post_type'   => TM_POPUP_POST_TYPE,
				'numberposts' => - 1,
				'post_status' => 'publish'
			)
		);

		if ( ! empty( $popups ) ) {
			$popup_custom_css_array      = array();
			$shortcodes_custom_css_array = array();

			foreach ( $popups as $popup ) {
				$popup_custom_css = get_post_meta( $popup->ID, '_wpb_post_custom_css', true );

				if ( ! empty( $popup_custom_css ) ) {
					$popup_custom_css_array[] = $popup_custom_css;
				}

				$shortcodes_custom_css = get_post_meta( $popup->ID, '_wpb_shortcodes_custom_css', true );
				if ( ! empty( $shortcodes_custom_css ) ) {
					$shortcodes_custom_css_array[] = $shortcodes_custom_css;
				}
			}

			if ( ! empty( $popup_custom_css_array ) ) {
				echo '<style type="text/css" data-type="vc_custom-css">';
				echo implode( '', $popup_custom_css_array );
				echo '</style>';
			}

			if ( ! empty( $shortcodes_custom_css_array ) ) {
				echo '<style type="text/css" data-type="vc_shortcodes-custom-css">';
				echo implode( '', $shortcodes_custom_css_array );
				echo '</style>';
			}

		}
	}

	function tm_popup_remove_wp_bar_view( $wp_admin_bar ) {
		if ( get_post_type() == TM_POPUP_POST_TYPE ) {
			$wp_admin_bar->remove_node( 'view' );
		}
	}

	function tm_popup_remove_row_actions( $actions ) {
		if ( get_post_type() == TM_POPUP_POST_TYPE ) {
			unset ( $actions['inline hide-if-no-js'] );
			unset ( $actions['view'] );
			unset ( $actions['edit_vc'] );
		}

		return $actions;
	}

	function tm_popup_admin_scripts() {
		wp_enqueue_style( 'metabox', plugins_url( 'assets/css/metabox.css', __FILE__ ) );
		wp_enqueue_script( 'metabox-script', plugins_url( 'assets/js/metabox.js', __FILE__ ) );
	}

	function tm_popup_frontend_scripts() {
		wp_enqueue_style( 'magnific-popup', plugins_url( 'assets/css/magnific-popup.css', __FILE__ ) );
		wp_enqueue_style( 'animate', plugins_url( 'assets/css/animate.css', __FILE__ ) );
		wp_enqueue_style( 'tm-popup', plugins_url( 'assets/css/popup.css', __FILE__ ) );

		wp_enqueue_script( 'magnific-script', plugins_url( 'assets/js/jquery.magnific-popup.min.js', __FILE__ ) );
		wp_enqueue_script( 'waypoints', plugins_url( 'assets/js/jquery.waypoints.min.js', __FILE__ ) );
		wp_enqueue_script( 'js-cookie', plugins_url( 'assets/js/js.cookie.js', __FILE__ ) );
	}

	function tm_popup_metabox() {

		$prefix = 'tm_popup_';

		$fields = array(

			// ========== Active ==========
			array(
				'name' => esc_html__( 'Active', 'tm-core' ),
				'desc' => esc_html__( 'Check this box to active the popup', 'tm-core' ),
				'id'   => $prefix . 'active',
				'type' => 'checkbox',
			),

			// ========== Appearance ==========
			array(
				'name' => esc_html__( 'Appearance', 'tm-core' ),
				'type' => 'title',
				'id'   => $prefix . 'appearance'
			),
			array(
				'name'    => esc_html__( 'Max Width', 'tm-core' ),
				'id'      => $prefix . 'max_width',
				'desc'    => esc_html__( 'Enter the max width of your popup. The height of your popup will be calculated automatically.', 'tm-core' ),
				'type'    => 'number',
				'default' => 900,
				'options' => array(
					'min'    => 300,
					'max'    => 1700,
					'suffix' => 'px'
				)
			),
			array(
				'name' => esc_html__( 'Display Animation', 'tm-core' ),
				'id'   => $prefix . 'display_animation',
				'type' => 'select',
				'desc' => sprintf(
					wp_kses(
						__( 'See Animate.css demos <a href="%s" target="_blank">here</a>.', 'tm-core' ),
						array(
							'a' => array(
								'href'   => array(),
								'target' => array(),
							),
						)
					), esc_url( 'https://daneden.github.io/animate.css/' )
				),
			),
			array(
				'name' => esc_html__( 'Closing Animation', 'tm-core' ),
				'id'   => $prefix . 'closing_animation',
				'type' => 'select',
				'desc' => sprintf(
					wp_kses(
						__( 'See Animate.css demos <a href="%s" target="_blank">here</a>.', 'tm-core' ),
						array(
							'a' => array(
								'href'   => array(),
								'target' => array(),
							),
						)
					), esc_url( 'https://daneden.github.io/animate.css/' )
				),
			),

			// ========== Displaying Options ==========
			array(
				'name' => esc_html__( 'Displaying Options', 'tm-core' ),
				'type' => 'title',
				'id'   => $prefix . 'display_title'
			),
			array(
				'name'    => esc_html__( 'Show in', 'tm-core' ),
				'id'      => $prefix . 'show_post_type',
				'type'    => 'select',
				'options' => $this->tm_popup_cmb_post_type_options()
			),
			array(
				'name'    => esc_html__( 'Show on selected pages and selected posts:', 'tm-core' ),
				'id'      => $prefix . 'posts',
				'type'    => 'tm_multiselect',
				'options' => $this->tm_popup_cmb_posts_options( array( 'post_type' => array( 'post', 'page' ) ) ),
			),
			array(
				'name' => '',
				'desc' => esc_html__( 'Exclude Archive pages', 'tm-core' ),
				'id'   => $prefix . 'exclude_archive_page',
				'type' => 'checkbox',
			),
			array(
				'name' => esc_html__( 'When to show the popup:', 'tm-core' ),
				'id'   => $prefix . 'display',
				'type' => 'popup_display',
			),
			array(
				'name'    => esc_html__( 'Shows the PopUp if the user is', 'tm-core' ),
				'id'      => $prefix . 'display_role',
				'type'    => 'select',
				'options' => array(
					''         => esc_html__( 'Everyone', 'tm-core' ),
					'login'    => esc_html__( 'Logged in to your site', 'tm-core' ),
					'no_login' => esc_html__( 'Not logged in to your site', 'tm-core' ),
				),
			),
			array(
				'name'    => esc_html__( 'Display Mode', 'tm-core' ),
				'id'      => $prefix . 'display_mode',
				'type'    => 'select',
				'options' => array(
					''            => esc_html__( 'All devices', 'tm-core' ),
					'only_mobile' => esc_html__( 'Only on mobile devices', 'tm-core' ),
					'not_mobile'  => esc_html__( 'Only on a normal computer or laptop (i.e. not a Phone or Tablet).', 'tm-core' ),
				),
			),

			// ========== "Never see this messeage again" settings  ==========
			array(
				'name' => esc_html__( '"Never see this messeage again" settings', 'tm-core' ),
				'type' => 'title',
				'id'   => $prefix . 'hide_title'
			),
			array(
				'name' => '',
				'desc' => esc_html__( 'Add "Never see this message again" checkbox', 'tm-core' ),
				'id'   => $prefix . 'can_hide',
				'type' => 'checkbox',
			),
			array(
				'name' => '',
				'desc' => esc_html__( 'Close button acts as "Never see this message again"', 'tm-core' ),
				'id'   => $prefix . 'close_hide',
				'type' => 'checkbox',
			),
			array(
				'name'    => '',
				'desc'    => esc_html__( 'Upon expiry, user will see this popup again', 'tm-core' ),
				'id'      => $prefix . 'expire',
				'type'    => 'number',
				'default' => 365,
				'options' => array(
					'min'    => 0,
					'prefix' => esc_html__( 'Expiry time', 'tm-core' ),
					'suffix' => 'days'
				),
			),
		);

		$meta_boxes['tm_popup_metabox'] = array(
			'id'           => 'tm_popup_metabox',
			'title'        => esc_html__( 'Popup Settings', 'tm-core' ),
			'object_types' => array( TM_POPUP_POST_TYPE ),
			'context'      => 'normal',
			'priority'     => 'high',
			'fields'       => $fields,
		);

		return $meta_boxes;
	}

	function tm_popup_cmb_post_type_options() {
		$post_types = array(
			'all'  => class_exists( 'WooCommerce' ) ? esc_html__( 'All posts, pages and products', 'tm-core' ) : ( esc_html__( 'All posts and pages', 'tm-core' ) ),
			'post' => esc_html__( 'All posts', 'tm-core' ),
			'page' => esc_html__( 'All pages', 'tm-core' ),
		);

		if ( class_exists( 'WooCommerce' ) ) {
			$post_types['product'] = esc_html__( 'All products', 'tm-core' );
		}
		$post_types['custom'] = esc_html__( 'Custom', 'tm-core' );

		return $post_types;
	}

	function tm_popup_cmb_display_animation_options( $args, $defaults, $field_object, $field_types_object ) {

		// Only do this for the 'display_animation' field
		if ( 'tm_popup_display_animation' != $field_types_object->_id() ) {
			return $args;
		}

		$option_array = array(
			esc_html__( 'Attention Seekers', 'tm-core' )  => array(
				'bounce'     => 'bounce',
				'flash'      => 'flash',
				'pulse'      => 'pulse',
				'rubberBand' => 'rubberBand',
				'shake'      => 'shake',
				'swing'      => 'swing',
				'tada'       => 'tada',
				'wobble'     => 'wobble',
				'jello'      => 'jello'
			),
			esc_html__( 'Bouncing Entrances', 'tm-core' ) => array(
				'bounceIn'      => 'bounceIn',
				'bounceInDown'  => 'bounceInDown',
				'bounceInLeft'  => 'bounceInLeft',
				'bounceInRight' => 'bounceInRight',
				'bounceInUp'    => 'bounceInUp'
			),
			esc_html__( 'Fading Entrances', 'tm-core' )   => array(
				'fadeIn'         => 'fadeIn',
				'fadeInDown'     => 'fadeInDown',
				'fadeInDownBig'  => 'fadeInDownBig',
				'fadeInLeft'     => 'fadeInLeft',
				'fadeInLeftBig'  => 'fadeInLeftBig',
				'fadeInRight'    => 'fadeInRight',
				'fadeInRightBig' => 'fadeInRightBig',
				'fadeInUp'       => 'fadeInUp',
				'fadeInUpBig'    => 'fadeInUpBig'
			),
			esc_html__( 'Flippers', 'tm-core' )           => array(
				'flip'    => 'flip',
				'flipInX' => 'flipInX',
				'flipInY' => 'flipInY'
			),
			esc_html__( 'Lightspeed', 'tm-core' )         => array(
				'lightSpeedIn' => 'lightSpeedIn'
			),
			esc_html__( 'Rotating Entrances', 'tm-core' ) => array(
				'rotateIn'          => 'rotateIn',
				'rotateInDownLeft'  => 'rotateInDownLeft',
				'rotateInDownRight' => 'rotateInDownRight',
				'rotateInUpLeft'    => 'rotateInUpLeft',
				'rotateInUpRight'   => 'rotateInUpRight'
			),
			esc_html__( 'Sliding Entrances', 'tm-core' )  => array(
				'slideInUp'    => 'slideInUp',
				'slideInDown'  => 'slideInDown',
				'slideInLeft'  => 'slideInLeft',
				'slideInRight' => 'slideInRight'
			),
			esc_html__( 'Zoom Entrances', 'tm-core' )     => array(
				'zoomIn'      => 'zoomIn',
				'zoomInDown'  => 'zoomInDown',
				'zoomInLeft'  => 'zoomInLeft',
				'zoomInRight' => 'zoomInRight',
				'zoomInUp'    => 'zoomInUp',
			),
			esc_html__( 'Specials', 'tm-core' )           => array(
				'rollIn' => 'rollIn'
			)
		);

		$saved_value = $field_object->escaped_value();
		$value       = $saved_value ? $saved_value : $field_object->args( 'default' );

		$options_string = '';
		$options_string .= $field_types_object->select_option(
			array(
				'label'   => __( 'No animation' ),
				'value'   => '',
				'checked' => ! $value
			)
		);

		foreach ( $option_array as $group_label => $group ) {

			$options_string .= '<optgroup label="' . $group_label . '">';

			foreach ( $group as $key => $label ) {
				$options_string .= $field_types_object->select_option(
					array(
						'label'   => $label,
						'value'   => $key,
						'checked' => $value == $key
					)
				);
			}
			$options_string .= '</optgroup>';
		}

		// Ok, replace the options value
		$defaults['options'] = $options_string;

		return $defaults;
	}

	function tm_popup_cmb_closing_animation_options( $args, $defaults, $field_object, $field_types_object ) {

		// Only do this for the 'display_animation' field
		if ( 'tm_popup_closing_animation' != $field_types_object->_id() ) {
			return $args;
		}

		$option_array = array(
			esc_html__( 'Bouncing Exits', 'tm-core' ) => array(
				'bounceOut'      => 'bounceOut',
				'bounceOutDown'  => 'bounceOutDown',
				'bounceOutLeft'  => 'bounceOutLeft',
				'bounceOutRight' => 'bounceOutRight',
				'bounceOutUp'    => 'bounceOutUp'
			),
			esc_html__( 'Fading Exits', 'tm-core' )   => array(
				'fadeOut'         => 'fadeOut',
				'fadeOutDown'     => 'fadeOutDown',
				'fadeOutDownBig'  => 'fadeOutDownBig',
				'fadeOutLeft'     => 'fadeOutLeft',
				'fadeOutLeftBig'  => 'fadeOutLeftBig',
				'fadeOutRight'    => 'fadeOutRight',
				'fadeOutRightBig' => 'fadeOutRightBig',
				'fadeOutUp'       => 'fadeOutUp',
				'fadeOutUpBig'    => 'fadeOutUpBig'
			),
			esc_html__( 'Flippers', 'tm-core' )       => array(
				'flipOutX' => 'flipOutX',
				'flipOutY' => 'flipOutY'
			),
			esc_html__( 'Lightspeed', 'tm-core' )     => array(
				'lightSpeedOut' => 'lightSpeedOut'
			),
			esc_html__( 'Rotating Exits', 'tm-core' ) => array(
				'rotateOut'          => 'rotateOut',
				'rotateOutDownLeft'  => 'rotateOutDownLeft',
				'rotateOutDownRight' => 'rotateOutDownRight',
				'rotateOutUpLeft'    => 'rotateOutUpLeft',
				'rotateOutUpRight'   => 'rotateOutUpRight'
			),
			esc_html__( 'Sliding Exits', 'tm-core' )  => array(
				'slideOutUp'    => 'slideOutUp',
				'slideOutDown'  => 'slideOutDown',
				'slideOutLeft'  => 'slideOutLeft',
				'slideOutRight' => 'slideOutRight'
			),
			esc_html__( 'Zoom Exits', 'tm-core' )     => array(
				'zoomOut'      => 'zoomOut',
				'zoomOutDown'  => 'zoomOutDown',
				'zoomOutLeft'  => 'zoomOutLeft',
				'zoomOutRight' => 'zoomOutRight',
				'zoomOutUp'    => 'zoomOutUp',
			),
			esc_html__( 'Specials', 'tm-core' )       => array(
				'hinge'   => 'hinge',
				'rollOut' => 'rollOut'
			)
		);

		$saved_value = $field_object->escaped_value();
		$value       = $saved_value ? $saved_value : $field_object->args( 'default' );

		$options_string = '';
		$options_string .= $field_types_object->select_option(
			array(
				'label'   => __( 'No animation' ),
				'value'   => '',
				'checked' => ! $value
			)
		);

		foreach ( $option_array as $group_label => $group ) {

			$options_string .= '<optgroup label="' . $group_label . '">';

			foreach ( $group as $key => $label ) {
				$options_string .= $field_types_object->select_option(
					array(
						'label'   => $label,
						'value'   => $key,
						'checked' => $value == $key
					)
				);
			}
			$options_string .= '</optgroup>';
		}

		// Ok, replace the options value
		$defaults['options'] = $options_string;

		return $defaults;
	}

	/**
	 * Get a list of posts
	 *
	 * Generic function to return an array of posts formatted for CMB2. Simply pass
	 * in your WP_Query arguments and get back a beautifully formatted CMB2 options
	 * array.
	 *
	 * @param array $query_args WP_Query arguments
	 *
	 * @return array CMB2 options array
	 */
	function tm_popup_cmb_posts_options( $args = array() ) {

		$defaults = array(
			'posts_per_page' => - 1
		);

		if ( class_exists( 'WooCommerce' ) ) {
			array_push( $args['post_type'], 'product' );
		}

		$query = new WP_Query( array_replace_recursive( $defaults, $args ) );

		$posts = $query->get_posts();

		$post_array = array();

		if ( ! empty( $posts ) ) {
			foreach ( $posts as $post ) {
				$post_array[ $post->ID ] = $post->post_title;
			}
		}

		return $post_array;
	}

	/**
	 *
	 * Get popup's settings
	 *
	 * @param $post_id
	 *
	 * @return array
	 */
	function tm_popup_settings( $post_id ) {
		$settings = array();

		$settings['active']               = get_post_meta( $post_id, 'tm_popup_active', true );
		$settings['max_width']            = get_post_meta( $post_id, 'tm_popup_max_width', true );
		$settings['display_animation']    = get_post_meta( $post_id, 'tm_popup_display_animation', true );
		$settings['closing_animation']    = get_post_meta( $post_id, 'tm_popup_closing_animation', true );
		$settings['show_post_type']       = get_post_meta( $post_id, 'tm_popup_show_post_type', true );
		$settings['posts']                = get_post_meta( $post_id, 'tm_popup_posts', true );
		$settings['exclude_archive_page'] = get_post_meta( $post_id, 'tm_popup_exclude_archive_page', true );
		$settings['display']              = get_post_meta( $post_id, 'tm_popup_display', true );
		$settings['display_role']         = get_post_meta( $post_id, 'tm_popup_display_role', true );
		$settings['display_mode']         = get_post_meta( $post_id, 'tm_popup_display_mode', true );
		$settings['can_hide']             = get_post_meta( $post_id, 'tm_popup_can_hide', true );
		$settings['close_hide']           = get_post_meta( $post_id, 'tm_popup_close_hide', true );
		$settings['expire']               = get_post_meta( $post_id, 'tm_popup_expire', true );
		$settings['exclude_posts']        = get_post_meta( $post_id, 'tm_popup_exclude_posts', true );

		return $settings;
	}

	function tm_popup_render() {

		$popups = get_posts(
			array(
				'post_type'   => array( 'tm_popup' ),
				'numberposts' => - 1,
				'post_status' => 'publish'
			)
		);

		foreach ( $popups as $popup ) {

			$popup_id = $popup->ID;
			$settings = $this->tm_popup_settings( $popup_id );

			if ( $settings['active']
			     && $this->tm_popup_check_valid_page( $settings )
			     && $this->tm_popup_check_valid_user( $settings['display_role'] )
			     && $this->tm_popup_check_valid_display_mode( $settings['display_mode'] )
			) {
				include( trailingslashit( dirname( __FILE__ ) ) . 'template.php' );

				return;
			}

		}
	}

	function tm_popup_check_valid_page( $settings ) {

		global $post;

		$valid = false;

		if ( 'all' == $settings['show_post_type'] && ! in_array( $post->ID, $settings['exclude_posts'] ) ) {
			$valid = true;
		} elseif ( 'custom' == $settings['show_post_type'] ) {
			if ( in_array( $post->ID, $settings['posts'] ) && ! is_archive() ) {
				$valid = true;
			}

			if ( function_exists( 'is_shop' ) ) {
				if ( is_shop() ) {
					$valid = true;
				}
			}
		} elseif ( 'page' == $settings['show_post_type'] || 'post' == $settings['show_post_type'] || 'product' == $settings['show_post_type'] ) {
			if ( $settings['show_post_type'] == $post->post_type && ! in_array( $post->ID, $settings['exclude_posts'] ) ) {
				if ( is_archive() && $settings['exclude_archive_page'] ) {
					$valid = false;
				} else {
					$valid = true;
				}
			}
		}

		return $valid;
	}

	function tm_popup_check_valid_user( $display_role ) {

		$valid = false;

		if ( '' == $display_role ) {
			$valid = true;
		} elseif ( 'login' == $display_role && is_user_logged_in() ) {
			$valid = true;
		} elseif ( 'no_login' == $display_role && ! is_user_logged_in() ) {
			$valid = true;
		}

		return $valid;
	}

	function tm_popup_check_valid_display_mode( $display_mode ) {

		$valid = false;

		if ( function_exists( 'is_mobile' ) && function_exists( 'is_tablet' ) ) {
			if ( '' == $display_mode ) {
				$valid = true;
			} elseif ( ( is_mobile() || is_tablet() ) && 'only_mobile' == $display_mode ) {
				$valid = true;
			} elseif ( ! is_mobile() && ! is_tablet() && 'not_mobile' == $display_mode ) {
				$valid = true;
			}
		}

		return $valid;
	}

	function tm_popup_save( $popup_id, $post, $update ) {

		if ( TM_POPUP_POST_TYPE != $post->post_type ) {
			return;
		}

		if ( wp_is_post_revision( $popup_id ) || wp_is_post_autosave( $popup_id ) ) {
			return;
		}

		$exclude_posts = array();

		$popups = get_posts(
			array(
				'post_type'   => array( 'tm_popup' ),
				'numberposts' => - 1,
				'post_status' => 'publish'
			)
		);

		if ( ! empty( $popups ) ) {
			foreach ( $popups as $popup ) {

				$post_type = get_post_meta( $popup->ID, 'tm_popup_show_post_type', true );

				if ( 'custom' == $post_type ) {
					$posts = get_post_meta( $popup->ID, 'tm_popup_posts', true );

					if ( is_array( $posts ) ) {
						$exclude_posts = array_merge( $exclude_posts, $posts );
					}
				}
			}

			foreach ( $popups as $popup ) {

				$post_type = get_post_meta( $popup->ID, 'tm_popup_show_post_type', true );

				if ( $popup_id == $popup->ID && isset( $_POST['tm_popup_show_post_type'] ) ) {
					$post_type = $_POST['tm_popup_show_post_type'];
				}

				if ( 'all' == $post_type ) {
					update_post_meta( $popup->ID, 'tm_popup_exclude_posts', $exclude_posts );
				} elseif ( 'page' == $post_type || 'post' == $post_type || 'product' == $post_type ) {
					if ( 'page' == $post_type ) {
						$posts = $this->tm_popup_get_ids_by_post_type( array( 'post', 'product' ) );
					}

					if ( 'post' == $post_type ) {
						$posts = $this->tm_popup_get_ids_by_post_type( array( 'page', 'product' ) );
					}

					if ( 'product' == $post_type ) {
						$posts = $this->tm_popup_get_ids_by_post_type( array( 'page', 'post' ) );
					}

					$posts = array_merge( $exclude_posts, $posts );
					update_post_meta( $popup->ID, 'tm_popup_exclude_posts', $posts );
				}
			}
		}
	}

	function tm_popup_get_ids_by_post_type( $post_type ) {
		return get_posts(
			array(
				'post_type'   => $post_type,
				'numberposts' => - 1,
				'post_status' => 'publish',
				'fields'      => 'ids'
			)
		);
	}
}

new ThemeMove_Popup();