<?php

class ESSB_Core_Button_Generator {

    public static function generate($position, $likeshare, $share_options, $is_shortcode, $shortcode_options, $media_url, $general_options, $network_options, $design_options, $button_style)
    {
        global $post;

        $cache_key_runtime = '';
        if (ESSBGlobalSettings::$cache_runtime) {
            if (isset($post) && !$is_shortcode) {
                $cache_key_runtime = sprintf('essb_cache_share_%1$s_%2$s', $post->ID, $position);

                $cached_data = wp_cache_get($cache_key_runtime);
                if (false !== $cached_data) {
                    return $cached_data;
                }
            }
        }

        $only_share = essb_option_bool_value('only_share', $share_options);
        $post_type = essb_option_value('post_type', $share_options);
        $user_based_post_type = $post_type;

        $amp_sharing = essb_option_bool_value('amp', $share_options);

        if ($general_options['reset_postdata']) {
            wp_reset_postdata();
        }

        $cache_key = '';
        if (isset($post) && defined('ESSB3_CACHE_ACTIVE') && !$is_shortcode) {
            $cache_key = sprintf('essb_cache_share_%1$s_%2$s', $post->ID, $position);

            $cached_data = ESSBDynamicCache::get($cache_key);
            if (!empty($cached_data)) {
                return $cached_data;
            }
        }

        list($post_share_details, $post_native_details, $post_type) = self::prepare_share_details($position, $is_shortcode, $shortcode_options, $share_options, $media_url, $post_type, $user_based_post_type);

        list($button_style, $social_networks, $social_networks_order, $social_networks_names, $check_position_settings_key) = self::init_networks_basic($position, $network_options, $design_options, $general_options, $button_style, $amp_sharing, $post_type);

        $share_bottom_networks = array();
        if ($position != 'sharebar' && $position != 'sharepoint' && $position != 'sharebottom') {
            list($button_style, $social_networks, $social_networks_order, $social_networks_names) = self::apply_standard_position($position, $check_position_settings_key, $post_type, $button_style, $social_networks, $social_networks_order, $social_networks_names);
        } else {
            list($button_style, $social_networks, $social_networks_order, $share_bottom_networks) = self::apply_mobile_bar($position, $button_style, $social_networks, $social_networks_order, $social_networks_names);
            $post_native_details['active'] = false;
        }

        list($social_networks, $social_networks_order, $social_networks_names, $button_style, $post_native_details, $share_bottom_networks) = self::finalize_networks($is_shortcode, $shortcode_options, $social_networks, $social_networks_order, $social_networks_names, $button_style, $post_native_details, $position, $share_bottom_networks);

        list($salt, $button_style, $post_native_details, $social_networks, $social_networks_order) = self::prepare_button_render($social_networks, $social_networks_order, $button_style, $network_options, $position, $design_options, $post_native_details, $post_share_details, $amp_sharing);

        return self::render_and_post_process($post_share_details, $button_style, $social_networks, $social_networks_order, $social_networks_names, $position, $salt, $likeshare, $post_native_details, $share_bottom_networks, $cache_key, $cache_key_runtime);
    }

    private static function prepare_share_details($position, $is_shortcode, $shortcode_options, $share_options, $media_url, $post_type, $user_based_post_type)
    {
        global $post;

        if (empty($post_type) && isset($post)) {
            $post_type = $post->post_type;
            if (!empty($user_based_post_type)) {
                $post_type = $user_based_post_type;
            }
        }

        $post_share_details = essb_get_post_share_details($position);
        $post_native_details = essb_get_native_button_settings($position, essb_option_bool_value('only_share', $share_options));

        if ($is_shortcode) {
            essb_depend_load_function('essb_shortcode_map_shareoptions', 'lib/core/extenders/essb-core-extender-shortcode.php');
            $post_share_details = essb_shortcode_map_shareoptions($post_share_details, $shortcode_options);
        } else {
            if (!empty($share_options['url'])) {
                $post_share_details['url'] = $share_options['url'];
            }
            if (!empty($share_options['title'])) {
                $post_share_details['title'] = $share_options['title'];
                $post_share_details['title_plain'] = isset($share_options['title_plain']) ? $share_options['title_plain'] : $share_options['title'];
            }
            if (!empty($share_options['image'])) {
                $post_share_details['image'] = $share_options['image'];
            }
            if (!empty($share_options['description'])) {
                $post_share_details['description'] = $share_options['description'];
            }
            if (!empty($share_options['twitter_user'])) {
                $post_share_details['twitter_user'] = $share_options['twitter_user'];
            }
            if (!empty($share_options['twitter_hashtags'])) {
                $post_share_details['twitter_hashtags'] = $share_options['twitter_hashtags'];
            }
            if (!empty($share_options['twitter_tweet'])) {
                $post_share_details['twitter_tweet'] = $share_options['twitter_tweet'];
            }

            if ($media_url != '') {
                $post_share_details['image'] = $media_url;
                $post_share_details['user_image_url'] = $media_url;
            }

            if (!empty($share_options['force_set_post_id'])) {
                $post_share_details['post_id'] = $share_options['force_set_post_id'];
            }

            if (!essb_option_bool_value('deactivate_module_google_analytics') && class_exists('ESSB_ShareURL_UTM_Tracking')) {
                if (ESSB_ShareURL_UTM_Tracking::is_active()) {
                    $post_share_details['utm_tracking'] = true;
                }
            }
        }

        if (has_filter('essb3_share_url')) {
            $post_share_details['url'] = apply_filters('essb3_share_url', $post_share_details['url']);
        }

        $post_share_details['full_url'] = $post_share_details['url'];

        return array($post_share_details, $post_native_details, $post_type);
    }

    private static function init_networks_basic($position, $network_options, $design_options, $general_options, $button_style, $amp_sharing, $post_type)
    {
        $button_style = self::get_buttons_visual_options($position == 'followme_bottom' ? 'followme' : $position, $design_options, $network_options, $general_options, $button_style);
        $button_style['amp'] = $amp_sharing;

        $social_networks = $network_options['networks'];
        $social_networks_order = $network_options['networks_order'];
        $social_networks_names = $network_options['default_names'];

        $check_position_settings_key = $position;

        if (essb_is_mobile() && essb_active_position_settings('mobile')) {
            $check_position_settings_key = 'mobile';
        }

        if (essb_is_mobile() && !essb_option_bool_value('user_fixed_networks')) {
            if (ESSBGlobalSettings::$mobile_networks_active) {
                $social_networks = ESSBGlobalSettings::$mobile_networks;
                $social_networks_names = essb_apply_position_network_names('mobile', $social_networks_names);
            }
            if (ESSBGlobalSettings::$mobile_networks_order_active) {
                $social_networks_order = ESSBGlobalSettings::$mobile_networks_order;
            }
        }

        if ($amp_sharing && !essb_option_bool_value('user_fixed_networks')) {
            $amp_networks = essb_options_value('amp_networks');
            if (!is_array($amp_networks)) {
                $amp_networks = array();
            }

            if (count($amp_networks) > 0) {
                $social_networks = $amp_networks;
                $social_networks_order = $amp_networks;
                $social_networks_names = essb_apply_position_network_names('amp', $social_networks_names);
            }
        }

        return array($button_style, $social_networks, $social_networks_order, $social_networks_names, $check_position_settings_key);
    }

    private static function apply_standard_position($position, $check_position_settings_key, $post_type, $button_style, $social_networks, $social_networks_order, $social_networks_names)
    {
        if (!defined('ESSB3_LIGHTMODE') && !ESSB_Runtime_Cache::is('adaptive-styles')) {
            if (!empty($post_type)) {
                if (essb_active_position_settings(sprintf('post-type-%1$s', $post_type))) {
                    $check_position_settings_key = sprintf('post-type-%1$s', $post_type);
                }
            }
        }

        if ($position == 'postbar') {
            $button_style = essb_apply_postbar_position_style_settings('postbar', $button_style);
        }

        if ($position == 'point') {
            $button_style = essb_apply_point_position_style_settings('point', $button_style);
        }

        if ($position == 'followme_bottom') {
            $button_style = essb_apply_followme_bottom_position_styles('followme', $button_style);
        }

        if (essb_active_position_settings($check_position_settings_key)) {
            $button_style = essb_apply_position_style_settings($check_position_settings_key, $button_style);

            if (!essb_option_bool_value('user_fixed_networks')) {
                if ($check_position_settings_key != 'mobile') {
                    $personalized_networks = essb_get_active_social_networks_by_position($check_position_settings_key);
                    $personalized_network_order = essb_get_order_of_social_networks_by_position($check_position_settings_key);

                    if (is_array($personalized_networks) && count($personalized_networks) > 0) {
                        $social_networks = $personalized_networks;
                    }

                    if (is_array($personalized_network_order) && count($personalized_network_order) > 0) {
                        $social_networks_order = $personalized_network_order;
                    }
                }

                $social_networks_names = essb_apply_position_network_names($check_position_settings_key, $social_networks_names);
            }
        } else {
            if (defined('ESSB3_LIGHTMODE') || ESSB_Runtime_Cache::is('adaptive-styles')) {
                essb_helper_maybe_load_feature('litemode-helper');

                if (ESSB_LightMode_Helper::position_with_predefined_options($position)) {
                    $button_style = ESSB_LightMode_Helper::apply_position_predefined_settings($position, $button_style);
                }
            }
        }

        if (has_filter("essb4_position_style_{$position}")) {
            $button_style = apply_filters("essb4_position_style_{$position}", $button_style);
        }

        return array($button_style, $social_networks, $social_networks_order, $social_networks_names);
    }

    private static function apply_mobile_bar($position, $button_style, $social_networks, $social_networks_order, $social_networks_names)
    {
        $share_bottom_networks = array();
        $mobile_position_with_networks_list = false;

        if (essb_active_position_settings($position)) {
            $button_style = essb_apply_mobile_position_style_settings($position, $button_style);

            $personalized_networks = essb_get_active_social_networks_by_position($position);
            $personalized_network_order = essb_get_order_of_social_networks_by_position($position);

            if (!essb_option_bool_value('user_fixed_networks')) {
                if (is_array($personalized_networks) && count($personalized_networks) > 0) {
                    $social_networks = $personalized_networks;
                    $mobile_position_with_networks_list = true;
                }

                if (is_array($personalized_network_order) && count($personalized_network_order) > 0) {
                    $social_networks_order = $personalized_network_order;
                }

                $social_networks_names = essb_apply_position_network_names($position, $social_networks_names);
            }
        }

        if ($position == 'sharebar' || $position == 'sharepoint') {
            $social_networks = essb_remove_network_from_list($social_networks, 'more');
            $social_networks = essb_remove_network_from_list($social_networks, 'share');

            $button_style = essb_apply_required_mobile_style_settings($position, $button_style);
        }

        if ($position == 'sharebottom') {
            $is_more = in_array('more', $social_networks);
            $is_share = in_array('share', $social_networks);

            if (!$mobile_position_with_networks_list) {
                if ($is_more || $is_share) {
                    $networks_after_more_share = essb_exist_networks_after_more_share($social_networks);

                    $social_networks = essb_remove_network_from_list($social_networks, 'more');
                    $social_networks = essb_remove_network_from_list($social_networks, 'share');

                    $mode = $is_more ? essb_options_value('more_button_func') : essb_options_value('share_button_func');

                    if (!$networks_after_more_share) {
                        $mode = '2';
                    }

                    if ($mode == '2') {
                        $social_networks = essb_core_helper_generate_list_networks_with_more($mode == '2');
                        $social_networks_order = essb_core_helper_generate_network_list();
                        $social_networks = essb_remove_network_from_list($social_networks, 'more');
                        $social_networks = essb_remove_network_from_list($social_networks, 'share');
                    }
                }
            } else {
                $social_networks = essb_remove_network_from_list($social_networks, 'more');
                $social_networks = essb_remove_network_from_list($social_networks, 'share');
            }

            $button_style = essb_apply_required_mobile_style_settings($position, $button_style);

            $available_networks_count = essb_option_value('mobile_sharebuttonsbar_count');
            $button_count_correction_when_total = isset($button_style['button_count_correction_when_total']) ? $button_style['button_count_correction_when_total'] : 0;
            if (intval($available_networks_count) == 0) {
                $available_networks_count = 4;
            }
            if (count($social_networks) > (intval($available_networks_count) - $button_count_correction_when_total)) {
                $share_bottom_networks = $social_networks;

                $share_bottom_networks = (array_slice($social_networks, intval($available_networks_count) - 1 - $button_count_correction_when_total));
                array_splice($social_networks, intval($available_networks_count) - 1 - $button_count_correction_when_total);
                $social_networks[] = 'more';
                $social_networks_order = $social_networks;
            }

            $button_style['button_width_columns'] = intval($available_networks_count);
        }

        return array($button_style, $social_networks, $social_networks_order, $share_bottom_networks);
    }

    private static function finalize_networks($is_shortcode, $shortcode_options, $social_networks, $social_networks_order, $social_networks_names, $button_style, $post_native_details, $position, $share_bottom_networks)
    {
        if (!is_array($social_networks)) {
            $social_networks = array();
        }
        if (!is_array($social_networks_order) || count($social_networks_order) == 0) {
            $social_networks_order = essb_core_helper_generate_network_list();
        }

        if ($is_shortcode) {
            essb_depend_load_function('essb_shortcode_map_visualoptions', 'lib/core/extenders/essb-core-extender-shortcode.php');

            $button_style = essb_shortcode_map_visualoptions($button_style, $shortcode_options);

            if (count($shortcode_options['networks']) > 0) {
                $social_networks = $shortcode_options['networks'];
                $social_networks_order = $shortcode_options['networks'];
            }

            if ($shortcode_options['customize_texts']) {
                $social_networks_names = $shortcode_options['network_texts'];
            }

            if (!empty($shortcode_options['fblike'])) {
                $post_native_details['facebook_url'] = $shortcode_options['fblike'];
            }
            if (!empty($shortcode_options['plusone'])) {
                $post_native_details['google_url'] = $shortcode_options['plusone'];
            }

            if ($position == 'sharebottom') {
                if (in_array('more', $social_networks)) {
                    if (($key = array_search('more', $social_networks)) !== false) {
                        unset($social_networks[$key]);
                    }
                }

                $button_style = essb_shortcode_map_visualoptions($button_style, $shortcode_options);

                $available_networks_count = essb_option_value('mobile_sharebuttonsbar_count');

                if (intval($available_networks_count) == 0) {
                    $available_networks_count = 4;
                }
                if (count($social_networks) > intval($available_networks_count)) {
                    $share_bottom_networks = $social_networks;
                    array_splice($social_networks, intval($available_networks_count) - 1);
                    $social_networks[] = 'more';
                    $social_networks_order[] = 'more';
                }

                $button_style['button_width_columns'] = intval($available_networks_count);
            }
        }

        return array($social_networks, $social_networks_order, $social_networks_names, $button_style, $post_native_details, $share_bottom_networks);
    }

    private static function prepare_button_render($social_networks, $social_networks_order, $button_style, $network_options, $position, $design_options, $post_native_details, $post_share_details, $amp_sharing)
    {
        $salt = mt_rand();

        if (in_array('mail', $social_networks)) {
            essb_resource_builder()->activate_resource('mail');
        }

        if (in_array('love', $social_networks)) {
            essb_depend_load_function('essb_love_generate_js_code', 'lib/core/helpers/helpers-loveyou-jscode.php');
        }

        $button_style['included_button_count'] = count($social_networks);
        if ($button_style['show_counter']) {
            if (isset($button_style['total_counter_pos'])) {
                if ($button_style['total_counter_pos'] != 'hidden') {
                    $button_style['included_button_count']++;
                }
            }
        }

        if ($position == 'sidebar' || $position == 'postfloat') {
            if ($button_style['more_button_func'] == '1') {
                $button_style['more_button_func'] = '2';
            }

            if ($button_style['share_button_func'] == '1') {
                $button_style['share_button_func'] = '2';
            }
        }
        if ($position == 'sharebottom') {
            $button_style['more_button_func'] = '3';
            $button_style['share_button_func'] = '3';
        }

        if ($design_options['sidebar_leftright_close'] && $position == 'sidebar') {
            $social_networks[] = 'sidebar-close';
            $social_networks_order[] = 'sidebar-close';
        }

        if ($post_native_details['active']) {
            $post_native_details['url'] = $post_share_details['url'];
            $post_native_details['text'] = $post_share_details['title'];
        }

        $button_style['mail_function'] = $network_options['mail_function'];

        if ($amp_sharing) {
            $button_style['mail_function'] = 'link';
        }

        $button_style['is_mobile'] = essb_is_mobile();

        if ($button_style['button_width_full_button'] == '') {
            $button_style['button_width_full_button'] = '95';
        }

        return array($salt, $button_style, $post_native_details, $social_networks, $social_networks_order);
    }

    private static function render_and_post_process($post_share_details, $button_style, $social_networks, $social_networks_order, $social_networks_names, $position, $salt, $likeshare, $post_native_details, $share_bottom_networks, $cache_key, $cache_key_runtime)
    {
        $ssbuttons = essb_draw_share_buttons(
            $post_share_details,
            $button_style,
            $social_networks,
            $social_networks_order,
            $social_networks_names,
            $position,
            $salt,
            $likeshare,
            $post_native_details
        );

        if (has_filter('essb4_draw_style_details')) {
            $button_style = apply_filters('essb4_draw_style_details', $button_style);
        }

        if ($button_style['button_width'] == 'fixed') {
            $fixedwidth_key = $button_style['button_width_fixed_value'] . '-' . $button_style['button_width_fixed_align'];
            essb_depend_load_function('essb_rs_css_build_fixedwidth_button', 'lib/helpers/assets/builder-share-fixedwidth.php');
            essb_resource_builder()->add_css(essb_rs_css_build_fixedwidth_button($salt, $button_style['button_width_fixed_value'], $button_style['button_width_fixed_align']), 'essb-fixed-width-' . $fixedwidth_key, 'footer');
        }
        if ($button_style['button_width'] == 'full') {
            $count_of_social_networks = count($social_networks);
            if ($button_style['show_counter']) {
                if (isset($button_style['total_counter_pos'])) {
                    if ($button_style['total_counter_pos'] != 'hidden') {
                        $count_of_social_networks++;
                    }
                }
            }
            $container_width = $button_style['button_width_full_container'];

            $single_button_width = intval($container_width) / $count_of_social_networks;
            $single_button_width = floor($single_button_width);

            essb_depend_load_function('essb_rs_css_build_fullwidth_buttons', 'lib/helpers/assets/builder-share-fullwidth.php');
            essb_resource_builder()->add_css(essb_rs_css_build_fullwidth_buttons($count_of_social_networks, $button_style['button_width_full_container'], $button_style['button_width_full_button'], $button_style['button_width_full_first'], $button_style['button_width_full_second']), 'essb-full-width-' . $single_button_width . '-' . $button_style['button_width_full_button'] . '-' . $button_style['button_width_full_container'], 'footer');
        }

        if ($button_style['button_width'] == 'flex' && ($button_style['flex_width_value'] != '' || $button_style['flex_button_value'] != '')) {
            essb_depend_load_function('essb_rs_css_build_flexwidth_buttons', 'lib/helpers/assets/builder-share-flexwidth.php');
            essb_resource_builder()->add_css(essb_rs_css_build_flexwidth_buttons($button_style['flex_width_value'], $button_style['flex_button_value']), 'essb_flex_' . $button_style['flex_width_value'] . '_' . $button_style['flex_button_value'], 'footer');
        }

        if (in_array('more', $social_networks) || in_array('share', $social_networks)) {
            essb_depend_load_class('ESSB_More_Share_Popup_Generator', 'lib/classes/share-button/class-more-share-popup.php');

            ESSB_More_Share_Popup_Generator::generate(
                $salt,
                $position,
                $position == 'sharebottom' ? $share_bottom_networks : $social_networks,
                $position == 'sharebottom' ? $share_bottom_networks : $social_networks_order,
                $button_style,
                $post_share_details
            );
        }

        if (in_array('subscribe', $social_networks) && ESSBGlobalSettings::$subscribe_function != 'link') {
            if (!class_exists('ESSBNetworks_Subscribe')) {
                include_once(ESSB3_PLUGIN_ROOT . 'lib/networks/essb-subscribe.php');
            }

            $ssbuttons .= ESSBNetworks_Subscribe::draw_subscribe_form($position, $salt, 'sharebuttons-' . $position);
        }

        if (($button_style['button_animation'] != '' && $button_style['button_animation'] != 'no') && !essb_resource_builder()->is_activated('animations')) {
            $animate_url = ESSB3_PLUGIN_URL . '/assets/css/essb-animations.min.css';
            essb_resource_builder()->add_static_resource_footer($animate_url, 'easy-social-share-buttons-animations', 'css');
            essb_resource_builder()->activate_resource('animations');
        }

        if (!empty($ssbuttons)) {
            $ssbuttons = trim(preg_replace('/\s+/', ' ', $ssbuttons));
        }

        if (!empty($cache_key)) {
            ESSBDynamicCache::put($cache_key, $ssbuttons);
        }

        if (!empty($cache_key_runtime) && ESSBGlobalSettings::$cache_runtime) {
            wp_cache_set($cache_key_runtime, $ssbuttons);
        }

        return $ssbuttons;
    }

    public static function get_buttons_visual_options($position, $design_options, $network_options, $general_options, $button_style)
    {
        $style = array();
        $style['template'] = $design_options['template'];
        $style['button_style'] = $design_options['button_style'];
        $style['button_align'] = $design_options['button_align'];
        $style['button_width'] = $design_options['button_width'];
        $style['button_width_fixed_value'] = $design_options['button_width_fixed_value'];
        $style['button_width_fixed_align'] = $design_options['button_width_fixed_align'];
        $style['button_width_full_container'] = $design_options['button_width_full_container'];
        $style['button_width_full_button'] = $design_options['button_width_full_button'];
        $style['button_width_full_button_mobile'] = $design_options['button_width_Full_button_mobile'];
        $style['button_width_columns'] = $design_options['button_width_columns'];
        $style['show_counter'] = $button_style['show_counter'];
        $style['counter_pos'] = $button_style['counter_pos'];
        $style['active_internal_counters'] = $button_style['active_internal_counters'];
        $style['total_counter_pos'] = $button_style['total_counter_pos'];
        $style['message_share_buttons'] = $button_style['message_share_buttons'];
        $style['message_share_before_buttons'] = $button_style['message_share_before_buttons'];
        $style['message_like_buttons'] = $button_style['message_like_buttons'];
        $style['total_counter_afterbefore_text'] = $general_options['total_counter_afterbefore_text'];
        $style['total_counter_hidden_till'] = $general_options['total_counter_hidden_till'];
        $style['button_counter_hidden_till'] = $general_options['button_counter_hidden_till'];
        $style['nospace'] = $design_options['nospace'];
        $style['more_button_func'] = $network_options['more_button_func'];
        $style['fullwidth_align'] = $design_options['fullwidth_align'];
        $style['fullwidth_share_buttons_columns_align'] = $design_options['fullwidth_share_buttons_columns_align'];

        $style['flex_width_align'] = essb_option_value('flex_width_align');
        $style['flex_width_value'] = essb_option_value('flex_width_value');
        $style['flex_button_value'] = essb_option_value('flex_button_value');

        if (intval($style['button_width_full_container']) == 0) {
            $style['button_width_full_container'] = '100';
        }

        if (essb_is_mobile()) {
            if ($style['button_width_full_button_mobile'] != '') {
                $style['button_width_full_button'] = $style['button_width_full_button_mobile'];
            }
        }

        if ($style['button_width_full_button'] == '') {
            $style['button_width_full_button'] = '100';
        }

        $style['button_width_full_first'] = essb_option_value('fullwidth_first_button');
        $style['button_width_full_second'] = essb_option_value('fullwidth_second_button');

        $style['button_animation'] = essb_option_value('css_animations');

        $style['share_button_func'] = essb_option_value('share_button_func');
        $style['share_button_icon'] = essb_option_value('share_button_icon');
        $style['share_button_style'] = essb_option_value('share_button_style');

        $style['button_size'] = essb_option_value('button_size');
        $style['button_size_mobile'] = essb_option_value('button_size_mobile');

        if (has_filter('essb4_button_visual_options')) {
            $style = apply_filters('essb4_button_visual_options', $style, $position);
        }

        return $style;
    }
}
