<?php
/*
    Scripts PHP
*/
if( ! defined( 'ABSPATH' ) ) exit;

new enqueue();
class enqueue {
    
    public function __construct() {

        // frontend
        add_action( 'wp_enqueue_scripts', array($this, 'load_scripts_head') );
        add_action( 'wp_footer', array($this, 'load_scripts_footer'), 1 );
        add_action( 'wp_footer', array($this, 'render_custom_styles'), 2 );
		add_action( 'wp_print_styles', array($this, 'dequeue_dashicons_style'), 100 );

        // backend
        add_action( 'admin_enqueue_scripts', array($this, 'load_admin_scripts'), 90 );
    }
    
    /**
     * Load scripts and styles in the head
     */
    public function load_scripts_head() {

        // root them style
        wp_enqueue_style('default_style', get_stylesheet_uri());
        wp_process_style('default_style', get_template_directory().'/assets/css/root.css');

        // icons CSS
        echo '<link rel="preload" href="'.get_template_directory_uri().'/assets/font/ElegantIcons.ttf" as="font" />';

		if ( ! class_exists( '\Greyd\Icons' ) ) {
			wp_register_style('elegant_icons', get_template_directory_uri().'/assets/font/elegant_icons.css', null, '1.0', 'all');
			wp_enqueue_style('elegant_icons');
		}

        // deprecated theme style
        if ( !is_greyd_blocks() ) {
            wp_process_style('default_style', get_template_directory().'/assets/css/deprecated/style.css');
        }

        // main theme style
        wp_process_style('default_style', get_template_directory().'/assets/css/style.css');

        // deprecated additional style
        if ( !is_pure_greyd_blocks() || is_customize_preview() ) {
            wp_process_style('default_style', get_template_directory().'/assets/css/deprecated/vc_styles.css');
        }

        // theme helper style
        if ( !is_greyd_blocks() ) {
            wp_process_style('default_style', get_template_directory().'/assets/css/deprecated/helper.css');
        } else {
            wp_process_style('default_style', get_template_directory().'/assets/css/helper.css');
        }
    }
    
    /**
     * Load scripts and styles in the footer
     */
    public function load_scripts_footer() {
        global $config;

        // JS
        wp_register_script('default_js', get_template_directory_uri().'/assets/js/default.js', array('jquery'), $config->theme_version, false);

        /**
         * bodymovin frontend
         * deprecated and moved to Plugin.
         * Plugin checks for registered script, so this is used until removed here.
         */
        $data = (array) $config->settings;
        $lottie_uri = get_template_directory_uri().'/libs/lottie.min.js';
        if ( $data['site']['lottie']['mode'] === 'default' ) {
            wp_register_script('bodymovin_js', $lottie_uri, array('jquery'), '5.5.9', true);
            wp_enqueue_script('bodymovin_js');
        }
        /**
         * deprecated - Plugin uses new global frontend var for settings 'greyd.setup'
         */
        wp_localize_script('default_js', 'lottie_setup', array(
            'src'     => esc_js( $lottie_uri ),
            'mode'    => esc_js( $data['site']['lottie']['mode'] ),
            'time'    => esc_js( $data['site']['lottie']['time'] ),
            'mobile'  => esc_js( $data['site']['lottie']['mobile'] ),
            'lazyload'=> esc_js( $data['site']['lazyload'] ),
        ) );

        // contentbuilder
        wp_add_inline_script( 'default_js', 'var greyd_builder = "'.basics::get_setting(array('site', 'builder')).'";', 'before' );

        // enqueue scripts
        wp_enqueue_script('default_js');
    }

	/**
	 * Dequeue Dashicons on Frontend.
	 * 
	 * @since 1.5.6
	 */
	public function dequeue_dashicons_style() {
		if ( !is_user_logged_in() ) {
			wp_deregister_style('dashicons');
		}
	}

    public function load_admin_scripts() {
        global $config;

        // admin styles
        wp_register_style( 'default_admin_css', get_template_directory_uri().'/assets/css/style_admin.css', null, $config->theme_version, 'all' );
        wp_enqueue_style('default_admin_css');
        wp_process_style('default_admin_css', get_template_directory().'/assets/css/root.css');

        if ( !is_greyd_blocks() ) wp_process_style('default_admin_css', get_template_directory().'/assets/css/deprecated/helper.css');
        else wp_process_style('default_admin_css', get_template_directory().'/assets/css/helper.css');

        // register & enqueue admin scripts
        wp_register_script('default_admin_js', get_template_directory_uri().'/assets/js/default_admin.js', array('jquery'), $config->theme_version, true);
        wp_enqueue_script('default_admin_js');

        /**
         * bodymovin backend
         * deprecated and moved to Plugin.
         * Plugin checks for registered script, so this is used until removed here.
         */
        $data = (array) $config->settings;
        if ( $data['site']['lottie']['mode'] !== 'disable' ) {
            wp_register_script('bodymovin_js', get_template_directory_uri().'/libs/lottie.min.js', array('jquery'), '5.5.9', true);
            wp_enqueue_script('bodymovin_js');
        }
        
        // global wordings for javascript files
        $wordings = array(
            "new_condition"     => __("andere Bedingung", 'core'),
            "select_image"      => __("Bitte eine Bilddatei auswählen (.svg|.png|.jpg|.gif)", 'core'),
            "select_animation"  => __("Bitte eine Animation auswählen (.json)", 'core'),
            "select_media"      => __("Bitte eine Mediendatei auswählen (.svg|.png|.jpg|.gif|.json)", 'core'),
            
            "wizard" => [
                "no_name_posttype"      => __("Bitte geben Sie einen Namen für den Post Type ein.", 'core'),
                "no_selected_posttype"  => __("Bitte wählen Sie einen zu bearbeitenden Post Type aus.", 'core'),
                "no_copy"               => __("Bitte wählen Sie ein zu kopierendes %s.", 'core'),
                "no_name"               => __("Bitte geben Sie einen Namen für das %s ein.", 'core'),
                "choose_copy"           => __("Bitte wählen Sie ein zu kopierendes Template.", 'core'),
                "set_name"              => __("Bitte geben Sie einen Namen für das Template ein.", 'core'),
                "single"                => __("Beitragseite", 'core'),
                "archives"              => __("Postarchiv", 'core'),
                "search"                => __("Suchergebnisse", 'core'),
                "for_type"              => __("Typ „%s“", 'core'),
                "for_cat"               => __("für Kategorie „%s“", 'core'),
                "main_menu"             => __("Hauptmenü", 'core'),
                "meta_menu"             => __("Metamenü", 'core'),
                "footer"                => __("Footer", 'core'),
                "fourofour"             => __("404 Seite", 'core'),
                "compatibility"         => __("Kompatibilitätsmeldung", 'core'),
                "woo_product"           => __("Produktseite", 'core'),
                "woo_product_cat"       => __("Shop-Übersicht nach Kategorie", 'core'),
                "woo_product_tag"       => __("Shop-Übersicht nach Schlagwort", 'core'),
            ],
            "template_types" => [
                'dynamic'               => __('Dynamic Templates', 'core'),
                'navigation'            => __('Navigation', 'core'),
                'single'                => __('Beitrag', 'core'),
                'archives'              => __('Archiv', 'core'),
                'search'                => __('Suche', 'core'),
                'more'                  => __('Weitere', 'core'),
                'woo'                   => __('WooCommerce', 'core')
            ],
            // wordings for vc.js
            "vc" => [
                "bg_row"        => __("Zeilenbreite: %s", 'core'),
                "bg_row_default" => _x("(Standard)", 'small', 'core'),
                "bg_color"      => __("Hintergrund: Farbe", 'core'),
                "bg_gradient"   => __("Hintergrund: Farbverlauf", 'core'),
                "bg_image"      => __("Hintergrund: Bild", 'core'),
                "bg_animation"  => __("Hintergrund: Animation", 'core'),
                "bg_video"      => __("Hintergrund: Video", 'core'),
                "bg_overlay"    => __("Hintergrund: Overlay", 'core'),
                "bg_seperator"  => __("Hintergrund: Seperator", 'core'),

                "alpha"         => __("Deckkraft: %s", 'core'),
                "position"      => __("Position: %s", 'core'),
                "gradient_max"  => __("Es können maximal 50 Farben definiert werden.", 'core'),
                "gradient_min"  => __("Es müssen mindestens zwei Farben vorhanden sein.", 'core'),
                "gradient_del"  => __("Verlaufsfarbe löschen?", 'core'),
                "gradient_pos"  => __("Neue Position in %:", 'core'),
                "set_link"      => __("Link einfügen", 'core'),
                "no_follow"     => __("nofollow Option an Link anfügen", 'core'),
        
                'animate_it'        => __("Vorschau", 'core'),
                "placeholder_dyn"   => _x("(Platzhalter)", 'small', 'core'),
                "placeholder"       => _x("(Platzhalter - optional)", 'small', 'core'),
                "edit"              => _x("Template bearbeiten", 'small', 'core'),
                "no_template"       => __("Kein Template ausgewählt", 'core'),
                "no_template_descr" => __("Bitte wähle oben im Dropdown ein Template aus, das du einbinden möchtest.", 'core'),
                "not_found"         => __("Template nicht gefunden.", 'core'),
                "not_found_descr"   => __("Das Template mit der Titelform „%s“ konnte nicht gefunden werden. Es wurde möglicherweise gelöscht oder verschoben.", 'core'),
                "no_content"        => __("Keine dynamischen Inhalte gefunden.", 'core'),
                "no_content_descr"  => __("Um Inhalte hier anzupassen, bearbeite das Template und stelle den Schieberegler in den Modulen auf „dynamisch“.", 'core'),
                "embed_template"    => __("Eingebettetes Template „%s“", 'core'),
                "duplicate"         => __("%s Duplikat gefunden", 'core'),
                "duplicates"        => __("%s Duplikate gefunden", 'core'),
                "duplicate_info"    => __("Das Element mit dem Namen „%1s“ wurde insgesamt %2sx gefunden.<br>Elemente mit demselben Namen werden mit denselben Inhalten befüllt.", 'core'),
                
                // dynamic tags
                "dynamic_tags"  => __("Dynamische Platzhalter:", 'core'),
                "tags"  => [
                    "query"         => _x("Suchbegriff", 'small', 'core'),
                    "filter"        => _x("Filter", 'small', 'core'),
                    "title"         => _x("Titel", 'small', 'core'),
                    "content"       => _x("Inhalt", 'small', 'core'),
                    "excerpt"       => _x("Auszug", 'small', 'core'),
                    "post-type"     => _x("Post Type", 'small', 'core'),
                    "author"        => _x("Autor", 'small', 'core'),
                    "date"          => _x("Datum", 'small', 'core'),
                    "category"      => _x("Kategorie", 'small', 'core'),
                    "categories"    => _x("Kategorien", 'small', 'core'),
                    "tag"           => _x("Schlagwort", 'small', 'core'),
                    "tags"          => _x("Schlagwörter", 'small', 'core'),
                    "image"         => _x("Beitragsbild", 'small', 'core'),
                    "post-link"     => _x("Link zum Beitrag", 'small', 'core'),
                    "image-link"    => _x("Link zum Beitragsbild", 'small', 'core'),
                    "author-link"   => _x("Link zum Autor", 'small', 'core'),
                    "author-email"  => _x("E-Mail des Autors", 'small', 'core'),
                    "post-count"    => _x("Anzahl der Beiträge", 'small', 'core'),
                    "posts-per-page"=> _x("Anzahl Beiträge pro Seite", 'small', 'core'),
                    "page-num"      => _x("aktuelle Seite", 'small', 'core'),
                    "page-count"    => _x("Seitenanzahl", 'small', 'core'),
                    "post-views"    => _x("Aufrufe des Beitrags", 'small', 'core'),
                    "site-title"    => _x("Website Titel", 'small', 'core'),
                    // woo
                    "price"         => _x("Preis", 'small', 'core'),
                    "vat"           => _x("Mehrwertsteuer", 'small', 'core'),
                    "cart"          => _x("Warenkorb Link", 'small', 'core'),
                    "cart-excerpt"  => _x("Warenkorb Auszug", 'small', 'core'),
                    "woo_ajax"      => _x("Ajax Button", 'small', 'core'),
                ],
                "h1"            => __("H1", 'core'),
                "h2"            => __("H2", 'core'),
                "h3"            => __("H3", 'core'),
                "h4"            => __("H4", 'core'),
                "h5"            => __("H5", 'core'),
                "h6"            => __("H6", 'core'),
                "div"           => __('keinen Tag setzen', 'core'),
                "chars"         => __("Zeichenanzahl", 'core'),
                "link"          => _x("Verlinken?", 'small', 'core'),
                "insert"        => _x("einfügen", 'small', 'core'),
                "more"          => _x("mehr", 'small', 'core'),
                "type"          => __("Art", 'core'),
                "name"          => _x("Name", 'small', 'core'),
                "email"         => _x("E-Mail", 'small', 'core'),
                "date_format"   => __("Datumsformat", 'core'),
                "date_formats"  => [
                    ''              => _x('Standardformat', 'small', 'core'),
                    'dmY'           => _x('TT.MM.JJJJ', 'small', 'core'),
                    'dmy'           => _x('TT.MM.JJ', 'small', 'core'),
                    'dm'            => _x('TT.MM', 'small', 'core'),
                    'ldmY'          => _x('Tag TT.MM.JJJJ', 'small', 'core'),
                    'ldmy'          => _x('Tag TT.MM.JJ', 'small', 'core'),
                    'ldm'           => _x('Tag TT.MM.', 'small', 'core'),
                    'jFY'           => _x('T. Monat JJJJ', 'small', 'core'),
                    'jFy'           => _x('T. Monat JJ', 'small', 'core'),
                    'jF'            => _x('T. Monat', 'small', 'core'),
                    'ljFY'          => _x('Tag T. Monat JJJJ', 'small', 'core'),
                    'ljFy'          => _x('Tag T. Monat JJ', 'small', 'core'),
                    'ljF'           => _x('Tag T. Monat', 'small', 'core'),
                    'mY'            => _x('MM.JJJJ', 'small', 'core'),
                    'my'            => _x('MM.JJ', 'small', 'core'),
                    'm'             => _x('MM', 'small', 'core'),
                    'FY'            => _x('Monat JJJJ', 'small', 'core'),
                    'Fy'            => _x('Monat JJ', 'small', 'core'),
                    'F'             => _x('Monat', 'small', 'core'),
                    'Y'             => _x('JJJJ', 'small', 'core'),
                    'y'             => _x('JJ', 'small', 'core'),
                    'Gi'            => _x('Uhrzeit (h:i)', 'small', 'core'),
                    'His'           => _x('Uhrzeit mit Sekunden (H:i:s)', 'small', 'core'),
                    'G'             => _x('Stunden', 'small', 'core'),
                    'm'             => _x('Minuten', 'small', 'core'),
                    's'             => _x('Sekunden', 'small', 'core'),
                ],
                "divider"       => __("Trennelement", 'core'),
                "dividers"      => [
                    ''              => _x('Komma (, )', 'small', 'core'),
                    'semi'          => _x('Semikolon (; )', 'small', 'core'),
                    'vert'          => _x('vertikaler Strich ( | )', 'small', 'core'),
                    'hor'           => _x('horizontaler Strich ( - )', 'small', 'core'),
                    'dot'           => _x('Punkt ( • )', 'small', 'core'),
                    'space'         => _x('Leerzeichen ( )', 'small', 'core'),
                    'br'            => _x('Zeilenumbruch', 'small', 'core')
                ],
                
                "symbol"        => __("Währungssymbol", 'core'),
                "symbols"       => [
                    ''              => _x('Standard', 'small', 'core'),
                    'after'         => _x('dahinter', 'small', 'core'),
                    'before'        => _x('davor', 'small', 'core'),
                    'afterh'        => _x('dahinter hochgestellt', 'small', 'core'),
                    'beforeh'       => _x('davor hochgestellt', 'small', 'core'),
                    'hide'          => _x('ausblenden', 'small', 'core')
                ],
                "format"        => __("Formatierung", 'core'),
                "formats"       => [
                    ''              => _x('Standard', 'small', 'core'),
                    'comma'         => _x('00,00', 'small', 'core'),
                    'none'          => _x('00', 'small', 'core')
                ],

                "redirect"      => __("Linkziel:", 'core'),
                "redirects"     => [
                    'default'       => _x('Standard', 'small', 'core'),
                    'cart'          => _x('zum Warenkorb', 'small', 'core'),
                    'checkout'      => _x('zur Kasse', 'small', 'core'),
                    'shop'          => _x('zum Shop', 'small', 'core'),
                    'false'         => _x('nicht weiterleiten', 'small', 'core'),
                    //'custom'        => _x('individueller Link', 'small', 'core')
                ],
                "not_twice"     => _x("Nicht doppelt hinzufügen", 'small', 'core'),
                "clear"         => _x("Warenkorb davor leeren", 'small', 'core'),
                "lost_values"   => [
                    "title" => __("Für folgende Inhalte konnte kein Feld mehr gefunden werden:", 'core'),
                    "info"  => __("Die Felder wurden möglicherweise gelöscht oder umbenannt. Beim Speichern deiner Änderungen, werden verwaiste Inhalte gelöscht.", 'core'),
                ]
            ],
            'tinymce' => [
                'uppercase' => __('Großbuchstaben', 'core'),
                'fontsize' => __('Schriftgröße', 'core'),
                'sizes' => \vc\helper::get_fontsize_array(),
                'colors' => \vc\helper::get_colors_array('tinymce'),
                'fontfamily' => __('Schriftart', 'core'),
                'fonts' => \vc\helper::get_font_array(),
                'styles' => \vc\helper::get_tinymce_styles(),
                'plugins' => \vc\helper::get_tinymce_plugins()
            ]
        );
        
        // add custom taxonomy wordings
        $all_taxonomies = array();
        if ( $posttypes = \vc\helper::get_dynamic_posttypes() ) {
            foreach( (array) $posttypes as $post_id => $posttype ) {
                if ( !isset($posttype["slug"]) ) continue;
                $slug = $posttype["slug"];
                if ( $taxonomies = \vc\helper::get_custom_taxonomies($slug) ) {
                    foreach( $taxonomies as $name => $label ) {
                        $name = "customtax-".str_replace($slug."_", "", $name);
                        $all_taxonomies[$name] = $label;
                    }
                }
            }
        }
        $wordings["vc"]["tags"] = array_merge( $all_taxonomies, $wordings["vc"]["tags"] );

        $js_wordings = json_encode($wordings);

        if ( !$js_wordings || empty($js_wordings) ) {
            trigger_error( json_last_error() . ": " . json_last_error_msg(), E_USER_WARNING );
            $js_wordings = "{ wizard: {}, template_types: {}, vc: {}, tinymce: {} }";
        }
        
        // add inline script
        wp_add_inline_script( 'default_admin_js', 'var theme_wordings = '.$js_wordings.';', 'before' );

    }
    
    /**
     *  Check the whole content to determine, what needs to be rendered
     * 
     * TBD - deprecate/remove (see basics.php):
     * function is never used.
     * last use in modules/maps removed due to debugging.
     */
    public static function check_enqueue($sc=[]) {
        $content = self::get_enqueue_content();
        if ($content == "") return false;
        if ( method_exists( '\dynamic', 'check_enqueue_template' ) ) return dynamic::check_enqueue_template($content, $sc);
        return true;
    }
    
    /**
     * @deprecated since 1.2.0
     */
    public static function get_enqueue_content() {
        $content = "";
        // resolve templates
        if ( method_exists( '\Greyd\Dynamic\Render', 'get_enqueue_content' ) ) {
            $content = \Greyd\Dynamic\Render::get_enqueue_content();
        }
        else if ( method_exists( '\dynamic', 'get_enqueue_content' ) ) {
            $content = dynamic::get_enqueue_content();
        }
        // popups
        $popups = method_exists( '\popup', 'check_popup' ) ? popup::check_popup() : null;
        if ($popups) {
            foreach ($popups as $popup) $content .= $popup['content'];
        }
        return $content;
    }
    
    /**
     * Holds all custom styles to be rendered inside the footer.
     * 
     * @var array
     */
    public static $custom_styles = [];
    
    /**
     * Counts the styles rendered.
     * 
     * @var int
     */
    public static $style_count = 0;
    
	/**
	 * Add a custom style to the page.
	 * 
	 * @param string $style       The custom CSS styles to render.
	 * @param bool   $in_footer   Whether the style should be rendered in the footer.
	 * 
	 * @return bool Whether the style was successfully rendered.
	 */
	public static function add_custom_style( $style, $in_footer=true ) {
		
		if ( !is_string($style) || empty($style) ) return false;

		// if we're in the classic greyd suite, render all styles in the footer by default
		if ( $in_footer === null ) {
			$in_footer = true;
		}

		/**
		 * @filter greyd_enqueue_render_custom_styles_in_footer
		 * 
		 * @param bool $render_in_footer    Whether the style should be rendered in the footer.
		 * @param string $style             The custom CSS styles to render.
		 * 
		 * @return bool|null Whether the style should be rendered in the footer.
		 */
		$render_in_footer = apply_filters( 'greyd_enqueue_render_custom_styles_in_footer', $in_footer, $style );

		// not overwritten by filter
		if ( $render_in_footer === null ) {

			/**
			 * Render the first couple of styles in the header.
			 * This way Cumulative Layout Shift (CLS) is reduced.
			 * @since 1.5.6
			 */
			$render_in_footer = self::$style_count > 10;
		}

		// add to class var to render in footer
		if ( $render_in_footer ) {
			self::$custom_styles[] = $style;
		}
		// render inline
		else if ( !defined('REST_REQUEST') || !constant('REST_REQUEST') ) {
			echo "<style type='text/css'>" . \processor::process_styles_string($style) . "</style>";

			// increase counter
			self::$style_count++;
		}

		return true;
	}

    /**
     * Render all custom styles inside the footer
     */
    public static function render_custom_styles() {
        
        $styles = "";
        foreach ( (array) self::$custom_styles as $style ) {
            if ( !empty($style) && is_string($style) ) $styles .= trim( preg_replace( "/<\/?style[^>]*>/", "", $style ) )." ";
        }
        $styles = apply_filters( 'greyd_custom_css', $styles );
        
        if ( !empty($styles) ) {
            self::$custom_styles = [];
            echo "<style title='greyd_custom_css' type='text/css'>".\processor::process_styles_string($styles)."</style>";
        }
    }
}
