<?php
/*
    woocommerce visual composer extensions
*/
if( ! defined( 'ABSPATH' ) ) exit;

new woo_composer();
class woo_composer {

    public static $builder;
    /* 
        Constructor 
    */
    function __construct() {
        
        

        if (!is_callable('vc_map')) return;
        add_action('after_setup_theme', array($this, 'init'));
       
        
        // make shop/archive/product dynamic
        add_action('vc_before_init', array($this, 'woo_content_vc'));

        // check if woocommerce-germanized is installed and active
        if (\vc\helper::is_active_plugin('woocommerce-germanized/woocommerce-germanized.php')) {
            // Legal textblocks
            add_action('vc_before_init', array($this, 'payment_methods_info_vc'));
            add_action('vc_before_init', array($this, 'gzd_complaints_vc'));
            add_action('vc_before_init', array($this, 'revocation_form_vc'));
            // Footer notifications
            add_action('vc_before_init', array($this, 'gzd_vat_info_vc'));
            add_action('vc_before_init', array($this, 'gzd_sale_info_vc'));
        }

        //add_action('admin_notices', array($this, 'mod_dynamic_vc'));
        add_action('admin_init', array($this, 'mod_defaults_vc'));
        add_action('admin_notices', array($this, 'display_admin_notices'));
        
        // add vc roles
        add_filter( 'greyd_add_vc_posttypes', [$this, 'add_vc_roles'] );
    }
    
    public function add_vc_roles($rules=[]) {
        return array_merge( $rules, ['product'] );
    }
    
    public function init() {
        $this->icon_uri = get_template_directory_uri()."/assets/icon/";
    }
    
    /*
        render vc modules
    */
    // dynamic woo content
    public function woo_content_vc() {
        vc_map(array(
            "name"          => __('Dynamischer Inhalt', 'core'),
            "description"   => __('Inhalt für Shop-, Produkt-, Kategorie- und Schlagwort-Seiten', 'core'),
            "base"          => "woo_content",
            "category"      => "WooCommerce",
            "icon"          => get_template_directory_uri()."/assets/icon/woo.svg",
            "show_settings_on_create" => false,
            "weight"        => 10,
            "params"        => array()
        ));
    }
    
    // woocommerce-germanized addons
    public function payment_methods_info_vc() {
        vc_map(array(
            "name"          => __('Info zu Zahlungsmethoden', 'core'),
            "description"   => __('Textblock von WooCommerce Germanized', 'core'),
            "base"          => "payment_methods_info",
            "category"      => "WooCommerce",
            "icon"          => get_template_directory_uri()."/assets/icon/woo_de.svg",
            "show_settings_on_create" => false,
            "weight"        => 8,
            "params"        => array()
        ));
    }
    public function gzd_complaints_vc() {
        vc_map(array(
            "name"          => __('Streitbeilegung', 'core'),
            "description"   => __('Textblock von WooCommerce Germanized', 'core'),
            "base"          => "gzd_complaints",
            "category"      => "WooCommerce",
            "icon"          => get_template_directory_uri()."/assets/icon/woo_de.svg",
            "show_settings_on_create" => false,
            "weight"        => 8,
            "params"        => array()
        ));
    }
    public function revocation_form_vc() {
        vc_map(array(
            "name"          => __('Widerrufsbelehrung', 'core'),
            "description"   => __('Formular von WooCommerce Germanized', 'core'),
            "base"          => "revocation_form",
            "category"      => "WooCommerce",
            "icon"          => get_template_directory_uri()."/assets/icon/woo_de.svg",
            "show_settings_on_create" => false,
            "weight"        => 8,
            "params"        => array()
        ));
    }
    public function gzd_vat_info_vc() {
        vc_map(array(
            "name"          => __('Steuer Info', 'core'),
            "description"   => __('Benachrichtigung von WooCommerce Germanized', 'core'),
            "base"          => "gzd_vat_info",
            "category"      => "WooCommerce",
            "icon"          => get_template_directory_uri()."/assets/icon/woo_de.svg",
            "show_settings_on_create" => false,
            "weight"        => 8,
            "params"        => array()
        ));
    }
    public function gzd_sale_info_vc() {
        vc_map(array(
            "name"          => __('Sale Info', 'core'),
            "description"   => __('Benachrichtigung von WooCommerce Germanized', 'core'),
            "base"          => "gzd_sale_info",
            "category"      => "WooCommerce",
            "icon"          => get_template_directory_uri()."/assets/icon/woo_de.svg",
            "show_settings_on_create" => false,
            "weight"        => 8,
            "params"        => array()
        ));
    }
    
    /*  
        modify modules
    */
    public function mod_dynamic_vc() {
        if (get_post_type() != 'dynamic_template') {
            vc_remove_element( "gzd_vat_info" );
            vc_remove_element( "gzd_sale_info" );
        }
    }
    public function mod_defaults_vc() {
        if(!is_admin()) return;
        if(!is_callable('vc_add_params')) return;
        if(!is_callable('vc_remove_element')) return;
        if(!is_callable('vc_map_update')) return;
        
        
//        $new_params = array_merge(
//            array(
//                array(
//                    "type"        => 'sub_seperator',
//                    "heading"     => __('Warenkorb Button', 'core'),
//                    "param_name"  => 'sub_seperator_btn',
//                ),
//            ),
//            array(
//                array(
//                    "type"          => "dropdown",
//                    "heading"       => __('Aussehen', 'core'),
//                    "param_name"    => "btn_style",
//                    'edit_field_class' => 'vc_col-xs-2 vc_clearleft',
//                    "value" => array(
//                        __('Button', 'core') => '_button',
//                        __('sekundärer Button', 'core') => "_button _sec",
//                        __('alternativer Button', 'core') => "_button _trd",
//                        __('Link', 'core') => '_link',
//                        __('sekundärer Link', 'core') => '_link _sec',
//                        __('individuell überschreiben', 'core') => "custom",
//                    ),
//                ), 
//            ),
//            // custom button
//            \vc\helper::custom_element_params_vc('btn_', 'btn_style', 'custom'),
//            
//            // Icon
//            \vc\helper::custom_icon_params_vc('btn_'),
//        ); 
//        vc_add_params("add_to_cart", $new_params);
//        vc_add_params("product", $new_params);
//        vc_add_params("product_page", $new_params);

        /* woocommerce */
        $wc_el = array(
            'woocommerce_cart' => [
                "name"          => __('Warenkorb', 'core'),
                "description"   => __('Zeigt den „Warenkorb“ Bereich', 'core')
            ],
            'woocommerce_checkout' => [
                "name"          => __('Kasse', 'core'),
                "description"   => __('Zeigt den „Kasse“ Bereich', 'core')
            ],
            'woocommerce_order_tracking' => [
                "name"          => __('Bestellstatus (Formular)', 'core'),
                "description"   => __('Lässt einen Nutzer den Bestellstatus einsehen', 'core'),
            ],
            'woocommerce_my_account' => [
                "name"          => __('Mein Konto', 'core'),
                "description"   => __('Zeigt den „Mein-Konto“ Bereich', 'core')
            ],
        );
        foreach ($wc_el as $key => $value) {
            vc_map_update(
                $key,
                array_merge(
                    array(
                        'icon'      => get_template_directory_uri()."/assets/icon/woo.svg",
                        'weight'    => 9,
                        'params'    => array()
                    ),
                    $value
                )
            );
        }
        $wc_el_del = array(
            // 'woocommerce_cart',
            // 'woocommerce_checkout',
            // 'woocommerce_order_tracking',
            // 'woocommerce_my_account',
            'recent_products',
            'featured_products',
            'product',
            'products',
            'add_to_cart',
            'add_to_cart_url',
            'product_page',
            'product_category',
            'product_categories',
            'sale_products',
            'best_selling_products',
            'top_rated_products',
            'product_attribute',
            'related_products'
        );
        foreach ($wc_el_del as $key => $value) {
            vc_remove_element( $value );
        }
        
        
        // only modify edit screens
        if ( !isset($_GET['post']) ) return;
        
        // get post
        $post_id    = $_GET['post'];
        $post       = get_post($post_id);
        if (!is_object($post)) return;
            
        // hide edit buttons for modules
        $inline_style = "<style>";
        $inline_style .= ".wpb_".implode( ' .vc_control-btn-edit, .wpb_', array_keys($wc_el) ).' .vc_control-btn-edit { display: none !important; }';
        $inline_style .= "</style>";
        echo $inline_style;
        
        // get post content
        $content    = $post->post_content;
        $before     = '<!-- wp:shortcode -->';
        $after      = '<!-- /wp:shortcode -->';
        
        // get original post_id if this is a wpml translated site
        if ( function_exists('icl_object_id') ) {
            global $sitepress;
            if ( $sitepress && method_exists($sitepress, 'get_default_language') ) {
                $lang_orig  = $sitepress->get_default_language();
                $lang_cur   = defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : explode('_', get_locale(),2)[0];
                if ( $lang_orig !== $lang_cur ) {
                    $post_id = strval( icl_object_id($post_id, $post->post_type, false, $lang_orig) );
                }
            }
        }

        // on shop page
        if ( $post_id === get_option('woocommerce_shop_page_id') ) {

            // force post content because it is also forced by woocommerce
            if ( empty($content) ) {
                $post->post_content = '[vc_row][vc_column][woo_content][/vc_column][/vc_row]';
                wp_update_post($post);
            }
        }
        // in shop templates
        else if ( $post->post_type === 'dynamic_template' && strpos($post->post_name, 'woo-product') === 0 ) {

        } else {
            vc_remove_element( 'woo_content' );
        }

        // on cart page
        if ( $post_id === get_option('woocommerce_cart_page_id') ) {
            if ( $content == $before.'[woocommerce_cart]'.$after ) {
                $post->post_content = '[vc_row][vc_column][woocommerce_cart][/vc_column][/vc_row]';
                wp_update_post($post);
            }
        } else {
            vc_remove_element( 'woocommerce_cart' );
        }

        // on checkout page
        if ( $post_id === get_option('woocommerce_checkout_page_id') ) {
            if ( $content == $before.'[woocommerce_checkout]'.$after ) {
                $post->post_content = '[vc_row][vc_column][woocommerce_checkout][/vc_column][/vc_row]';
                wp_update_post($post);
            }
        } else {
            vc_remove_element( 'woocommerce_checkout' );
        }

        // on myaccount page
        if ( $post_id === get_option('woocommerce_myaccount_page_id') ) {
            if ( $content == $before.'[woocommerce_my_account]'.$after ) {
                $post->post_content = '[vc_row][vc_column][woocommerce_my_account][/vc_column][/vc_row]';
                wp_update_post($post);
            }
        } else {
            vc_remove_element( 'woocommerce_my_account' );
        }
    }
    
    public function display_admin_notices() {
        if ( isset($_GET['post']) ) {
            $errortext  = '';
            $post_id    = $_GET['post'];
            $wizard_url = admin_url('edit.php?post_type=dynamic_template&wizzard=add');
            
            // on shop page
            if ( $post_id === get_option('woocommerce_shop_page_id') ) {
                $errortext = sprintf(
                    __('Diese Seite wird standardmäßig für die Darstellung von Produkten & allen Shop-Übersichten verwendet. Wenn du genauere Kontrolle über die einzelnen Seiten haben möchtest, kannst du dir unter %sTemplates > Neues Template%s spezielle WooCommerce-Templates erstellen.', 'core'),
                    '<a href='.$wizard_url.'>',
                    '</a>'
                );
            }
            
            // on shop page
            else if ( $post_id === get_option('woocommerce_myaccount_page_id') ) {
                $errortext = sprintf(
                    __('Die einzelnen Unterpunkte und Inhalte des Kontobereichs werden automatisch erstellt. Du kannst dir aber unter %sTemplates > Neues Template%s verschiedene Templates erstellen, die in den jeweiligen Unterseiten über oder unter dem Inhalt angezeigt werden. Wähle dafür als Art des Templates „Mein Konto“ und stelle die gewünschte Position ein.', 'core'),
                    '<a href='.$wizard_url.'>',
                    '</a>'
                );
            }
            if ( !empty($errortext) )
                echo "<div class='notice notice-info is-dismissible'><p>".$errortext."</p></div>";
        }
    }
}