<?php

class ESSB_More_Share_Popup_Generator
{

    private static $popups = array();

    /**
     * Initializes the More Share Popup functionality.
     *
     * This static method sets up the necessary hooks, actions, or configurations
     * required for the More Share Popup feature within the Easy Social Share Buttons plugin.
     *
     * @return void
     */
    public static function init()
    {
        add_action('wp_footer', array('ESSB_More_Share_Popup_Generator', 'output_popups'), 99);
    }

    /**
     * Checks if the 'more' button is present in the provided list of networks.
     *
     * This method determines whether the 'more' option is included in the array of social networks.
     *
     * @param array $networks An array of network identifiers to check.
     * @return bool Returns true if 'more' is found in the array, false otherwise.
     */
    public static function legacy_check_more_button($networks = array())
    {
        return in_array('more', $networks);
    }

    /**
     * Determines and returns the mode for the share button based on the provided button styles and networks.
     *
     * This method checks if the "more" button should be used by calling the legacy_check_more_button method.
     * Depending on the result, it selects the appropriate mode from the $button_styles array, giving priority
     * to location-specific button functions if they are set.
     *
     * @param array $button_styles An associative array of button style options, which may include:
     *                             - 'more_button_func' (string): The default function for the "more" button.
     *                             - 'location_more_button_func' (string, optional): Location-specific function for the "more" button.
     *                             - 'share_button_func' (string): The default function for the share button.
     *                             - 'location_share_button_func' (string, optional): Location-specific function for the share button.
     * @param array $networks      An array of social network identifiers to check for the "more" button condition.
     * @param string $position      The position where the share popup will be displayed.
     *
     * @return string The selected mode for the share button, based on the provided styles and networks.
     */
    
    public static function get_mode($button_styles = array(), $networks = array(), $position = '')
    {
        $is_more = self::legacy_check_more_button($networks);

        $mode = '';

        if ($is_more) {
            $mode = $button_styles['more_button_func'];

            if (isset($button_styles['location_more_button_func'])) {
                $mode = $button_styles['location_more_button_func'];
            }
        } else {
            $mode = $button_styles['share_button_func'];

            if (isset($button_styles['location_share_button_func'])) {
                $mode = $button_styles['location_share_button_func'];
            }
        }

        if ($position == 'sidebar' && $mode == '1') {
            $mode = '3';
        }

        return $mode;
    }

    /**
     * Generates the HTML output for the "More Share" popup with customizable options.
     *
     * @param string $salt           Optional. A unique salt value for cache-busting or identification.
     * @param string $position       Optional. The position where the popup should appear.
     * @param array  $networks       Optional. List of social networks to include in the popup.
     * @param array  $networks_order Optional. Custom order for displaying the social networks.
     * @param array  $styles         Optional. Array of CSS styles or classes to apply to the popup.
     * @param array  $share_data     Optional. Additional data required for sharing (e.g., URL, title).
     */
    public static function generate($salt = '', $position = '', $networks = array(), $networks_order = array(), $styles = array(), $share_data = array())
    {
        $mode = self::get_mode($styles, $networks, $position);


        // Mode not supported
        if ($mode != '2' && $mode != '3') {
            return;
        }

        $popup_style = essb_options_value('share_button_popstyle');
        $popup_template = essb_options_value('share_button_poptemplate');
        $popup_title = essb_options_value('share_button_title');
        $popup_networks = array();

        $user_networks = essb_options_value('share_button_popnetworks');

        if (empty($popup_title)) {
            $popup_title = esc_html__('Share via', 'essb');
        }

        if (has_filter('essb_morepopup_title')) {
            $popup_title = apply_filters('essb_morepopup_title', $popup_title);
        }

        // If the position does not support different popup styles
        if (!self::position_supports_modern_style($position)) {
            $popup_style = '';
        }

        $popup_networks = essb_core_helper_generate_list_networks_with_more($mode == '2');
        $popup_networks_order = essb_core_helper_generate_network_list();

        if ($mode != '2' && is_array($networks) && $position == 'shortcode') {
            $popup_networks = $networks;
            $popup_networks_order = $networks_order;
        }

        if ($mode != '2') {
            $personalized_networks = essb_get_active_social_networks_by_position($position);
            $personalized_network_order = essb_get_order_of_social_networks_by_position($position);

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

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

        if ($mode == '3') {
            if (in_array('more', $popup_networks) || in_array('share', $popup_networks)) {
                $popup_networks = essb_core_helper_networks_after_more($popup_networks);
            }
        }

        if ($mode == '2') {
            $popup_networks = self::networks_without_more_share($popup_networks);
        }

        $share_data = self::parse_mail_button_if_exists($popup_networks, $share_data);

        if (!empty($user_networks)) {
            $popup_networks = $user_networks;
            $popup_networks_order = $user_networks;
        }

        if ($position == 'sharebottom') {
            $popup_networks = $networks;
            $popup_networks_order = $networks_order;
            $popup_style = ''; // only supports classic popup
        }

        $styles = self::apply_default_morepopup_styles($styles, $popup_template, $popup_style, $position);

        $popup_key = $position . '-' . mt_rand();

        self::$popups[$popup_key] = self::generate_output(array(
            'salt' => $salt,
            'position' => $position,
            'styles' => $styles,
            'networks' => $popup_networks,
            'networks_order' => $popup_networks_order,
            'share_data' => $share_data,
            'popup_style' => $popup_style,
            'popup_template' => $popup_template,
            'popup_title' => $popup_title
        ));
    }

    /**
     * Generates the output for the "More Share" popup.
     *
     * @param array $options  Optional. Array of options to customize the output.
     
     * @return string The generated HTML output for the popup.
     */
    public static function generate_output($options = array())
    {
        $output = '';

        /**
         * Loading existing network names for the rendering (in the popup always showing the standard names)
         */
        $network_names = ESSB_Share_Networks_Helper::get_networks_with_names(true);
        $more_salt = mt_rand();
        $style = !empty($options['popup_style']) ? $options['popup_style'] : 'classic';

        $user_message_inpop = "";

        if ($options['popup_style'] == 'modern') {
            $sharing_title = isset($options['share_data']['title_plain']) ? $options['share_data']['title_plain'] : '';
            $user_message_inpop = '<div class="essb-morepop-modern-t">' . $sharing_title . '</div>';
        }

        $user_message_inpop = apply_filters('essb_morepopup_message', $user_message_inpop);

        self::prepare_styles();

        self::register_actions();

        $output = '';
        $output .= ESSB_Dynamic_CSS_Builder::register_and_prepare_inline_code('essb-morepopup', ESSB_Runtime_CSS_Builder::compile('essb-morepopup'), true);
        $output .= '<div class="essb-morepop-overlay essb-morepop-' . esc_attr($style) . ' essb-morepop-' . esc_attr($options['salt']) . ' essb-morepop-p-' . esc_attr($options['position']) . '" data-salt="' . esc_attr($options['salt']) . '">';
        $output .= '<div class="essb-morepop-window">';
        $output .= '<div class="essb-morepop-window-h">';
        $output .= '<span>' . $options['popup_title'] . '</span>';
        $output .= '<a href="#" class="essb-morepop-window-h-close" data-salt="' . esc_attr($options['salt']) . '">' . essb_svg_icon('close') . '</a>';
        $output .= '</div>'; // essb-morepop-window-h

        $output .= '<div class="essb-morepop-window-c">';
        $output .= $user_message_inpop;
        $output .= essb_draw_share_buttons(
            $options['share_data'],
            $options['styles'],
            $options['networks'],
            $options['networks_order'],
            $network_names,
            "more_popup",
            $more_salt,
            'share'
        );
        $output .= '</div>';

        $output .= '</div>'; // essb-morepop-window

        $output .= '</div>'; // essb-morepop-overlay

        return $output;
    }

    /**
     * Outputs the HTML and necessary scripts for the "more share" popup feature.
     *
     * This static method is responsible for rendering the popup interface that allows users
     * to access additional social sharing options beyond the default set. It typically includes
     * the markup and any required JavaScript to handle the popup's display and interaction.
     */
    public static function output_popups()
    {
        $output = '';

        foreach (self::$popups as $key => $content) {
            $output .= $content;
        }

        echo $output;
    }

    /**
     * Determines if the given position supports the modern style for the share button popup.
     *
     * @param string $position The position to check for modern style support.
     * @return bool True if the position supports modern style, false otherwise.
     */
    private static function position_supports_modern_style($position = '')
    {
        $without_support = array('sharebottom', 'sharebar', 'sharepoint');

        return in_array($position, $without_support) ? false : true;
    }

    /**
     * Returns a list of social networks excluding those that should not appear in the "more share" popup.
     *
     * @param array $networks Optional. An array of network identifiers to filter. Default is an empty array.
     * @return array The filtered array of network identifiers without those excluded from the "more share" popup.
     */
    private static function networks_without_more_share($networks = array())
    {
        $r = array();

        foreach ($networks as $network) {
            if ($network != 'more' && $network != 'share') {
                $r[] = $network;
            }
        }

        return $r;
    }

    /**
     * Parses the mail button if it exists within the provided networks array.
     *
     * This method checks if the 'mail' network is present in the given list of networks,
     * and processes it accordingly using the provided share data.
     *
     * @param array $networks   An array of network identifiers to check for the mail button.
     * @param array $share_data An associative array containing data to be shared.
     * @return array            The modified networks array after processing the mail button.
     */
    private static function parse_mail_button_if_exists($networks = array(), $share_data = array())
    {
        if (in_array('mail', $networks)) {
            essb_resource_builder()->activate_resource('mail');

            if (!function_exists('essb_sharing_prepare_mail')) {
                include_once(ESSB3_PLUGIN_ROOT . 'lib/core/extenders/essb-core-extender-sharing.php');
            }

            $share_data = essb_sharing_prepare_mail($share_data);
        }

        return $share_data;
    }

    /**
     * Applies the default styles for the "more share" popup button.
     *
     * @param array  $button_style Optional. An array of button style options. Default empty array.
     * @param string $template     Optional. The template name to use. Default empty string.
     * @param string $style        Optional. The style identifier. Default empty string.
     * @param string $position     Optional. The position of the popup. Default empty string.
     *
     * @return array The modified button style array with default styles applied.
     */
    private static function apply_default_morepopup_styles($button_style = array(), $template = '', $style = '', $position = '')
    {
        $button_style['button_style'] = "button";
        $button_style['button_align'] = 'left';
        $button_style['show_counter'] = false;
        $button_style['button_width'] = "column";
        $button_style['button_width_columns'] = $position == 'sharebottom' ? '1' : (essb_is_mobile() ? "1" : "3");
        $button_style['counter_pos'] = "left";
        $button_style['nospace'] = false;

        if (!empty($template)) {
            $button_style['template'] = $template;
        }

        if ($style == 'modern') {
            $button_style['button_style'] = "vertical";
            $button_style['button_align'] = 'center';
            $button_style['button_width_columns'] = (essb_is_mobile() ? "2" : "4");
        }

        return $button_style;
    }



    /**
     * Prepares and returns the necessary styles for the "more share" popup.
     *
     * This method is responsible for generating or retrieving the CSS styles
     * required to properly display the additional share buttons popup in the
     * Easy Social Share Buttons plugin.     
     */
    private static function prepare_styles()
    {
        ESSB_Runtime_CSS_Builder::init('essb-morepopup');
        //ESSB_Runtime_CSS_Builder::register('essb-morepopup', '.essb-morepop-overlay', 'background-color', 'rgba(0,0,0,0.5)');
        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-overlay',
            array(
                'display' => 'none',
                'align-items' => 'center',
                'justify-content' => 'center',
                'position' => 'fixed',
                'top' => '0',
                'left' => '0',
                'z-index' => '100002',
                'width' => '100%',
                'height' => '100%',
                'background-color' => 'rgba(0,0,0,0.5)'
            ),
        );

        ESSB_Runtime_CSS_Builder::register('essb-morepopup', '.essb-morepop-overlay.essb-morepop-active', 'display', 'flex');
        ESSB_Runtime_CSS_Builder::register('essb-morepopup', '.essb-morepop-overlay.essb-morepop-modern', 'background-color', 'rgba(0,0,0,0.8)');

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-window',
            array(
                'width' => '90%',
                'max-width' => '720px',
                'display' => 'flex',
                'align-items' => 'center',
                'justify-content' => 'center',
                'flex-direction' => 'column',
                'overflow' => 'hidden',
            )
        );

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-classic .essb-morepop-window',
            array(
                'background-color' => '#fff',
                'max-width' => '720px',
                'overflow' => 'hidden',
                'border-radius' => '5px'
            )
        );

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-window-h',
            array(
                'width' => '100%',
                'display' => 'flex',
                'align-items' => 'center',
                'justify-content' => 'space-between',
                'font-size' => '16px',
                'padding' => '10px'
            )
        );

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-classic .essb-morepop-window-h',
            array(
                'background-color' => '#1b84ff',
                'color' => '#fff',
            )
        );

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-modern .essb-morepop-window-h',
            array(
                'color' => '#fff'
            )
        );

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-window-h-close',
            array(
                'width' => '14px',
                'height' => '14px',
                'fill' => '#fff',
                'display' => 'flex',
                'align-items' => 'center',
                'justify-content' => 'center',
                'opacity' => '0.8',
                'transition' => 'opacity 0.1s ease-in-out'
            )
        );

        ESSB_Runtime_CSS_Builder::register('essb-morepopup', '.essb-morepop-window-h-close:hover', 'opacity', '1');

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-window-c',
            array(
                'padding' => '15px 15px 5px 15px',
                'max-height' => '70vh',
                'overflow-y' => 'auto',
                'scrollbar-width' => 'thin',
                'width' => '100%'
            )
        );

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-modern .essb-morepop-window-c',
            array(
                'max-height' => '80vh',
                'scrollbar-color' => 'rgba(255, 255, 255,0.5) transparent'
            )
        );

        ESSB_Runtime_CSS_Builder::register('essb-morepopup', '.essb-morepop-window-c .essb_links', 'margin-top', '0');
        ESSB_Runtime_CSS_Builder::register('essb-morepopup', '.essb-morepop-overlay.essb-morepop-active', 'display', 'flex');

        ESSB_Runtime_CSS_Builder::register_multiple(
            'essb-morepopup',
            '.essb-morepop-modern .essb-morepop-modern-t',
            array(
                'font-size' => '1.1em',
                'color' => '#fff',
                'text-align' => 'center',
                'margin-bottom' => '1em'
            )
        );
    }

    /**
     * Registers the necessary actions for the More Share Popup functionality.
     *
     * This private static method is responsible for hooking up all required actions
     * that enable the popup to function correctly within the Easy Social Share Buttons plugin.
     */
    private static function register_actions()
    {
        ESSB_Dynamic_JS_Builder::push_footer_code('essb-morepopup', 'function essb_open_morepopup_window(e=""){if(essb.essb_morepopup_opened){essb_close_morepopup_window(e);return}let o=document.querySelector(".essb-morepop-"+e);o&&o.classList.add("essb-morepop-active"),essb.essb_morepopup_opened=!0}function essb_close_morepopup_window(e=""){let o=document.querySelector(".essb-morepop-"+e);o&&o.classList.remove("essb-morepop-active"),essb.essb_morepopup_opened=!1}document.addEventListener("DOMContentLoaded",function(){document.querySelectorAll(".essb-morepop-window-h-close").forEach(e=>{e.onclick=function(e){e.preventDefault();let o=this.getAttribute("data-salt")||"";""!=o&&essb_close_morepopup_window(o)}}),document.querySelectorAll(".essb-morepop-overlay").forEach(e=>{e.onclick=function(e){if(e.target!==this)return;e.preventDefault();let o=this.getAttribute("data-salt")||"";""!=o&&essb_close_morepopup_window(o)}})});');
    }
}

/**
 * Initialize the generator
 */
ESSB_More_Share_Popup_Generator::init();
