<?php

if( ! defined( 'ABSPATH' ) ) exit;

new popup($config);
class popup {
    
    private $config;
    private $post_type = "greyd_popup";

    /**
     * Holds all popup ids to be rendered on the page
     */
    public static $popup_ids = array();

    // private $meta_settings = "popup_settings";
    // private $meta_design = "popup_design";
    // private $beta = true;

    public function __construct($config) {
        // set config
        $this->config = (object)$config;

        // define and add custom post type
        add_action( 'init', array($this, 'add_posttype'), 1 );
        add_filter( 'manage_edit-greyd_popup_columns', array($this, 'add_column_heading') );
        add_action( "manage_greyd_popup_posts_custom_column", array($this, 'add_column_value'), 10, 2 );
        
        // edit screen for posttype
        add_action( 'add_meta_boxes', array($this, 'add_posttype_boxes') );
        add_action( 'save_post', array($this, 'save_post'), 20, 2 );
        add_action( 'admin_enqueue_scripts', array($this, 'load_admin_scripts'), 90 );
        
        // add wizard
        add_action( 'admin_enqueue_scripts', array($this, 'add_script'), 99 );
        add_action( 'in_admin_footer', array($this, 'add_footer_script') );
        add_action( 'admin_notices', array($this, 'add_wizard'), 999 );

        // VC close modul
        if(is_callable('vc_map') && is_callable('vc_add_param')) {
            add_action( 'vc_before_init', array($this, 'popup_close_vc') );
            add_action( 'init', array($this, 'mod_popup_vc'), 100 );
        }

        // frontend
        if (!is_admin() && isset($_GET['popup_preview'])) {
            add_filter( 'show_admin_bar', '__return_false' );
        }
        else if (!isset($_GET['popup_preview'])) {
            // add_action('wp_enqueue_scripts', array($this, 'popup_enqueue'), 0);
            add_shortcode( 'vc_close', array($this, 'popup_close_sc') );
            add_action( 'popup', array($this, 'render_popup') );
        }
        
        // add vc roles
        add_filter( 'greyd_add_vc_posttypes', [$this, 'add_vc_roles'] );
    }
    
    public function add_vc_roles($rules=[]) {
        return array_merge( $rules, [$this->post_type] );
    }

    /**
     * Add a popup ID to be rendered
     */
    public static function add_popup_id($id) {
        self::$popup_ids[$id] = $id;
    }
    
    
    /*
    ====================================================================================
        Register Pop-up Posttype
    ====================================================================================
    */
    // add custom post type
    public function add_posttype() {
        
        $name = __("Pop-ups", 'core');
        $singular = __("Pop-up", 'core');
        
        // define new post type
        $post_type_labels = array(
            'name'               => $name,
            'singular_name'      => $singular,
            'menu_name'          => $name,
            'name_admin_bar'     => $singular,
            'add_new'            => sprintf(__( 'Neues %s erstellen', 'core' ), $singular),
            'add_new_item'       => sprintf(__( '%s erstellen', 'core' ), $singular),
            'new_item'           => sprintf(__( 'Neues %s', 'core' ), $singular),
            'edit_item'          => sprintf(__( '%s bearbeiten', 'core' ), $singular),
            'view_item'          => sprintf(__( 'Zeige %s', 'core'), $singular),
            'all_items'          => sprintf(__( 'Alle %s', 'core'), $name),
            'all_items'          => $name,
            'search_items'       => sprintf(__( 'Suche %s', 'core'), $singular),
            'parent_item_colon'  => sprintf(__( 'Übergeordnetes %s', 'core'), $singular),
            'not_found'          => sprintf(__( 'Keine %s gefunden', 'core'), $name),
            'not_found_in_trash' => sprintf(__( 'Kein %s im Papierkorb gefunden', 'core'), $singular),
        );
        $post_type_arguments = array(
            'labels'             => $post_type_labels,
            'description'        => __( 'Beschreibung', 'core' ),
            'public'             => true,
            'exclude_from_search'=> true,
            'publicly_queryable' => false,
            'show_ui'            => true,
            'show_in_menu'       => 'greyd_dashboard',
            // 'show_in_menu'       => true,
            // 'menu_position'      => 20,
            // 'menu_icon'          => 'dashicons-external',
            'show_in_nav_menus'  => false,
            'show_in_admin_bar'  => false,
            'query_var'          => false,
            'rewrite'            => false,
            'capability_type'    => 'post',
            'has_archive'        => false,
            'supports'           => array( 'title', 'editor', 'custom-fields' ),
            'admin_column_sortable' => true,
            'admin_column_filter'   => true,
            'show_in_rest' => true
        );

        // register post_type and taxonony
        register_post_type($this->post_type, $post_type_arguments);
    }

    public function add_column_heading( $columns ) {
        $slug_column = array(
            'greyd_popup_trigger' => __( 'Trigger', 'core' ),
            'greyd_popup_display' => __( 'Darstellung', 'core' ),
            'greyd_popup_rules' => __( 'Regeln', 'core' ),
            'greyd_popup_prio' => __( 'Priorität', 'core' )
        );
        $columns = array_slice( $columns, 0, 2, true ) + $slug_column + array_slice( $columns, 2, count( $columns ) - 1, true );

        return $columns;
    }
    public function add_column_value( $column_name, $id ) {
        $meta = (array)get_post_meta($id, 'popup_settings', true);

        foreach( $meta as $k => $v ) {
            $meta[$k] = (object)$v;
        }

        if ($column_name == 'greyd_popup_trigger') {
            $trigger = array();
            if (isset($meta['on_init']) && $meta['on_init']->value != 'off') $trigger[] = __('Seitenaufruf', 'core');
            if (isset($meta['on_scroll']) && $meta['on_scroll']->value != 'off') $trigger[] = __('Scrollen', 'core');
            if (isset($meta['on_idle']) && $meta['on_idle']->value != 'off') $trigger[] = __('Inaktivität', 'core');
            if (isset($meta['on_exit']) && $meta['on_exit']->value != 'off') $trigger[] = __('Exit Intent', 'core');
            if (count($trigger) > 0) 
                echo implode(', ', $trigger);
            else echo "--";
        }
        else if ($column_name == 'greyd_popup_display') {
            $display = array();
            foreach ($meta as $key => $value) {
                if (strpos($key, 'on_') === 0) {
                    if ($key != 'on_init' && $key != 'on_scroll' && $key != 'on_idle' && $key != 'on_exit') {
                        if ($value->value != 'off') {
                            $posttype = get_post_type_object(substr($key, 3));
                            if ($posttype) {
                                $pre = __("alle", 'core');
                                if ($value->value == 'custom') $pre = __("einige", 'core');
                                $display[] = $pre." ".$posttype->label;
                            }
                        }
                    }
                }
            }
            if (count($display) > 0) 
                echo implode(', ', $display);
            else echo "--";
        }
        else if ($column_name == 'greyd_popup_rules') {
            $rules = array();
            if (isset($meta['delay']) && $meta['delay']->value != 'off') $rules[] = __('nach X Seiten', 'core');
            if (isset($meta['urlparam']) && $meta['urlparam']->value != 'off') $rules[] = __('URL Parameter', 'core');
            if (isset($meta['referer']) && $meta['referer']->value != 'off') $rules[] = __('vorherige Seite', 'core');
            if (isset($meta['user']) && $meta['user']->value != 'off') $rules[] = __('Nutzer', 'core');
            if (isset($meta['time']) && $meta['time']->value != 'off') $rules[] = __('Tageszeit', 'core');
            if (isset($meta['device']) && $meta['device']->value != 'off') $rules[] = __('Gerät', 'core');
            if (isset($meta['browser']) && $meta['browser']->value != 'off') $rules[] = __('Browser', 'core');
            if (count($rules) > 0) 
                echo implode(', ', $rules);
            else echo "--";
        }
        else if ($column_name == 'greyd_popup_prio') {
            $off1 = (isset($meta['prio']) && $meta['prio']->value == 1) ? 'off' : '';
            $off2 = (isset($meta['prio']) && $meta['prio']->value == 9) ? 'off' : '';
            echo "<span class='popup_prio ".$off1."' onclick='popup.prio_dec(".$id.")'>-</span>
                  <span id='popup_".$id."_priority'>".(isset($meta['prio']) ? $meta['prio']->value : 5)."</span>
                  <span class='popup_prio ".$off2."' onclick='popup.prio_inc(".$id.")'>+</span>";
        }
    }
    
    
    /*
    ====================================================================================
        Pop-up Meta
    ====================================================================================
    */
    public function add_posttype_boxes() {
        add_meta_box(
            'popup_design', // ID
            __('Aussehen', 'core'), // Title
            array($this, 'render_design_box'), // Callback
            $this->post_type, // CPT name
            'normal', // advanced = at bottom of page
            'low' // Priority
            //array $callback_args = null // Arguments passed to the callback
        );
        add_meta_box(
            'popup_settings', // ID
            __('Anzeige', 'core'), // Title
            array($this, 'render_settings_box'), // Callback
            $this->post_type, // CPT name
            'normal', // advanced = at bottom of page
            'low' // Priority
            //array $callback_args = null // Arguments passed to the callback
        );
    }
    
    /*
        Metabox: Aussehen
    */
    public function render_design_box($post) {
        $tabs       = [];
        $post_id    = $post->ID;
        $name       = 'popup_design';
        $meta       = (array)get_post_meta($post_id, $name, true);
        // debug($meta);

        $default_options = array(
            'layout' => array(
                'position' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'position', 
                    'label'         => __('Position', 'core'), 
                    'options'       => array( 
                        __('oben links', 'core') => 'tl', 
                        __('oben mitte', 'core') => 'tc', 
                        __('oben rechts', 'core') => 'tr', 
                        __('mitte links', 'core') => 'ml', 
                        __('mitte mitte', 'core') => 'mc', 
                        __('mitte rechts', 'core') => 'mr', 
                        __('unten links', 'core') => 'bl', 
                        __('unten mitte', 'core') => 'bc', 
                        __('unten rechts', 'core') => 'br', 
                    ), 
                    'default'       => 'mc', 
                ),
                'width' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'width', 
                    'label'         => __('Breite', 'core'), 
                    'options'       => array( 
                        __('auto', 'core') => 'auto', 
                        __('100%', 'core') => '100', 
                        __('individuell', 'core') => 'custom', 
                    ), 
                    'default'       => 'auto', 
                ),
                'width_custom' => array( 
                    'type'          => 'input', 
                    'param_name'    => 'width_custom', 
                    'placeholder'   => __('in px oder %', 'core'), 
                    'default'       => '',
                    'dependency'  => array(
                        array( 'element' => 'width', 'value' => array( 'custom' ) ),
                    ),
                ),
                'height' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'height', 
                    'label'         => __('Höhe', 'core'), 
                    'options'       => array( 
                        __('auto', 'core') => 'auto', 
                        __('100%', 'core') => '100', 
                        __('individuell', 'core') => 'custom', 
                    ), 
                    'default'       => 'auto', 
                ),
                'height_custom' => array( 
                    'type'          => 'input', 
                    'param_name'    => 'height_custom', 
                    'placeholder'   => __('in px oder %', 'core'), 
                    'default'       => '',
                    'dependency'  => array(
                        array( 'element' => 'height', 'value' => array( 'custom' ) ),
                    ),
                ),
                'align' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'align', 
                    'label'         => __('Ausrichtung Inhalt', 'core'), 
                    'options'       => array( 
                        __('oben', 'core') => 'top', 
                        __('mittig', 'core') => 'middle', 
                        __('unten', 'core') => 'bottom', 
                    ), 
                    'default'       => 'middle', 
                    'dependency'  => array(
                        array( 'element' => 'height', 'not_value' => array( 'auto' ) ),
                    ),
                ),
                'padding_tb' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'padding_tb', 
                    'label'         => array( 'lbl' => __('Padding oben/unten', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 20, 
                ),
                'padding_lr' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'padding_lr', 
                    'label'         => array( 'lbl' => __('Padding seitlich', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 20, 
                ),
                'margin_tb' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'margin_tb', 
                    'label'         => array( 'lbl' => __('Abstand oben/unten', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 30, 
                ),
                'margin_lr' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'margin_lr', 
                    'label'         => array( 'lbl' => __('Abstand seitlich', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 30, 
                ),

                'mobile_enable' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'mobile_enable', 
                    'head'          => __('Mobil', 'core'), 
                    'label'         => __('Abstände für Mobilgeräte verändern (< 768px)', 'core'), 
                    'default'       => 'false', 
                ),
                'mobile_width' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'mobile_width', 
                    'label'         => __('Breite', 'core'), 
                    'options'       => array( 
                        __('auto', 'core') => 'auto', 
                        __('100%', 'core') => '100', 
                        __('individuell', 'core') => 'custom', 
                    ), 
                    'default'       => 'auto',
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'mobile_width_custom' => array( 
                    'type'          => 'input', 
                    'param_name'    => 'mobile_width_custom', 
                    'placeholder'   => __('in px oder %', 'core'), 
                    'default'       => '',
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'mobile_width', 'value' => array( 'custom' ) ),
                    ),
                ),
                'mobile_height' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'mobile_height', 
                    'label'         => __('Höhe', 'core'), 
                    'options'       => array( 
                        __('auto', 'core') => 'auto', 
                        __('100%', 'core') => '100', 
                        __('individuell', 'core') => 'custom', 
                    ), 
                    'default'       => 'auto',
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'mobile_height_custom' => array( 
                    'type'          => 'input', 
                    'param_name'    => 'mobile_height_custom', 
                    'placeholder'   => __('in px oder %', 'core'), 
                    'default'       => '',
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'mobile_height', 'value' => array( 'custom' ) ),
                    ),
                ),
                'mobile_align' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'mobile_align', 
                    'label'         => __('Ausrichtung Inhalt', 'core'), 
                    'options'       => array( 
                        __('oben', 'core') => 'top', 
                        __('mittig', 'core') => 'middle', 
                        __('unten', 'core') => 'bottom', 
                    ), 
                    'default'       => 'middle', 
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'mobile_height', 'not_value' => array( 'auto' ) ),
                    ),
                ),
                'mobile_padding_tb' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'mobile_padding_tb', 
                    'label'         => array( 'lbl' => __('Padding oben/unten', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 20,
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'mobile_padding_lr' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'mobile_padding_lr', 
                    'label'         => array( 'lbl' => __('Padding seitlich', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 20,
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'mobile_margin_tb' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'mobile_margin_tb', 
                    'label'         => array( 'lbl' => __('Abstand oben/unten', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 30,
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'mobile_margin_lr' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'mobile_margin_lr', 
                    'label'         => array( 'lbl' => __('Abstand seitlich', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 30,
                    'dependency'  => array(
                        array( 'element' => 'mobile_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
            ),
            'design' => array(
                'text_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'text_color', 
                    'label'         => __('Textfarbe', 'core'), 
                    'default'       => 'color_21', 
                ),
                'head_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'head_color', 
                    'label'         => __('Headline Farbe', 'core'), 
                    'default'       => 'color_21', 
                ),
                'bg_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'bg_color', 
                    'label'         => __('Hintergrundfarbe', 'core'), 
                    'default'       => 'color_23', 
                ),
                'border_radius' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'border_radius', 
                    'label'         => array( 'lbl' => __('Eckenradius', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => 5, 
                ),

                'border_enable' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'border_enable', 
                    'label'         => __('Rahmen aktivieren', 'core'), 
                    'default'       => 'false', 
                ),
                'border_width' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'border_width', 
                    'label'         => array( 'lbl' => __('Stärke', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 50, 'step' => 1 ), 
                    'default'       => 1,
                    'dependency'  => array(
                        array( 'element' => 'border_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'border_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'border_color', 
                    'label'         => __('Rahmenfarbe', 'core'), 
                    'default'       => 'color_21',
                    'dependency'  => array(
                        array( 'element' => 'border_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'border_style' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'border_style', 
                    'label'         => __('Stil', 'core'), 
                    'options'       => \vc\helper::get_border_styles(), 
                    'default'       => 'solid',
                    'dependency'  => array(
                        array( 'element' => 'border_enable', 'value' => array( 'true' ) ),
                    ), 
                ),

                'shadow_enable' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'shadow_enable', 
                    'label'         => __('Schlagschatten aktivieren', 'core'), 
                    'default'       => 'false', 
                ),
                'shadow' => array( 
                    'type'          => 'shadow', 
                    'param_name'    => 'shadow', 
                    'default'       => 'none',
                    'dependency'  => array(
                        array( 'element' => 'shadow_enable', 'value' => array( 'true' ) ),
                    ) 
                ),
                
                'hover_enable' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'hover_enable', 
                    'head'          => __('Hover', 'core'), 
                    'label'         => __('Design on Hover verändern', 'core'), 
                    'default'       => 'false', 
                ),
                'hover_text_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'hover_text_color', 
                    'label'         => __('Textfarbe', 'core'), 
                    'default'       => 'color_21',
                    'dependency'  => array(
                        array( 'element' => 'hover_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'hover_head_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'hover_head_color', 
                    'label'         => __('Headline Farbe', 'core'), 
                    'default'       => 'color_21',
                    'dependency'  => array(
                        array( 'element' => 'hover_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'hover_bg_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'hover_bg_color', 
                    'label'         => __('Hintergrundfarbe', 'core'), 
                    'default'       => 'color_23',
                    'dependency'  => array(
                        array( 'element' => 'hover_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'hover_border_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'hover_border_color', 
                    'label'         => __('Rahmenfarbe', 'core'), 
                    'default'       => 'color_21',
                    'dependency'  => array(
                        array( 'element' => 'hover_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'border_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'hover_shadow' => array( 
                    'type'          => 'shadow', 
                    'param_name'    => 'hover_shadow', 
                    'label'         => __('Schlagschatten', 'core'), 
                    'default'       => 'none',
                    'dependency'  => array(
                        array( 'element' => 'hover_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'shadow_enable', 'value' => array( 'true' ) ),
                    ) 
                ),
            ),
            'more' => array(
                'overlay_enable' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'overlay_enable', 
                    'head'          => __('Seiten Overlay', 'core'), 
                    'label'         => __('Überlagerung der Seite aktivieren', 'core'), 
                    'default'       => 'true', 
                ),
                'overlay_color' => array( 
                    'type'          => 'colorselect', 
                    'param_name'    => 'overlay_color', 
                    'label'         => __('Farbe', 'core'), 
                    'default'       => 'color_61',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'overlay_opacity' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_opacity', 
                    'label'         => array( 'lbl' => __('Deckkraft', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => '25',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                    ), 
                ),

                'overlay_effect' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'overlay_effect', 
                    'label'         => __('Überlagerungseffekt', 'core'),
                    'description'   => __('Achtung: Überlagerungseffekte kosten eine Menge Ressourcen und können je nach Endgerät „ruckelig“ erscheinen.', 'core'),
                    'options'       => array( 
                        __('kein Effekt', 'core') => 'none',
                        __('Unschärfe', 'core') => 'blur',
                        __('Helligkeit', 'core') => 'brightness',
                        __('Kontrast', 'core') => 'contrast',
                        __('Graustufen', 'core') => 'grayscale',
                        __('Farbtonrotation', 'core') => 'hue-rotate',
                        __('Invertierung', 'core') => 'invert',
                        __('Sättigung', 'core') => 'saturate',
                        __('Sepiafarben', 'core') => 'sepia',
                    ), 
                    'default'       => 'blur',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'overlay_effect_blur' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_blur', 
                    'label'         => array( 'lbl' => __('Unschärfe', 'core'), 'unit' => 'px' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => '10',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'blur' ) ),
                    ), 
                ),
                'overlay_effect_brightness' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_brightness', 
                    'label'         => array( 'lbl' => __('Helligkeit', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 200, 'step' => 1 ), 
                    'default'       => '110',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'brightness' ) ),
                    ), 
                ),
                'overlay_effect_contrast' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_contrast', 
                    'label'         => array( 'lbl' => __('Kontrast ', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 200, 'step' => 1 ), 
                    'default'       => '110',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'contrast' ) ),
                    ), 
                ),
                'overlay_effect_grayscale' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_grayscale', 
                    'label'         => array( 'lbl' => __('Graustufen', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => '10',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'grayscale' ) ),
                    ), 
                ),
                'overlay_effect_hue-rotate' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_hue-rotate', 
                    'label'         => array( 'lbl' => __('Farbtonrotation', 'core'), 'unit' => '°' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 360, 'step' => 1 ), 
                    'default'       => '10',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'hue-rotate' ) ),
                    ), 
                ),
                'overlay_effect_invert' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_invert', 
                    'label'         => array( 'lbl' => __('Invertierung', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => '10',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'invert' ) ),
                    ), 
                ),
                'overlay_effect_saturate' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_saturate', 
                    'label'         => array( 'lbl' => __('Sättigung', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 200, 'step' => 1 ), 
                    'default'       => '110',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'saturate' ) ),
                    ), 
                ),
                'overlay_effect_sepia' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'overlay_effect_sepia', 
                    'label'         => array( 'lbl' => __('Sepiafarben', 'core'), 'unit' => '%' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 100, 'step' => 1 ), 
                    'default'       => '10',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                        array( 'element' => 'overlay_effect', 'value' => array( 'sepia' ) ),
                    ), 
                ),

                'overlay_close' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'overlay_close', 
                    'label'         => __('Pop-up bei Klick auf Overlay schließen', 'core'), 
                    'default'       => 'true',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                    ), 
                ),
                'overlay_noscroll' => array( 
                    'type'          => 'checkbox', 
                    'param_name'    => 'overlay_noscroll', 
                    'label'         => __('Scrollen auf der Seite verhindern', 'core'), 
                    'default'       => 'false',
                    'dependency'  => array(
                        array( 'element' => 'overlay_enable', 'value' => array( 'true' ) ),
                    ), 
                ),

                'anim_type' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'anim_type', 
                    'head'          => __('Animation', 'core'), 
                    'label'         => __('Art', 'core'), 
                    'options'       => array( 
                        __('keine Animation', 'core') => 'none',
                        __('Fade in', 'core') => 'fade', 
                        __('Scale up', 'core') => 'scale', 
                        __('Slide in von oben', 'core') => 'slide_top', 
                        __('Slide in von rechts', 'core') => 'slide_right', 
                        __('Slide in von unten', 'core') => 'slide_bottom', 
                        __('Slide in von links', 'core') => 'slide_left', 
                        __('Flip in (vertikal)', 'core') => 'flip_vertical', 
                        __('Flip in (horizontal)', 'core') => 'flip_horizontal', 
                        __('Flip in (3D)', 'core') => 'flip_3d', 
                    ), 
                    'default'       => 'fade', 
                ),
                'anim_time' => array( 
                    'type'          => 'range', 
                    'param_name'    => 'anim_time', 
                    'label'         => array( 'lbl' => __('Zeit', 'core'), 'unit' => 'ms' ), 
                    'input_attrs'   => array( 'min' => 0, 'max' => 5000, 'step' => 1 ), 
                    'default'       => 300,
                    'dependency'  => array(
                        array( 'element' => 'anim_type', 'not_value' => array( 'none' ) ),
                    ), 
                ),
                'overflow' => array( 
                    'type'          => 'select', 
                    'param_name'    => 'overflow', 
                    'head'          => __('Weitere Einstellungen', 'core'), 
                    'label'         => __('Überlauf im Pop-up', 'core'), 
                    'options'       => array( 
                        __('scrollbar', 'core') => 'auto', 
                        __('sichtbar', 'core') => 'visible', 
                        __('nicht sichtbar', 'core') => 'hidden',
                    ), 
                    'default'    => 'auto' 
                ),
                'css_class' => array( 
                    'type'          => 'input', 
                    'param_name'    => 'css_class', 
                    'label'         => __('CSS Klasse', 'core'), 
                    'placeholder'   => __('Klassennamen mit Leerzeichen trennen', 'core'), 
                    'default'       => ''  
                ),
            ),
        );
        
        $controls = array(
            'layout' => array(),
            'design' => array(),
            'more' => array(),
        );
        foreach ($default_options as $slug => $options) {
            $inputs = "";
            foreach ($options as $control => $params) {
                if ($params == "") continue;
                $dependency = (isset($params['dependency'])) ? 'data-dependency="'.urlencode(json_encode($params['dependency'])).'"' : '';
                $type = ' data-param_type="'.$params['type'].'"';
                $value = (isset($meta[$control])) ? $meta[$control] : $params['default'];
                switch ($params['type']) {
                    case 'range': $inputs .= '<div class="design_input" '.$dependency.$type.'>'.self::render_range_control( $params, $value ).'</div>'; break;
                    case 'input': $inputs .= '<div class="design_input" '.$dependency.$type.'>'.self::render_input_control( $params, $value ).'</div>'; break;
                    case 'checkbox': $inputs .= '<div class="design_input" '.$dependency.$type.'>'.self::render_checkbox_control( $params, $value ).'</div>'; break;
                    case 'select': $inputs .= '<div class="design_input" '.$dependency.$type.'>'.self::render_select_control( $params, $value ).'</div>'; break;
                    case 'colorselect': $inputs .= '<div class="design_input" '.$dependency.$type.'>'.self::render_colorselect_control( $params, $value ).'</div>'; break;
                    case 'shadow': $inputs .= '<div class="design_input" '.$dependency.$type.'>'.self::render_shadow_control( $params, $value ).'</div>'; break;
                }
            }
            $controls[$slug] = $inputs;
        }

        // -------------------- Tab: Layout
        $tabs[] = [
            "slug" => "layout",
            "title" => __("Layout", 'core'),
            "content" => '<div class="input_section">'.$controls['layout'].'</div>'
        ];
        // -------------------- Tab: Design
        $tabs[] = [
            "slug" => "design",
            "title" => __("Design", 'core'),
            "content" => '<div class="input_section">'.$controls['design'].'</div>'
        ];
        // -------------------- Tab: Erweitert
        $tabs[] = [
            "slug" => "more",
            "title" => __("Erweitert", 'core'),
            "content" => '<div class="input_section">'.$controls['more'].'</div>'
        ];
        
        // -------------------- Render
        echo '<input class="popup_design_data" type="hidden" name="'.$name.'" value="'.addslashes(json_encode($meta)).'" style="width:100%">';
        echo '<div class="popup_design">';
            echo '<div class="popup_design_tabs">';
                echo '<div class="tabs">';
                $active = "active";
                foreach($tabs as $tab) {
                    echo '<div class="tablink '.$active.'" onclick="popup.switchDesignTab(this)" data-title="'.$tab['slug'].'">'.$tab['title'].'</div>';
                    $active = "";
                }
                echo '</div>';
                $active = "maybe_active";
                foreach($tabs as $tab) {
                    echo '<div class="tabcontent '.$active.'" data-title="'.$tab['slug'].'">'.$tab['content'].'</div>';
                    $active = "";
                }
            echo '</div>';
            
            $website = '<div class="popup_website">
                            <iframe name="popup-preview-0" src="'.home_url().'/?popup_preview='.wp_generate_uuid4().'"></iframe>
                        </div>';
            $popup   = "<div>".$this->popup_close_sc( array( 'align'=>'_right', 'size'=>20, 'width'=>2 ) )."
                            <h3>".__('Vorschau', 'core')."</h3>
                            <p style='max-width:36em;'>".__('Dies ist eine exemplarische Vorschau. Sie zeigt nicht den tatsächlichen Inhalt deines Pop-ups.', 'core')."</p>
                        </div>";
            $preview = "<div id='popup_preview' name='popup-preview' class='popup hidden'>
                            <div class='popup_overlay'></div>
                            <div class='popup_content animate_fast'>
                                <div class='popup_wrapper'>".$popup."</div>
                            </div>
                        </div>";
            $switch =  '<div class="popup_switch">
                            <span class="dashicons dashicons-desktop desktop active"></span>
                            <span class="dashicons dashicons-smartphone mobile"></span>
                        </div>';

            echo '<div class="popup_design_preview">
                    '.$website.$preview.$switch.'
                  </div>';
        echo '</div>';
    }

    /*
        Metabox: Anzeige
    */
    public function render_settings_box($post) {
        $rows       = [];
        $post_id    = $post->ID;
        $name       = 'popup_settings';
        $meta       = (array)get_post_meta($post_id, $name, true);
        // debug($meta);

        $trigger = array(
            'on_init' => array(
                'type'          => 'switch', 
                'param_name'    => 'on_init', 
                'head'          => __('beim Seitenaufruf', 'core'), 
                'label'         => __('nach %s Sekunden', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'numfield', 
                        'param_name'    => "time",
                        'default'       => '15', // string
                        'steps'         => '1',
                        'min'           => '0',
                        'max'           => '360'
                    ),
                ),
            ),
            'on_scroll' => array(
                'type'          => 'switch', 
                'param_name'    => 'on_scroll', 
                'head'          => __('beim Scrollen', 'core'), 
                'label'         => __('nach %s der Seite (px, % oder vh)', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'textfield', 
                        'param_name'    => "height",
                        'default'       => '50%', // string
                    ),
                ),
            ),
            'on_idle' => array(
                'type'          => 'switch', 
                'param_name'    => 'on_idle', 
                'head'          => __('bei Inaktivität', 'core'), 
                'label'         => __('nach %s Sekunden Inaktivität', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'numfield', 
                        'param_name'    => "time",
                        'default'       => '15', // string
                        'steps'         => '1',
                        'min'           => '0',
                        'max'           => '360'
                    ),
                ),
            ),
            'on_exit' => array(
                'type'          => 'switch', 
                'param_name'    => 'on_exit', 
                'head'          => __('Exit Intent', 'core'), 
                'label'         => __('wenn der Nutzer die Seite verlassen möchte', 'core'), 
                'default'       => 'on', // 'on'/'off'
            ),
            'button_popup' => array(
                'type'          => 'info', 
                'param_name'    => 'button_popup', 
                'head'          => __('durch einen Button', 'core'), 
                'label'         => sprintf(
                    "<p>".__("Um ein Pop-up über einen Button auszulösen, wähle im Button-Modul auf der entsprechenden Seite den Button-Typ '%s' aus und wähle das gewünschte Pop-up aus.", 'core')."</p>".
                    "<p>".__("Am besten stellst du keine Regeln oder Darstellungen ein - das Pop-up wird automatisch dargestellt. Wir empfehlen zudem, unten den Haken für '%s' wegzulassen.", 'core')."</p>",
                    '<b>'._x('Pop-up öffnen', 'small', 'core').'</b>',
                    '<b>'.__('Pop-up nur einmal anzeigen', 'core').'</b>' )
            ),
        );

        $display = array(
            'on_page' => array(
                'type'          => 'radio_switch', 
                'radio'         => array(
                    __('anzeigen', 'core') => 'on',
                    __('individuell', 'core') => 'custom', 
                    __('ausblenden', 'core') => 'off', 
                ),
                'param_name'    => 'on_page', 
                'head'          => __('auf normalen Seiten', 'core'), 
                'default'       => 'on', // 'on'/'custom'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'autotags', 
                        'param_name'    => "items", 
                        'label'         => __('Seiten auswählen', 'core'), 
                        'values'        => array(), 
                        'default'       => '', // string
                    ),
                ),
            ),
            'on_system' => array(
                'type'          => 'radio_switch', 
                'radio'         => array(
                    __('anzeigen', 'core') => 'on',
                    __('individuell', 'core') => 'custom', 
                    __('ausblenden', 'core') => 'off', 
                ),
                'param_name'    => 'on_system', 
                'head'          => __('auf System Seiten (404, Suche...)', 'core'), 
                'default'       => 'off', // 'on'/'custom'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'checkbox', 
                        'param_name'    => "show_on", 
                        'values'        => array( 
                            __('auf der 404 Seite', 'core') => '404',
                            __('in der Suche', 'core') => 'search',
                        ), 
                        'default'       => '', // string
                    ),
                ),
            ),
            'on_post' => array(
                'type'          => 'radio_switch', 
                'radio'         => array(
                    __('anzeigen', 'core') => 'on',
                    __('individuell', 'core') => 'custom', 
                    __('ausblenden', 'core') => 'off', 
                ),
                'param_name'    => 'on_post', 
                'head'          => __('auf Beitragsseiten', 'core'), 
                'default'       => 'custom', // 'on'/'custom'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'autotags', 
                        'param_name'    => "items", 
                        'label'         => __('Beiträge auswählen', 'core'), 
                        'values'        => array(), 
                        'default'       => '', // string
                    ),
                    array( 
                        'type'          => 'checkbox', 
                        'param_name'    => "show_on", 
                        'values'        => array( 
                            __('auf Archivseiten anzeigen', 'core') => 'archive', 
                        ), 
                        'default'       => '', // string
                    ),
                ),
            ),
            // 'dpts' => ...
        );
        foreach (\vc\helper::get_all_posttypes() as $pt) {
            if ($pt->count == 0) continue;
            
            // posts
            $all        = \vc\helper::get_all_posts($pt->slug);
            $content    = array();
            $single     = $pt->slug == 'page' ? __('Seiten', 'core') : __('Beiträge', 'core');
            $values     = array( $single => array() );
            foreach ($all as $item) {
                $title = urlencode($item->title);
                $content[$title] = $item->id;
                $values[$single][$title] = $item->id;
            }
            
            // categories
            $cats = \vc\helper::get_category_slug($pt->slug);
            if ($cats) {
                $values[__('Kategorien', 'core')] = array();
                $cats = \vc\helper::get_all_terms($cats);
                foreach ($cats as $item) {
                    $title = urlencode($item->title);
                    $content[$title.__(' (Kategorie)', 'core')] = "cat_".$item->id;
                    $values[__('Kategorien', 'core')][$title] = "cat_".$item->id;
                }
            }
            $slug = "on_".$pt->slug;
            if ($pt->slug == 'post' || $pt->slug == 'page')
                $display[$slug]['params'][0]['values'] = $values;
            else {
                $display[$slug] = array(
                    'type'          => 'radio_switch', 
                    'radio'         => array(
                        __('anzeigen', 'core') => 'on',
                        __('individuell', 'core') => 'custom', 
                        __('ausblenden', 'core') => 'off', 
                    ),
                    'param_name'    => $slug, 
                    'head'          => sprintf(__('auf "%s"-Seiten', 'core'), $pt->title), 
                    'options'       => $content, 
                    'default'       => 'off', // 'on'/'custom'/'off'
                    'params'        => array(
                        array( 
                            'type'          => 'autotags', 
                            'param_name'    => "items", 
                            'label'         => sprintf(__('%s auswählen', 'core'), $pt->title), 
                            'values'        => $values, 
                            'default'       => '', // string
                        ),
                    ),
                );
                $greyd_posttype = \vc\helper::get_dynamic_posttype_by_slug($pt->slug);
                if ( $greyd_posttype ) {
                    $posttype_settings = isset($greyd_posttype['arguments']) ? (array) $greyd_posttype['arguments'] : array();
                    if ( isset($posttype_settings['archive']) ) {
                        $display[$slug]['params'][] = array( 
                            'type'          => 'checkbox', 
                            'param_name'    => 'show_on', 
                            'values'        => array( 
                                __('auf Archivseiten anzeigen', 'core') => "archive", 
                            ), 
                            'default'       => '', // string
                        );
                    }
                }
            }
        }

        $conditions = array( 
            _x('hat den Wert:', 'small', 'core') => 'is',
            _x('enthält den Wert:', 'small', 'core') => 'has',
            _x('hat nicht den Wert:', 'small', 'core') => 'is_not',
            _x('ist gesetzt', 'small', 'core') => 'not_empty',
            _x('ist nicht gesetzt', 'small', 'core') => 'empty',
        );
        $conditions2 = array( 
            _x('enthält:', 'small', 'core') => 'has',
            _x('enthält nicht:', 'small', 'core') => 'has_not',
            _x('ist:', 'small', 'core') => 'is',
            _x('ist nicht:', 'small', 'core') => 'is_not',
        );
        $user_roles = array( _x("unbekannt (nicht eingeloggt)", 'small', 'core') => "none" );
        foreach (get_editable_roles() as $role => $atts) {
            $user_roles[$atts["name"]] = $role;
        }
        $times = array(
            _x("morgens (ab 5 Uhr)", 'small', 'core') => "5-12",
            _x("mittags (ab 12 Uhr)", 'small', 'core') => "12-17",
            _x("abends (ab 17 Uhr)", 'small', 'core') => "17-23",
            _x("nachts (23 Uhr bis 5 Uhr)", 'small', 'core') => "23-24,0-5",
            _x("individuelle Uhrzeit", 'small', 'core') => "custom"
        );
        $rules = array(
            'delay' => array(
                'type'          => 'switch', 
                'param_name'    => 'delay', 
                'head'          => __('erst nach X Seiten anzeigen', 'core'), 
                'label'         => __('nach %s besuchten Seiten', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'numfield', 
                        'param_name'    => "count",
                        'default'       => '3', // string
                        'steps'         => '1',
                        'min'           => '0',
                        'max'           => '20'
                    ),
                ),
            ),
            'urlparam' => array(
                'type'          => 'switch', 
                'param_name'    => 'urlparam', 
                'head'          => __('abhängig von URL Parameter', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'textfield', 
                        'param_name'    => "name", 
                        'label'         => __('URL Parameter', 'core' ),
                        'placeholder'   => __('Name', 'core' ),
                        'default'       => '', // string
                    ),
                    array( 
                        'type'          => 'select', 
                        'param_name'    => "condition", 
                        'options'       => $conditions,
                        'default'       => 'is', // option
                    ),
                    array( 
                        'type'          => 'textfield', 
                        'param_name'    => "value", 
                        'placeholder'   => __('Wert', 'core' ),
                        'default'       => '', // string
                    ),
                ),
                'class'         => 'inline',
            ),
            'referer' => array(
                'type'          => 'switch', 
                'param_name'    => 'referer', 
                'head'          => __('abhängig von vorheriger Seite', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'select', 
                        'param_name'    => "condition", 
                        'label'         => __('voherige URL', 'core' ),
                        'options'       => $conditions2,
                        'default'       => 'is', // option
                    ),
                    array( 
                        'type'          => 'textfield', 
                        'param_name'    => "value", 
                        'placeholder'   => __('URL oder Teil einer URL', 'core' ),
                        'default'       => '', // string
                    ),
                ),
                'class'         => 'inline',
            ),
            'user' => array(
                'type'          => 'switch', 
                'param_name'    => 'user', 
                'head'          => __('nur für bestimmte Nutzer', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'checkbox', 
                        'param_name'    => "select", 
                        'values'        => $user_roles, 
                        'default'       => '', // string
                    ),
                ),
            ),
            'time' => array(
                'type'          => 'switch', 
                'param_name'    => 'time', 
                'head'          => __('nur zu bestimmten Tageszeiten', 'core'),
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'checkbox', 
                        'param_name'    => "select", 
                        // 'label'         => __('Tageszeiten auswählen', 'core'), 
                        'values'        => $times, 
                        'default'       => '', // string
                    ),
                    array( 
                        'type'          => 'textfield', 
                        'param_name'    => "custom", 
                        // 'label'         => __('individuelle Uhrzeit', 'core' ),
                        'description'   => __('Uhrzeiten in vollen Stunden angeben und mit Bindestrichen trennen (z.B. für 12 bis 13 Uhr: 12-13).<br>Mehrere Zeitabschnitte mit Komma trennen (z.B. 12-13,15-16).<br>Uhrzeiten vor und nach Mitternacht als einzelne Abschnitte angeben (z.B. für 22 bis 4 Uhr morgens: 22-24,0-4).', 'core'),
                        'default'       => '', // string
                    ),
                ),
            ),
            'device' => array(
                'type'          => 'switch', 
                'param_name'    => 'device', 
                'head'          => __('abhängig vom Gerät', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'checkbox', 
                        'param_name'    => "select", 
                        'values'        => array( 
                            __('Windows', 'core') => 'win', 
                            __('OSX', 'core') => 'osx', 
                            __('iOS', 'core') => 'ios', 
                            __('Android', 'core') => 'android', 
                            __('unbekanntes Gerät', 'core') => 'unknown',
                        ), 
                        'default'       => '', // string
                    ),
                ),
            ),
            'browser' => array(
                'type'          => 'switch', 
                'param_name'    => 'browser', 
                'head'          => __('abhängig vom Browser', 'core'), 
                'default'       => 'off', // 'on'/'off'
                'params'        => array(
                    array( 
                        'type'          => 'checkbox', 
                        'param_name'    => "select", 
                        'values'        => array( 
                            __('Firefox', 'core') => 'firefox', 
                            __('Chrome', 'core') => 'chrome', 
                            __('Opera', 'core') => 'opera', 
                            __('Edge', 'core') => 'edge', 
                            __('Internet Explorer', 'core') => 'ie', 
                            __('Safari', 'core') => 'safari', 
                            __('unbekannter Browser', 'core') => 'unknown', 
                        ), 
                        'default'       => '', // string
                    ),
                ),
            ),
        );

        $more = array(
            'prio' => array( 
                'type'          => 'select', 
                'param_name'    => 'prio', 
                'label'         => __('Priorität', 'core'), 
                'description'   => __('Pop-ups mit höherer Priorität werden <b>über</b> anderen Pop-ups dargestellt.<br>Bei gleicher Priorität wird das Datum verwendet (neuer = wichtiger).', 'core'), 
                'options'       => array( 
                    '10' => '10', '9' => '9', '8' => '8', '7' => '7', '6' => '6',
                    '5'.__(' (Standard)', 'core') => '5', '4' => '4',  '3' => '3', '2' => '2', '1' => '1',
                    
                ), 
                'default'       => '5',  // 0-9
            ),
            'highest' => array( 
                'type'          => 'checkbox', 
                'param_name'    => 'highest', 
                'label'         => __('Sobald das Pop-up getriggert wird, alle Pop-ups mit niedrigerer Priorität ausblenden', 'core'), 
                'default'       => 'false', // 'true'/'false'
            ),
            'hashtag' => array( 
                'type'          => 'checkbox', 
                'param_name'    => 'hashtag', 
                'label'         => __('Hashtags in URL setzen', 'core'), 
                'description'   => __('Durch diese Funktion wird die URL der Seite beim Öffnen des Pop-ups verändert, indem ein Hashtag gesetzt wird.<br>Dadurch lässt sich das Pop-up mit Analytic-Tools tracken und so das Nutzerverhalten nachvollziehen.', 'core'), 
                'default'       => 'false', // 'true'/'false'
            ),
            'once' => array( 
                'type'          => 'checkbox', 
                'param_name'    => 'once', 
                'label'         => __('Pop-up nur einmal anzeigen', 'core'), 
                'description'   => __('Ist diese Funktion aktiv, wird das Pop-up nach dem Schließen komplett entfernt.<br>Somit kann es auf der Seite nicht mehrfach getriggert werden.', 'core').'<br><strong>'.__('Nach Beenden des Browsers wird das Popup erneut einmal angezeigt.', 'core').'</strong>', 
                'default'       => 'false', // 'true'/'false'
            ),

        );

        $default_options = array(
            'trigger' => $trigger,
            'display' => $display,
            'rules' => $rules,
            'more' => $more,
        );
        
        $controls = array(
            'trigger' => '',
            'display' => '',
            'rules' => '',
            'more' => '',
        );
        
        foreach ($default_options as $slug => $options) {
            $inputs = "";
            foreach ($options as $control => $params) {
                if (!is_array($params)) continue;
                $type = ' data-param_type="'.$params['type'].'"';
                $value = isset($params['default']) ? $params['default'] : NULL;
                // debug($meta[$control]);
                $value = (isset($meta[$control])) ? (array)$meta[$control] : $value;
                switch ($params['type']) {
                    case 'switch': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_switch_setting( $params, $value ).'</div>'; break;
                    case 'radio_switch': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_rswitch_setting( $params, $value ).'</div>'; break;
                    // case 'range': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_range_control( $params, $value ).'</div>'; break;
                    // case 'input': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_input_control( $params, $value ).'</div>'; break;
                    case 'checkbox': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_checkbox_setting( $params, $value ).'</div>'; break;
                    case 'select': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_select_setting( $params, $value ).'</div>'; break;
                    // case 'colorselect': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_colorselect_control( $params, $value ).'</div>'; break;
                    // case 'shadow': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_shadow_control( $params, $value ).'</div>'; break;
                    case 'info': $inputs .= '<div class="settings_input" '.$type.'>'.self::render_info_setting( $params, $value ).'</div>'; break;
                }
            }
            $controls[$slug] = $inputs;
        }

        // -------------------- Row: Trigger
        $rows[] = [
            "title" => __("Trigger", 'core'),
            "desc" => __("Wann soll das Pop-up ausgelöst werden?", 'core'),
            "content" => '<div class="input_section">'.$controls['trigger'].'</div>'
        ];
        // -------------------- Row: Darstellung
        $rows[] = [
            "title" => __("Darstellung", 'core'),
            "desc" => __("Auf welchen Seiten soll das Pop-up auslösbar sein?", 'core'),
            "content" => '<div class="input_section">'.$controls['display'].'</div>'
        ];
        // -------------------- Row: Regeln
        $rows[] = [
            "title" => __("Regeln", 'core'),
            "desc" => __("Bedingungen die erfüllt sein müssen, damit das Pop-up angezeigt wird", 'core'),
            "content" => '<div class="input_section">'.$controls['rules'].'</div>'
        ];
        // -------------------- Row: Erweitert
        $rows[] = [
            "title" => __("Erweitert", 'core'),
            "desc" => __("Wie verhält sich das Pop-up?", 'core'),
            "content" => '<div class="input_section">'.$controls['more'].'</div>'
        ];
        
        // -------------------- Render
        echo '<input class="popup_settings_data" type="hidden" name="'.$name.'" value="" style="width:100%">';
        echo '<table class="greyd_table vertical big posttype_table">';
        foreach($rows as $row) {
            $this->render_table_row($row);
        }
        echo '</table>';
        
        $this->render_submit();
    }

    
    /*
        Save posttype
    */
    public function save_post($post_id, $post) {
        if ($post->post_type != $this->post_type) return;
        if (!is_admin()) return;
        if (empty($_POST)) return;
        if ( !isset($_POST['meta_action']) || $_POST['meta_action'] !== 'wp_backend' ) return;
        
        // debug($_POST);
        // debug($_POST['popup_design']);
        // debug($_POST['popup_settings']);
        // debug(json_decode(stripslashes($_POST['popup_design'])));
        // debug(json_decode(stripslashes($_POST['popup_settings'])));
        // wp_die();

        if (isset($_POST['popup_design']) && $_POST['popup_design'] != "") 
            $this->save_metadata( $post_id, 'popup_design', json_decode(stripslashes($_POST['popup_design'])) );
        if (isset($_POST['popup_settings']) && $_POST['popup_settings'] != "") 
            $this->save_metadata( $post_id, 'popup_settings', json_decode(stripslashes($_POST['popup_settings'])) );
    }
    
    public function load_admin_scripts() {
        global $config;

        // admin styles
        wp_register_style( 'popups_admin_css', get_template_directory_uri().'/assets/css/deprecated/popups_admin.css', null, $config->theme_version, 'all' );
        wp_enqueue_style('popups_admin_css');

        // register & enqueue admin scripts
        wp_register_script('popups_admin_js', get_template_directory_uri().'/assets/js/deprecated/popups_admin.js', array('jquery'), $config->theme_version, false);
        wp_enqueue_script('popups_admin_js');

    }
    
    

    /*
    ====================================================================================
        Wizard
    ====================================================================================
    */
    // add scripts
    public function add_script() {
        global $config;
        $screen = get_current_screen();
        if ($screen->post_type == $this->post_type) {
            if ($screen->base == 'edit') {
                $plist = array();
                $posts = \vc\helper::get_all_posts($this->post_type);
                foreach($posts as $post) {
                    $plist[] = array( 'id' => $post->id, 'slug' => $post->slug, 'title' => $post->title );
                }
                wp_add_inline_script( 'default_admin_js', 'var popups = '.json_encode($plist).';' );
            }
            if ($screen->base == 'post') {
                // register & enqueue admin scripts
                wp_register_script('popup_admin_js', get_template_directory_uri().'/assets/js/vc_colors.js', array('jquery'), $config->theme_version, true);
                wp_enqueue_script('popup_admin_js');

            }
        }
    }
    public function add_footer_script() {
        global $config;
        $screen = get_current_screen();
        if ($screen->post_type == $this->post_type && $screen->base == 'post') {
            global $wp_scripts;
            // register & enqueue admin scripts when vc editor is disabled
            if (!in_array('wp-color-picker', $wp_scripts->queue)) {
                wp_enqueue_style( 'wp-color-picker' );
                wp_enqueue_script( 'wp-color-picker');
            }
            if (!in_array('vc-backend-min-js', $wp_scripts->queue)) {
                wp_add_inline_script( 'wp-color-picker', 'var root = '.json_encode(\processor::$root).';' );
                wp_register_style( 'vc_extensions', get_template_directory_uri().'/assets/css/deprecated/vc_extensions.css', null, $config->theme_version, 'all' );
                wp_enqueue_style( 'vc_extensions' );
            }
        }
    }
    // add Pop-up Wizard
    public function add_wizard() {
        $screen = get_current_screen();
        if ($screen->post_type == $this->post_type) {
            if ($screen->base == 'edit') {

                $this->render_wizard();
            }
        }
    }
    // render Pop-up Wizard
    public function render_wizard() {
        $asset_url = get_template_directory_uri()."/assets/icon/wizard";
        
        $popup_presets = array();
        $active_preset = "active";

        if ( empty(\ajax_handler::$default_contents) ) \ajax_handler::init_default_contents();

        foreach (\ajax_handler::$default_contents['popups'] as $id => $content) {
            $big = ($id != "empty") ? 'big' : '';
            $popup_presets[] = '<span id="'.$id.'" class="content_option '.$active_preset.'"><img class="option_icon '.$big.'" src="'.$asset_url.'/'.$content['icon'].'"><p>'.$content['title'].'</p></span>';
            $active_preset = "";
        }

        $popups = array();
        $posts = \vc\helper::get_all_posts($this->post_type);
        foreach($posts as $post) {
            $plist[] = array( 'id' => $post->id, 'slug' => $post->slug, 'title' => $post->title );
            $language = "";
            if (is_array($post->lang) && $post->lang['display_name'] != "") 
                $language = ' ('.$post->lang['language_code'].')';
            $popups[] = '<option value="'.$post->id.'">'.$post->title.$language.'</option>';
        }

        echo '
        <div id="greyd-wizard" class="wizzard popup_wizzard">
            <div class="wizzard_box big">
                <div class="wizzard_head">
                    <img class="wizzard_icon" src="'.$asset_url.'/logo_light.svg">
                    <span class="close_wizzard dashicons dashicons-no-alt"></span>
                </div>
                <div class="wizzard_content">
                    <div data-slide="0-error">
                        <h2>'.__('Ooooops!', 'core').'</h2>
                        <div class="greyd_info_box orange" style="width: 100%; box-sizing: border-box;">
                            <span class="dashicons dashicons-warning"></span>
                            <div>
                                <p>'.__('Ein Problem ist aufgetreten:', 'core').'</p><br>
                                <p class="error_msg"></p>
                            </div>
                        </div>
                    </div>
                    <div data-slide="1">
                        <h2>'.__('Neues Pop-up erstellen', 'core').'</h2>
                        
                        <div class="row flex">
                            <div class="element grow">
                                <div class="label">'.__('Name', 'core').'</div>
                                <input id="name" name="name" type="text" value="" placeholder="'.__('hier eingeben', 'core').'" >
                                <input id="slug" name="slug" type="hidden" value="" >
                                <input id="ttype" name="ttype" type="hidden" value="popup" >
                            </div>
                        </div>
                        <div class="row flex">
                            <div class="element grow name_double" style="display:none">
                                <div class="greyd_info_box warning">
                                    <span class="dashicons dashicons-warning"></span>
                                    <div>
                                        <div style="margin-bottom:10px"><strong>'.__('Achtung:', 'core').'</strong></div>
                                        <div style="margin-bottom:10px">'.sprintf(__('Das gewählte Pop-up existiert bereits (Name: „%s“). Um das Pop-up neu zu erstellen, musst du erst das vorhandene in den Papierkorb legen. Du kannst es aber auch ganz einfach auf den Standard zurücksetzen oder bearbeiten.', 'core'), '<span class="double_name">Templatename</span>').'</div>
                                        <div style="margin-bottom:10px"><a class="double_reset" style="cursor:pointer;text-decoration:underline">'.__('auf Standard zurücksetzen', 'core').'</a> | <a class="double_edit" href="#">'._x('Pop-up bearbeiten', 'small', 'core').'</a></div>
                                    </div>
                                </div>
                            </div>
                            <div class="element grow name_ok">
                                <div class="label">'.__('Inhalt', 'core').'</div>
                                <div class="content_options">
                                    '.implode('', $popup_presets).'
                                    <span id="copy" class="content_option"><img class="option_icon" src="'.$asset_url.'/copy.png"><p>'._x('Kopie', 'small', 'core').'</p>
                                        <select id="copy_popup" class="copy" name="copy_popup">
                                            <option value="0">'._x('Pop-up wählen', 'small', 'core').'</option>
                                            '.implode('', $popups).'
                                        </select>
                                    </span>
                                </div>
                            </div>
                        </div>

                        
                    </div>
                    <div data-slide="11">
                        <h2>'.__('Glückwunsch!', 'core').'</h2>
                        <div class="install_txt">'.__('Das Pop-up "%s" wurde erfolgreich erstellt.', 'core').'</div>
                        <div class="success_mark"><div class="checkmark"></div></div>
                    </div>
                </div>
                <div class="wizzard_foot">
                    <div data-slide="0-error">
                        <div class="flex">
                            <span class="back button button-secondary">'.__('zurück', 'core').'</span>
                            <span class="close_wizzard reload button button-primary">'.__('schließen', 'core').'</span>
                        </div>
                    </div>
                    <div data-slide="1">
                        <div class="flex">
                            <span class="close_wizzard button button-secondary">'.__('zurück', 'core').'</span>
                            <span class="create button button-primary">'._x('Pop-up erstellen', 'small', 'core').'</span>
                        </div>
                    </div>
                    <div data-slide="11">
                        <div class="flex">
                            <span class="close_wizzard reload button button-secondary">'.__('schließen', 'core').'</span>
                            <a class="finish_wizzard button button-primary" href="">'._x('Pop-up bearbeiten', 'small', 'core').'</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>';
    }



    /*
    ====================================================================================
        Helper functions
    ====================================================================================
    */
    
    /*
        handling settings
    */
    public function save_metadata($post_id, $name, $value) {
        if (metadata_exists('post', $post_id, $name)) {
            update_post_meta($post_id, $name, $value);
        } else {
            add_post_meta($post_id, $name, $value);
        }
    }
    
    
    /*
        render stuff
    */
    public function render_table_row($atts=[], $echo=true) {
        
        $title      = isset($atts["title"]) ? "<h3>".$atts["title"]."</h3>" : "";
        $desc       = isset($atts["desc"]) ? $atts["desc"] : "";
        $content    = isset($atts["content"]) ? $atts["content"] : "";
        
        ob_start();
        echo '<tr>
                <th>
                    '.$title.'
                    '.$desc.'
                </th>
                <td>
                    '.$content.'
                </td>
            </tr>';
        $return = ob_get_contents();
        ob_end_clean();
        if ($echo) echo $return;
        else return $return;
    }
    public function render_submit($break_meta=true, $text=null) {
        
        // render hidden action
        echo '<input type="hidden" name="meta_action" value="wp_backend" />';
        
        if ($break_meta) echo '</div></div></div><div><div><div>';

        if ( method_exists( '\greyd\blocks\helper', 'is_gutenberg_page' ) ) {
            if ( \greyd\blocks\helper::is_gutenberg_page() ) return;
        }

        // render submit button
        if (empty($text)) $text = __('Änderungen speichern', 'greyd_hub');
        
        if ( get_current_screen()->action !== "add") {
            submit_button( $text, 'primary large', 'save', true , ["id" => "submit"]);
        }
    }
    
    // design controls
    public static function render_range_control( $settings, $value ) {
        $value = str_replace(array('px','%','em'), '', $value);
        $param = esc_attr($settings['param_name']);
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = "";
        if (isset($settings['label'])) {
            if (is_array($settings['label'])) $label = "<label data-label='".esc_attr($settings['label']['lbl'])."' data-unit='".esc_attr($settings['label']['unit'])."'></label>";
            else if (!empty($settings['label'])) $label = "<label>".esc_attr($settings['label'])."</label>";
        }
        $input_attrs = $settings['input_attrs'];
        $atts = "min='".esc_attr($input_attrs['min'])."' max='".esc_attr($input_attrs['max'])."' step='".esc_attr($input_attrs['step'])."' ";
        $range = "<input type='range' name='$param' class='settings_input_value $param' value='$value' $atts />";

        return $head.$label.$range;
    }

    public static function render_input_control( $settings, $value ) {
        $param = esc_attr($settings['param_name']);
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? "<label>".esc_attr($settings['label'])."</label>" : "";
        $placeholder = esc_attr($settings['placeholder']);

        return $head.$label."<input type='text' name='$param' class='settings_input_value $param' value='$value' placeholder='$placeholder' />";
    }
    
    public static function render_checkbox_control( $settings, $value ) {
        $param = esc_attr($settings['param_name']);
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? esc_attr($settings['label']) : "";
        $value = ($value == 'true') ? "checked='checked'" : '';

        return $head."<label><input type='checkbox' name='$param' class='settings_input_value $param' $value />$label</label>";
    }
    
    public static function render_select_control( $settings, $value ) {
        $param = esc_attr($settings['param_name']);
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? "<label>".esc_attr($settings['label'])."</label>" : "";
        $select = "<select name='$param' class='settings_input_value $param' data-option='$value'>";
        foreach ($settings['options'] as $title => $id)
            $select .= "<option value='".$id."' ".selected($id, $value, false).">".$title."</option>";
        $select .= "</select>"; 
        $description = (isset($settings['description']) && !empty($settings['description'])) ? "<i class='descr'>".esc_attr($settings['description'])."</i>" : "";

        return $head.$label.$select.$description;
    }

    public static function render_colorselect_control( $settings, $value ) {
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? "<label>".esc_attr($settings['label'])."</label>" : "";
        $colorselect = \vc\defaults::render_colorselect_control( $settings, $value, 'settings_input_value' );

        return $head."<div class='vc_shortcode-param edit_form_line'>".$label.$colorselect."</div>";
    }

    public static function render_shadow_control( $settings, $value ) {
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? "<label>".esc_attr($settings['label'])."</label>" : "";
        $shadow = \vc\defaults::render_shadow_control( $settings, $value, 'settings_input_value' );

        return $head."<div class='vc_shortcode-param edit_form_line'>".$label.$shadow."</div>";
    }

    // settings controls
    public static function render_rswitch_setting( $settings, $value ) {
        $param = esc_attr($settings['param_name']);
        $val = isset($value['value']) ? $value['value'] : $settings['default'];
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? "<label>".esc_attr($settings['label'])."</label>" : "";
        $input = "<input type='hidden' name='$param' class='settings_input_value $param' value='$val'>";

        $radio = "<select>";
        foreach ($settings['radio'] as $title => $id)
            $radio .= "<option value='".$id."' ".selected($id, $val, false).">".$title."</option>";
        $radio .= "</select>";
        $radio = "<div class='settings_options'>".$radio."</div>";
    
        $class = (isset($settings['class']) && !empty($settings['class'])) ? $settings['class'] : "";
        $options = "";
        if (isset($settings['params'])) {
            $options = "<div class='settings_input_options ".$class."' style='display:none;' data-param_name='".$param."'>
                            ".self::render_setting_params($settings['params'], $value)."
                        </div>";
        }

        return "<div class='settings_input_switch'>".$head.$label.$radio."</div>".$input.$options;
    }
    public static function render_switch_setting( $settings, $value ) {
        $param = esc_attr($settings['param_name']);
        $val = isset($value['value']) ? $value['value'] : $settings['default'];
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $label = (isset($settings['label']) && !empty($settings['label'])) ? "<label>".esc_attr($settings['label'])."</label>" : "";
        $input = "<input type='hidden' name='$param' class='settings_input_value $param' value='$val'>";
        
        $slide = "<div class='greyd_switch'><label>
                    <span>&nbsp;</span><span>
                    <input type='checkbox' ".($val != 'off' ? 'checked="checked"' : '').">
                    <span>&nbsp;</span></span>
                </label></div>";

        $class = (isset($settings['class']) && !empty($settings['class'])) ? $settings['class'] : "";
        $options = "";
        if (isset($settings['params'])) {
            if (strpos($label, '%s') !== false) {
                $pname = $settings['params'][0]['param_name'];
                $poptions = isset($value['options']) ? (array)$value['options'] : array();
                $pval = isset($poptions[$pname]) ? $poptions[$pname] : $settings['params'][0]['default'];
                $pinput = self::render_settings_option($settings['params'][0], $pval, $pname);
                $label = str_replace('%s', $pinput, $label);
            }
            else {
                $options = "<div class='settings_input_options ".$class."' style='display:none;' data-param_name='".$param."'>
                                ".self::render_setting_params($settings['params'], $value)."
                            </div>";
            }
        }

        return "<div class='settings_input_switch'>".$head.$label.$slide."</div>".$input.$options;
    }
    public static function render_setting_params( $params, $value ) {
        $value = isset($value['options']) ? (array)$value['options'] : array();
        $options = "";
        foreach ($params as $param) {
            $name = esc_attr($param['param_name']);
            $val = isset($value[$name]) ? $value[$name] : $param['default'];
            $class = (isset($param['class']) && $param['class'] != "") ? $param['class'] : "";
            $options .= "<div class='settings_input_option ".$param['type']." ".$class."' data-param_name='".$name."'>";
            if (isset($param['label']) && $param['label'] != "") $options .= "<label class='head_label'>".esc_attr($param['label'])."</label>";
            
            $options .= self::render_settings_option($param, $val, $name);
            
            if (isset($param['description']) && $param['description'] != "") $options .= "<label class='description_label'>".$param['description']."</label>";
            $options .= "</div>";
        }
        return $options;
    }
    
    public static function render_settings_option( $param, $val, $name ) {
        $return = "";
        if ($param['type'] == 'autotags') {
            $return .= "<input type='hidden' name='".$name."' class='settings_input_option_value' value='".$val."' data-tags='".json_encode($param['values'])."' />";
        }
        else if ($param['type'] == 'checkbox') {
            $vals = explode(',', $val);
            $boxes = "";
            $final_val = array();
            foreach ($param['values'] as $title => $id) {
                $checked = "";
                if (in_array($id, $vals)) {
                    $checked = 'checked="checked"';
                    $final_val[] = $id;
                }
                $boxes .= "<label><input type='checkbox' name='".$id."' $checked />".$title."</label>";
            }
            $final_val = implode(',', $final_val);
            $return .= "<input type='hidden' name='".$name."' class='settings_input_option_value' value='".$final_val."' />".$boxes;
        }
        else if ($param['type'] == 'textfield') {
            $placeholder = (isset($param['placeholder']) && $param['placeholder'] != "") ? "placeholder='".esc_attr($param['placeholder'])."'" : "";
            $return .= "<input type='text' name='".$name."' class='settings_input_option_value' value='".$val."' ".$placeholder." />";
        }
        else if ($param['type'] == 'numfield') {
            $placeholder    = (isset($param['placeholder']) && $param['placeholder'] != "") ? "placeholder='".esc_attr($param['placeholder'])."'" : "";
            $steps          = (isset($param['steps']) && $param['steps'] != "") ? "steps='".esc_attr($param['steps'])."'" : "";
            $max            = (isset($param['max']) && $param['max'] != "") ? "max='".esc_attr($param['max'])."'" : "";
            $min            = (isset($param['min']) && $param['min'] != "") ? "min='".esc_attr($param['min'])."'" : "";
            $return .= "<input type='number' name='".$name."' class='settings_input_option_value' value='".$val."' ".$placeholder." ".$steps." ".$min." ".$max." />";
        }
        else if ($param['type'] == 'select') {
            $return .= "<select name='".$name."' class='settings_input_option_value'>";
            foreach ($param['options'] as $title => $id)
                $return .= "<option value='".$id."' ".selected($id, $val, false).">".$title."</option>";
            $return .= "</select>"; 
        }
        return $return;
    }

    public static function render_checkbox_setting( $settings, $value ) {
        $val = isset($value['value']) ? $value['value'] : $settings['default'];
        $input = self::render_checkbox_control( $settings, $val );
        $description = (isset($settings['description']) && !empty($settings['description'])) ? "<span class='description_label'>".$settings['description']."</span>" : "";
        return "<div class='settings_input_element'>".$input.$description."</div>";
    }

    public static function render_select_setting( $settings, $value ) {
        $val = isset($value['value']) ? $value['value'] : $settings['default'];
        $description = (isset($settings['description']) && !empty($settings['description'])) ? "<span class='description_label'>".$settings['description']."</span>" : "";
        unset($settings['description']);
        $input = self::render_select_control( $settings, $val );
        return "<div class='settings_input_element'>".$input.$description."</div>";
    }
    
    public static function render_info_setting( $settings, $value ) {
        // debug($settings);
        $head = (isset($settings['head']) && !empty($settings['head'])) ? "<span class='head_label'>".esc_attr($settings['head'])."</span>" : "";
        $text  = isset($settings['label']) ? $settings['label'] : '';
        // return "<div class='settings_input_switch'>".$head.\vc\helper::render_info_box( $atts )."</div>";
        $return = "<div class='settings_input_switch'>".$head."<div class='info_toggle'><span class='dashicons dashicons-info'></div></div>";
        $return .= "<div class='settings_input_options' style='display:none'>".$text."</div>";
        return $return;
    }


    /*
    ====================================================================================
        Frontend
    ====================================================================================
    */
    // visual composer
    public function popup_close_vc() {
        
        vc_map(array(
            "name"          => __('Pop-up schließen', 'core'),
             "description"   => __('X-Button zum Schließen von Pop-ups', 'core'),
            "base"          => "vc_close",
            "category"      => __('Inhalt', 'core'),
            "icon"          => get_template_directory_uri()."/assets/icon/close.png",
            "params"        => array(
                array(
                    "type"          => "seperator",
                    "heading"       => __('Allgemein', 'core'),
                    "param_name"    => "seperator_basic",
                ),
                // alignment
                array(
                    "type"          => "dropdown",
                    "heading"       => __('Ausrichtung', 'core'),
                    "param_name"    => "align",
                    'admin_label'   => true,
                    "value"         => array(
                        _x('linksbündig', 'small', 'core')  => '',
                        _x('zentriert', 'small', 'core') => '_center',
                        _x('rechtsbündig', 'small', 'core') => '_right',
                    ),
                    'edit_field_class' => 'vc_col-xs-6',
                ),
                array(
                    "type"          => "close_preview",
                    "heading"       => __('Vorschau', 'core'),
                    "param_name"    => "preview",
                    "values"        => array(
                        'align','size', 'width', 'color', 'color_hover', 'as_box', 'padding', 'border_radius', 'color_bg', 'color_bg_hover'
                    ),
                    'edit_field_class' => 'vc_col-xs-6',
                ),
                array(
                    'type'          => 'range',
                    'param_name'    => 'size',
                    'input_attrs'   => array( "min" => 0, "max" => 100, "step" => 1 ),
                    'label'         => array( "lbl" => __('Größe: ', 'core'), "unit" => "px" ),
                    'value'         => '40',
                    'edit_field_class' => 'vc_col-xs-6',
                ),
                array(
                    'type'          => 'range',
                    'param_name'    => 'width',
                    'input_attrs'   => array( "min" => 0, "max" => 20, "step" => 1 ),
                    'label'         => array( "lbl" => __('Stärke: ', 'core'), "unit" => "px" ),
                    'value'         => '4',
                    'edit_field_class' => 'vc_col-xs-6',
                ),
                // Color
                array(
                    "type"          => "colorselect",
                    "heading"       => __('Farbe', 'core'),
                    "param_name"    => "color",
                    'value'         => 'color_21',
                    'edit_field_class' => 'vc_col-xs-6',
                ),
                array(
                    "type"          => "colorselect",
                    "heading"       => __('Farbe Hover', 'core'),
                    "param_name"    => "color_hover",
                    // 'value'         => 'color_23',
                    'edit_field_class' => 'vc_col-xs-6',
                ),

                // Box
                array(
                    "type"        => 'sub_seperator',
                    "heading"     => __('Box', 'core'),
                    "param_name"  => 'seperator_box',
                ),
                array(
                    "type"        => "checkbox",
                    "heading"     => __("als Box gestalten", 'core'),
                    "param_name"  => "as_box",
                ),
                array(
                    'type'          => 'range',
                    'param_name'    => 'padding',
                    'input_attrs'   => array( "min" => 0, "max" => 100, "step" => 1 ),
                    'label'         => array( "lbl" => __('Padding: ', 'core'), "unit" => "px" ),
                    'value'         => '15',
                    'edit_field_class' => 'vc_col-xs-6',
                    'dependency'    => array(
                        'element'   => 'as_box',
                        'not_empty' => true
                    ),
                ),
                array(
                    'type'          => 'range',
                    'param_name'    => 'border_radius',
                    'input_attrs'   => array( "min" => 0, "max" => 100, "step" => 1 ),
                    'label'         => array( "lbl" => __('Eckenradius: ', 'core'), "unit" => "px" ),
                    'value'         => '5',
                    'edit_field_class' => 'vc_col-xs-6',
                    'dependency'    => array(
                        'element'   => 'as_box',
                        'not_empty' => true
                    ),
                ),
                // Color Box
                array(
                    "type"          => "colorselect",
                    "heading"       => __('Hintergrundfarbe', 'core'),
                    "param_name"    => "color_bg",
                    'value'         => 'color_11',
                    'edit_field_class' => 'vc_col-xs-6',
                    'dependency'    => array(
                        'element'   => 'as_box',
                        'not_empty' => true
                    ),
                ),
                array(
                    "type"          => "colorselect",
                    "heading"       => __('Hintergrundfarbe Hover', 'core'),
                    "param_name"    => "color_bg_hover",
                    'value'         => 'color_11',
                    'edit_field_class' => 'vc_col-xs-6',
                    'dependency'    => array(
                        'element'   => 'as_box',
                        'not_empty' => true
                    ),
                ),
            ),
        ));
    }
    public function mod_popup_vc() {
        $post = -1;
        if (isset($_REQUEST['post'])) $post = $_REQUEST['post'];
        else if (isset($_REQUEST['post_id'])) $post = $_REQUEST['post_id'];
        if ($post != -1) {
            if (get_post_type($post) != 'greyd_popup') {
                vc_remove_element( "vc_close" );
                $map = \WPBMap::getShortCode( 'vc_cbutton' );
                foreach ( (array) $map['params'] as $params) {
                    if ($params['param_name'] == 'style') {
                        $params['value'][_x('Pop-up öffnen', 'small', 'core')] = "popup_open";
                        vc_update_shortcode_param( 'vc_cbutton', $params );
                        break;
                    }
                }
            }
            else {
                $map = \WPBMap::getShortCode( 'vc_cbutton' );
                foreach ( (array) $map['params'] as $params) {
                    if ($params['param_name'] == 'style') {
                        $params['value'][_x('Pop-up schließen', 'small', 'core')] = "popup_close";
                        vc_update_shortcode_param( 'vc_cbutton', $params );
                        break;
                    }
                }
            }
        }
        // else vc_remove_element( "vc_close" );
    }
    public function make_color($color) {
        if ($color == "") $color = 'transparent';
        if (strpos($color, "color_") === 0) $color = 'var(--'.str_replace("_", "", $color).')';
        return $color;
    }
    public function make_value($data, $key) {
        $value = $data[$key];
        if ($value == 'custom') $value = $data[$key.'_custom'];
        if ($value != 'auto') {
            if (strpos($value, 'px') === false && strpos($value, '%') === false) {
                if (intval($value) <= 100) $value .= "%";
                else $value .= "px";
            }
        }
        return $value;
    }

    // shortcode
    public function popup_close_sc($atts, $content=null) {
        // debug($atts);
        $id = uniqid("popup_close_");
        $align = isset($atts['align']) ? esc_attr($atts['align']) : '';
        $align = str_replace("_", "", $align);
        $size = isset($atts['size']) ? esc_attr($atts['size']) : 40;
        $width = isset($atts['width']) ? esc_attr($atts['width']) : 4;
        $color = isset($atts['color']) ? esc_attr($atts['color']) : 'color_21';
        $color_hover = isset($atts['color_hover']) ? esc_attr($atts['color_hover']) : '';

        $as_box = isset($atts['as_box']) ? true : false;
        $padding = $border_radius = 0;
        $color_bg = $color_bg_hover = 'transparent';
        if ($as_box) {
            $padding = isset($atts['padding']) ? esc_attr($atts['padding']) : 15;
            $border_radius = isset($atts['border_radius']) ? esc_attr($atts['border_radius']) : 5;
            $color_bg = isset($atts['color_bg']) ? esc_attr($atts['color_bg']) : 'color_11';
            $color_bg_hover = isset($atts['color_bg_hover']) ? esc_attr($atts['color_bg_hover']) : 'color_11';
        }

        // make style
        $inline_style = 
            "#".$id." { 
                width: ".$size."px;
                height: ".$size."px;
                padding: ".$padding."px;
                border-radius: ".$border_radius."px;
                background-color: ".$this->make_color($color_bg).";
            }
            #".$id.":hover {
                background-color: ".$this->make_color($color_bg_hover).";
            }
            #".$id." .close_popup:before,
            #".$id." .close_popup:after { 
                left: ".(($size-$width)/2.0)."px;
                height: ".$size."px;
                width: ".$width."px;
                background-color: ".$this->make_color($color).";
            }";
        if ( !empty($color_hover) ) {
            $inline_style .=
               "#".$id.":hover .close_popup:before,
                #".$id.":hover .close_popup:after { 
                    background-color: ".$this->make_color($color_hover).";
                }";
        };

        ob_start();

        // custom css
        \enqueue::add_custom_style($inline_style);
        
        echo "<div class='".$align."'>
                <div id='".$id."' class='close_popup_wrapper animate_fast' onclick='popups.close(this)'>
                    <span class='close_popup animate_fast'></span>
                </div>
            </div>";
            
		$return = ob_get_contents();
		ob_end_clean();
		return $return;
    }
    // render popup
    public function render_popup() {
        
        $popups = self::check_popup();
        if ($popups) {
            $style = "";
            $content = "";
            foreach ($popups as $popup) {

                if (isset($popup['design']['version']) && $popup['design']['version'] > 1) {
                    // only original v1 popups can be rendered.
                    continue;
                }

                $id = "popup_".$popup['id'];
                $slug = \vc\helper::get_clean_slug(esc_attr($popup['title']));
                $class = $popup['design']['css_class'];

                // position
                $p = $popup['design']['position'];
                $jc = ($p=='tl' || $p=='ml' || $p=='bl') ? 'flex-start' : (($p=='tc' || $p=='mc' || $p=='bc') ? 'center' : 'flex-end');
                $ai = ($p=='tl' || $p=='tc' || $p=='tr') ? 'flex-start' : (($p=='ml' || $p=='mc' || $p=='mr') ? 'center' : 'flex-end');

                // width height and alignment
                $width = $this->make_value($popup['design'], 'width');
                $height = $this->make_value($popup['design'], 'height');
                $align = "flex-start";
                if ($height != 'auto') {
                    $align = ($popup['design']['align'] == 'top') ? 'flex-start' : (($popup['design']['align'] == 'middle') ? 'center' : 'flex-end');
                }
                $inner_width = ($popup['design']['margin_lr'] > 0) ? "calc(100% - ".(2*$popup['design']['margin_lr'])."px)" : "100%";
                $inner_height = ($popup['design']['margin_tb'] > 0) ? "calc(100% - ".(2*$popup['design']['margin_tb'])."px)" : "100%";
                $inner_width_max = ($popup['design']['margin_lr'] > 0) ? "calc(100vw - ".(2*$popup['design']['margin_lr'])."px)" : "100vw";
                $inner_height_max = ($popup['design']['margin_tb'] > 0) ? "calc(100vh - ".(2*$popup['design']['margin_tb'])."px)" : "100vh";

                // mobile
                $mobile_width = $this->make_value($popup['design'], 'mobile_width');
                $mobile_height = $this->make_value($popup['design'], 'mobile_height');
                $mobile_align = "flex-start";
                if ($mobile_height != 'auto') {
                    $mobile_align = ($popup['design']['mobile_align'] == 'top') ? 'flex-start' : (($popup['design']['mobile_align'] == 'middle') ? 'center' : 'flex-end');
                }
                $mobile_inner_width = ($popup['design']['mobile_margin_lr'] > 0) ? "calc(100% - ".(2*$popup['design']['mobile_margin_lr'])."px)" : "100%";
                $mobile_inner_height = ($popup['design']['mobile_margin_tb'] > 0) ? "calc(100% - ".(2*$popup['design']['mobile_margin_tb'])."px)" : "100%";
                $mobile_inner_width_max = ($popup['design']['mobile_margin_lr'] > 0) ? "calc(100vw - ".(2*$popup['design']['mobile_margin_lr'])."px)" : "100vw";
                $mobile_inner_height_max = ($popup['design']['mobile_margin_tb'] > 0) ? "calc(100vh - 50px - ".(2*$popup['design']['mobile_margin_tb'])."px)" : "calc(100vh - 50px)";

                // textcolor
                $color = $this->make_color($popup['design']['text_color']);
                $color_hover = $this->make_color($popup['design']['hover_text_color']);
                // headline color
                $head = $this->make_color($popup['design']['head_color']);
                $head_hover = $this->make_color($popup['design']['hover_head_color']);
                // background color
                $background = $this->make_color($popup['design']['bg_color']);
                $background_hover = $this->make_color($popup['design']['hover_bg_color']);
                // border
                $border = $border_hover = "none";
                if ($popup['design']['border_enable'] == 'true') {
                    $bcolor = $this->make_color($popup['design']['border_color']);
                    $border = $popup['design']['border_width']."px ".$popup['design']['border_style']." ".$bcolor;
                    $bcolor_hover = $this->make_color($popup['design']['hover_border_color']);
                    $border_hover = $popup['design']['border_width']."px ".$popup['design']['border_style']." ".$bcolor_hover;
                }
                // shadow
                $shadow = $shadow_hover = "none";
                if ($popup['design']['shadow_enable'] == 'true') {
                    $shadow = \vc\helper::get_shadow($popup['design'], 'shadow');
                    $shadow_hover = \vc\helper::get_shadow($popup['design'], 'hover_shadow');
                }

                // transition
                $transition_prop = "opacity, top, left";
                $transition_time = strval( intval($popup['design']['anim_time']) / 1000.0 ) . "s";

                // make style
                $inline_style = 
                    "#".$id." { 
                        justify-content: ".$jc.";
                        align-items: ".$ai.";
                        will-change: $transition_prop;
                        transition-property: $transition_prop;
                        transition-duration: $transition_time;
                    }";
                // basic
                $inline_style .= 
                    "#".$id." .popup_content { 
                        width: ".$width.";
                        height: ".$height.";
                    }
                    #".$id." .popup_content .popup_wrapper { 
                        justify-content: ".$align.";
                        width: ".$inner_width.";
                        height: ".$inner_height.";
                        max-width: ".$inner_width_max.";
                        max-height: ".$inner_height_max.";
                        margin: ".$popup['design']['margin_tb']."px ".$popup['design']['margin_lr']."px;
                        padding: ".$popup['design']['padding_tb']."px ".$popup['design']['padding_lr']."px;
                        border-radius: ".$popup['design']['border_radius']."px;
                        overflow: ".$popup['design']['overflow'].";
                        color: ".$color.";
                        background-color: ".$background.";
                        border: ".$border.";
                        box-shadow: ".$shadow.";
                        transition-duration: $transition_time;
                    } ";
                $inline_style .= 
                    "#".$id." .popup_content h1, 
                    #".$id." .popup_content h2,
                    #".$id." .popup_content h3,
                    #".$id." .popup_content h4,
                    #".$id." .popup_content h5,
                    #".$id." .popup_content h6 { 
                        color: ".$head.";
                    } ";
                // hover
                if ($popup['design']['hover_enable'] == 'true') {
                    $inline_style .= 
                        "#".$id." .popup_content:hover .popup_wrapper { 
                            color: ".$color_hover.";
                            background-color: ".$background_hover.";
                            border: ".$border_hover.";
                            box-shadow: ".$shadow_hover.";
                        } ";
                    $inline_style .= 
                        "#".$id." .popup_content:hover h1, 
                        #".$id." .popup_content:hover h2,
                        #".$id." .popup_content:hover h3,
                        #".$id." .popup_content:hover h4,
                        #".$id." .popup_content:hover h5,
                        #".$id." .popup_content:hover h6 { 
                            color: ".$head_hover.";
                        } ";
                }
                // mobile
                if ($popup['design']['mobile_enable'] == 'true') {
                    $inline_style .= 
                        "@media (max-width: var(grid_md)) { 
                            #".$id." .popup_content { 
                                width: ".$mobile_width.";
                                height: ".$mobile_height.";
                            }
                            #".$id." .popup_content .popup_wrapper { 
                                justify-content: ".$mobile_align.";
                                width: ".$mobile_inner_width.";
                                height: ".$mobile_inner_height.";
                                max-width: ".$mobile_inner_width_max.";
                                max-height: ".$mobile_inner_height_max.";
                                margin: ".$popup['design']['mobile_margin_tb']."px ".$popup['design']['mobile_margin_lr']."px;
                                padding: ".$popup['design']['mobile_padding_tb']."px ".$popup['design']['mobile_padding_lr']."px;
                            } 
                        } ";
                }

                // overlay
                $overlay_click = "";
                $overlay_effekt = "";
                if ($popup['design']['overlay_enable'] == 'true') {
                    // overlay color
                    $overlay = $this->make_color($popup['design']['overlay_color']);
                    $opacity = $popup['design']['overlay_opacity']/100.0;
                    $inline_style .= 
                        "#$id .popup_overlay { 
                            top: 0; left: 0; width: 100%; height: 100%;
                            background-color: $overlay;
                            opacity: $opacity;
                            will-change: $transition_prop;
                            transition-property: $transition_prop;
                            transition-duration: $transition_time;
                        } ";
                    $overlay_effekt .= " data-opacity='".$opacity."'";
                    if ($popup['design']['overlay_effect'] != 'none') {
                        $effect = $popup['design']['overlay_effect'];
                        $value = $popup['design']['overlay_effect_'.$effect];
                        $unit = "%";
                        if ($effect == 'blur') $unit = "px";
                        if ($effect == 'brightness') $unit = "";
                        if ($effect == 'hue-rotate') $unit = "deg";
                        $overlay_effekt .= " data-effect='".$effect."(".$value.$unit.")'";
                    }
                    if ($popup['design']['overlay_noscroll'] == 'true') {
                        $overlay_effekt .= " data-noscroll='true'";
                    }
                    if ($popup['design']['overlay_close'] == 'true') 
                        $overlay_click .= " onclick='popups.close(this)'";
                }

                // animation
                $animation = "";
                if ($popup['design']['anim_type'] != 'none') {
                    $animation .= "data-anim_type='".$popup['design']['anim_type']."'";
                    $animation .= " data-anim_time='".$popup['design']['anim_time']."'";
                    if ($popup['design']['anim_type'] == 'fade') {
                        $inline_style .= "#".$id." { opacity: 0; } ";
                    }
                    else if ($popup['design']['anim_type'] == 'slide_top') {
                        $inline_style .= "#".$id." { top: -100%; } ";
                        $inline_style .= "#".$id." .popup_overlay { top: 100%; opacity: 0; } ";
                    }
                    else if ($popup['design']['anim_type'] == 'slide_bottom') {
                        $inline_style .= "#".$id." { top: 100%; } ";
                        $inline_style .= "#".$id." .popup_overlay { top: -100%; opacity: 0; } ";
                    }
                    else if ($popup['design']['anim_type'] == 'slide_left') {
                        $inline_style .= "#".$id." { left: -100%; } ";
                        $inline_style .= "#".$id." .popup_overlay { left: 100%; opacity: 0; } ";
                    }
                    else if ($popup['design']['anim_type'] == 'slide_right') {
                        $inline_style .= "#".$id." { left: 100%; } ";
                        $inline_style .= "#".$id." .popup_overlay { left: -100%; opacity: 0; } ";
                    }
                    else {
                        $inline_style .= "#".$id." .popup_overlay { opacity: 0; } ";
                        if ($popup['design']['anim_type'] == 'scale')
                            $inline_style .= "#".$id." .popup_content .popup_wrapper { transform: scale(0); } ";
                        else if ($popup['design']['anim_type'] == 'flip_vertical')
                            $inline_style .= "#".$id." .popup_content .popup_wrapper { transform: rotateY(90deg); } ";
                        else if ($popup['design']['anim_type'] == 'flip_horizontal')
                            $inline_style .= "#".$id." .popup_content .popup_wrapper { transform: rotateX(90deg); } ";
                        else if ($popup['design']['anim_type'] == 'flip_3d')
                            $inline_style .= "#".$id." .popup_content .popup_wrapper { transform: rotate3d(1,1,1,240deg) scale(0); } ";
                    }
                }
                // trigger, conditions and more
                $trigger = "data-trigger='".json_encode($popup['trigger'])."'";
                $conditions = "data-conditions='".json_encode($popup['conditions'])."'";
                $more = "";
                if ($popup['highest'] == 'true') $more .= "data-highest='true'";
                if ($popup['hashtag'] == 'true') $more .= " data-hashtag='true'";
                if ($popup['once'] == 'true') {
                    $more .= " data-once='true'";
                    $more .= " data-cookie='seen".$id."'";
                }
                
                // fix css
                $style .= \vc\helper::get_vc_custom_css($popup['content']);
                
                $style .= $inline_style;

                $post_content = has_blocks($popup['content']) ? apply_filters( 'the_content', $popup['content'] ) : do_shortcode($popup['content']);
                $content .= "<div id='".$id."' name='".$slug."' class='popup ".$class." hidden' ".$animation." ".$trigger." ".$conditions." ".$more.">
                                <div class='popup_overlay' ".$overlay_click." ".$overlay_effekt." ></div>
                                <div class='popup_content animate_fast'>
                                    <div class='popup_wrapper animate_fast'>".$post_content."</div>
                                </div>
                            </div>";
            }

            global $config;

            // add style
            wp_register_style( 'popups_css', get_template_directory_uri().'/assets/css/deprecated/popups_frontend.css', null, $config->theme_version, 'all' );
            wp_enqueue_style('popups_css');
            \enqueue::add_custom_style($style);

            // add script
            wp_register_script('popups_js', get_template_directory_uri().'/assets/js/deprecated/popups.js', array('jquery'), $config->theme_version, false);
            wp_enqueue_script('popups_js');
            
            // return html
            echo "<section class='popups' aria-label='Popups'>".$content."</section>";
        }
    }
    
    // public static function popup_enqueue() {
    //     $content = enqueue::get_enqueue_content();
    //     debug( esc_attr($content) );
    //     $buttons = \vc\helper::get_shortcodes($content, array( 'vc_cbutton' ));
    //     // debug($buttons);
    //     self::$popup_ids = array();
    //     if ($buttons) {
    //         foreach ($buttons as $button) {
    //             if ($button['atts'] != "") {
    //                 foreach ($button['atts'] as $att) {
    //                     // debug($att['key'].' = '.$att['value']);
    //                     if ($att['key'] == 'popup') {
    //                         self::$popup_ids[] = $att['value'];
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }
    public static function check_popup() {

        // debug(self::$popup_ids);
        if (is_customize_preview()) return false;

        $post_categories = array();
        if ( is_404() ) {
            $post_type  = 'system';
            $post_id    = '404';
        }
        else if ( is_search() ) {
            $post_type  = 'system';
            $post_id    = 'search';
        }
        else if ( is_archive() ) {
            $post_type  = get_post_type();
            $post_id    = 'archive';
            if ( !$post_type && is_tax() ) {
                $queried_obj = get_queried_object();
                if ( isset($queried_obj->taxonomy) ) {
                    $tax_slug = $queried_obj->taxonomy;
                    global $wp_taxonomies;
                    $post_type = isset( $wp_taxonomies[$tax_slug] ) ? $wp_taxonomies[$tax_slug]->object_type[0] : '';
                }
            }
        }
        else {
            $post_type  = get_post_type();
            $post_id    = get_the_ID();
            if ( $post_type != 'page' ) {
                $categories = \vc\helper::get_categories(get_post());
                if (isset($categories) && is_array($categories) && count($categories) > 0) {
                    foreach ($categories as $category) {
                        array_push($post_categories, "cat_".$category->term_id);
                    }
                }
            }
        }
        // debug($post_id);
        // debug($post_type);
        // debug($post_categories);

        $popups = array();
        $posts = \vc\helper::get_all_posts('greyd_popup', false);
        
        foreach($posts as $popup) {
            $show_popup = false;
            $meta_settings = (array)get_post_meta($popup->id, 'popup_settings', true);
            foreach( $meta_settings as $k => $v ) {
                if ( is_array($v) && isset($v['options']) ) $v['options'] = (object)$v['options'];
                $meta_settings[$k] = (object)$v;
            }

            // popup is enqueued via content
            if ( isset(self::$popup_ids[$popup->id]) || isset(self::$popup_ids[$popup->slug]) ) {
                $show_popup = true;
            }
            // check posttype condition
            else {
                // debug($meta_settings);
                if (isset($meta_settings['on_'.$post_type])) {
                    $meta = $meta_settings['on_'.$post_type];
                    if (isset($meta->value) && $meta->value != "off") {
                        $show_popup = $meta->value == "on" ? true : false;
                        if ($meta->value == "custom") {
                            // check custom selection
                            if (isset($meta->options)) {
                                if ( isset($meta->options->show_on) && $meta->options->show_on != "" ) {
                                    $on = explode(',', $meta->options->show_on);
                                    if (in_array($post_id, $on)) {
                                        $show_popup = true;
                                    }
                                }
                                if (isset($meta->options->items) && $meta->options->items != "") {
                                    $on = explode(',', $meta->options->items);
                                    if (in_array($post_id, $on)) {
                                        $show_popup = true;
                                    }
                                    else if (count($post_categories) > 0) {
                                        foreach ($post_categories as $cat) {
                                            if (in_array($cat, $on)) 
                                                $show_popup = true;
                                        }
                                    }
                                }
                            }
                        }
                        if ($show_popup) {
                            // check time condition
                            $time = ($meta_settings['time']->value == 'off') ? 'off' : explode(',', $meta_settings['time']->options->select);
                            if (is_array($time)) {
                                if (in_array('custom', $time)) {
                                    $custom = strtolower(preg_replace("/\s/", "", $meta_settings['time']->options->custom));
                                    $time = array_merge($time, explode(',', $custom));
                                }
                                $show_popup = false;
                                $now = date("H");
                                foreach ($time as $t) {
                                    if ($t == 'custom') continue;
                                    $t = explode("-", $t); // explode start-end to ["start","end"]
                                    if (!isset($t[1])) $t[1] = $t[0]+1; // if only no end isset -> use start+1 (12 -> 12-13)
                                    if ( intval($t[0]) <= $now && $now < intval($t[1]) ) {
                                        $show_popup = true;
                                        break;
                                    }
                                }
    
                            }
                        }
                        if ($show_popup) {
                            // check user condition
                            $user = ($meta_settings['user']->value == 'off') ? 'off' : explode(',', $meta_settings['user']->options->select);
                            if (is_array($user)) {
                                $show_popup = false;
                                $me = is_user_logged_in() ? wp_get_current_user()->roles : array("none");
                                $flipped = array_flip($me); // get userroles as keys of array
                                foreach ($user as $u) {
                                    if (isset($flipped[$u])) { // check if key isset
                                        $show_popup = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if ($show_popup) {
                            // check url-param condition
                            $urlparam = ($meta_settings['urlparam']->value == 'off') ? 'off' : (array)$meta_settings['urlparam']->options;
                            if (is_array($urlparam)) {
                                $show_popup = false;
                                $params = class_exists("url_handler") ? \url_handler::get_all_url_values() : array(); // get all url_params
                                // debug($params);
                                $should = $urlparam['value'];
                                $is = isset($params[$urlparam['name']]) ? $params[$urlparam['name']] : NULL;
                                if ($urlparam['condition'] === "is") {
                                    if ($should === $is) $show_popup = true;
                                } 
                                else if ($urlparam['condition'] === "is_not") {
                                    if ($should !== $is) $show_popup = true;
                                } 
                                else if ($urlparam['condition'] === "has") {
                                    if (strpos($is, $should) !== false) $show_popup = true;
                                } 
                                else if ($urlparam['condition'] === "empty") {
                                    if (empty($is)) $show_popup = true;
                                } 
                                else if ($urlparam['condition'] === "not_empty") {
                                    if (!empty($is)) $show_popup = true;
                                }
                            }
                        }
                        if ($show_popup) {
                            // check site cookie if setting 'once' is enabled
                            if ( $meta_settings['once']->value === "true" && isset($_COOKIE["seenpopup_".$popup->id]) && $_COOKIE["seenpopup_".$popup->id] === "true" ) {
                                $show_popup = false;
                            }
                        }
                    }
                }
            }
            // debug( $show_popup );

            if ($show_popup) {
                // debug($meta_settings);
                $popup_sets = (array)$popup;
                $popup_sets['prio'] = $meta_settings['prio']->value;
                $popup_sets['date'] = get_post_field('post_date', $popup->id);
                $popup_sets['highest'] = $meta_settings['highest']->value;
                $popup_sets['hashtag'] = $meta_settings['hashtag']->value;
                $popup_sets['once'] = $meta_settings['once']->value;
                $popup_sets['content'] = get_post_field('post_content', $popup->id);
                $popup_sets['trigger'] = array( 'on_init' => 'off',  'on_scroll' => 'off',  'on_idle' => 'off',  'on_exit' => 'off' );
                $popup_sets['conditions'] = array( 'delay' => 'off',  'referer' => 'off',  'device' => 'off',  'browser' => 'off' );
                if (!in_array($popup->id, self::$popup_ids)) {
                    $popup_sets['trigger'] = array(
                        'on_init' => ($meta_settings['on_init']->value == 'off') ? 'off' : $meta_settings['on_init']->options->time,
                        'on_scroll' => ($meta_settings['on_scroll']->value == 'off') ? 'off' : $meta_settings['on_scroll']->options->height,
                        'on_idle' => ($meta_settings['on_idle']->value == 'off') ? 'off' : $meta_settings['on_idle']->options->time,
                        'on_exit' => $meta_settings['on_exit']->value,
                    );
                    $popup_sets['conditions'] = array(
                        'delay' => ($meta_settings['delay']->value == 'off') ? 'off' : $meta_settings['delay']->options->count,
                        'referer' => ($meta_settings['referer']->value == 'off') ? 'off' : (array)$meta_settings['referer']->options,
                        'device' => ($meta_settings['device']->value == 'off') ? 'off' : explode(',', $meta_settings['device']->options->select),
                        'browser' => ($meta_settings['browser']->value == 'off') ? 'off' : explode(',', $meta_settings['browser']->options->select),
                    );
                }
                $popup_sets['design'] = (array)get_post_meta($popup->id, 'popup_design', true);
                $popups[] = $popup_sets;
            }
        }
        
        usort($popups, function($a, $b) {
            if ($a['prio'] != $b['prio']) return intval($a['prio']) - intval($b['prio']);
            else return strtotime($a['date']) - strtotime($b['date']);
        });
        // debug($popups);
        return (count($popups) > 0) ? $popups : false;
    }

}