Sh3ll
OdayForums


Server : LiteSpeed
System : Linux premium84.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64
User : claqxcrl ( 523)
PHP Version : 8.1.32
Disable Function : NONE
Directory :  /home/claqxcrl/confenda.com/wp-content/plugins/poll-maker/public/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //home/claqxcrl/confenda.com/wp-content/plugins/poll-maker/public/class-poll-maker-ays-public.php
<?php

// use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\Exception;

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://ays-pro.com/
 * @since      1.0.0
 *
 * @package    Poll_Maker_Ays
 * @subpackage Poll_Maker_Ays/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Poll_Maker_Ays
 * @subpackage Poll_Maker_Ays/public
 * @author     Poll Maker Team <info@ays-pro.com>
 */
class Poll_Maker_Ays_Public {

	/**
	 * The settings of this plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      Poll_Maker_Settings_Actions object $settings The current settings of this plugin.
	 */
	protected $settings;
    protected $fields_placeholders;
	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $plugin_name The ID of this plugin.
	 */
	private $plugin_name;
	private static $p;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $version The current version of this plugin.
	 */
	private $version;
	private static $v;

	/**
	 * The instance of this plugin public class.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      Poll_Maker_Ays_Public object.
	 */
	private static $instance = null;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @param string $plugin_name The name of the plugin.
	 * @param string $version The version of this plugin.
	 *
	 * @since    1.0.0
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version     = $version;
		self::$p           = $plugin_name;
		self::$v           = $version;

		add_shortcode('ays_poll', array($this, 'ays_poll_generate_shortcode'));
		$this->settings = new Poll_Maker_Settings_Actions($this->plugin_name);
		add_shortcode('ays_poll_all', array($this, 'ays_poll_all_generate_shortcode'));
		add_shortcode('ayspoll_results', array($this, 'ays_poll_results_generate_shortcode'));
		add_shortcode('ays_poll_cat', array($this, 'ays_poll_generate_categories_method'));
		add_shortcode('ays_poll_gleaderboard', array($this, 'ays_poll_generate_gleaderboard_list'));
		add_shortcode('ays_poll_request_form', array($this, 'ays_poll_generate_requests_form_method'));
        add_shortcode('ays_poll_user_history', array($this, 'ays_poll_user_history_method'));
		add_shortcode('ays_poll_cat_gleaderboard', array($this, 'ays_poll_generate_category_gleaderboard_list'));
        add_shortcode('ays_display_polls', array($this, 'ays_generate_display_polls_method'));
	}

	/**
	 * Get instance of this class. Singleton pattern.
	 *
	 * @since    7.4.0
	 */
	public static function get_instance() {
		if (self::$instance == null) {
			self::$instance = new Poll_Maker_Ays_Public(self::$p, self::$v);
		}

		return self::$instance;
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Poll_Maker_Ays_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Poll_Maker_Ays_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */


		wp_enqueue_style( 'ays_poll_font_awesome', POLL_MAKER_AYS_ADMIN_URL . '/css/poll-maker-font-awesome-all.css', array(), $this->version, 'all');
		// wp_enqueue_style('ays_poll_fa_v4_shims', plugin_dir_url(__FILE__) . 'css/font_awesome_v4-shims.css', array(), '5.6.3', 'all');
        wp_enqueue_style( $this->plugin_name . '-select2', POLL_MAKER_AYS_ADMIN_URL . '/css/select2.min.css', array(), $this->version, 'all');
		wp_enqueue_style( $this->plugin_name , plugin_dir_url(__FILE__) . 'css/poll-maker-ays-public.css', array(), $this->version, 'all');
        wp_enqueue_style( $this->plugin_name . '-dataTable-min',  plugin_dir_url(__FILE__) . 'css/poll-maker-dataTables.min.css', array(), $this->version, 'all');

	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Poll_Maker_Ays_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Poll_Maker_Ays_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
        $is_elementor_exists = $this->ays_poll_is_elementor();
		if(!$is_elementor_exists){
            wp_enqueue_script("jquery-effects-core");
            wp_enqueue_script( $this->plugin_name . '-select2', POLL_MAKER_AYS_ADMIN_URL . '/js/select2.min.js', array('jquery'), $this->version, true);
            wp_enqueue_script( $this->plugin_name . '-ajax-public', plugin_dir_url(__FILE__) . 'js/poll-maker-public-ajax.js', array('jquery'), $this->version, true);
            wp_enqueue_script( $this->plugin_name , plugin_dir_url(__FILE__) . 'js/poll-maker-ays-public.js', array('jquery'), $this->version, false);
            wp_enqueue_script( $this->plugin_name . '-category', plugin_dir_url(__FILE__) . 'js/poll-maker-public-category.js', array('jquery'), $this->version, false);
            wp_enqueue_script( $this->plugin_name . '-autosize', plugin_dir_url(__FILE__) . 'js/poll-maker-autosize.js', array('jquery'), $this->version, false);
            
            wp_localize_script( $this->plugin_name . '-ajax-public', 'poll_maker_ajax_public',
                array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'alreadyVoted'  => __( "You have already voted" , $this->plugin_name ),
                    'answerText'    => __( "Answer text" , $this->plugin_name ),
                    'pollTitle'     => __( "Poll title can't be empty" , $this->plugin_name ),
                    'pollQuestion'  => __( "Question can't be empty" , $this->plugin_name ),
                    'pollAnswer'    => __( "You must fill all answers" , $this->plugin_name ),
                    'pollMInAnswer' => __( "Sorry minimum count of answers should be 2" , $this->plugin_name ),
                    'day'           => __( 'day', $this->plugin_name ),
                    'days'          => __( 'days', $this->plugin_name ),
                    'hour'          => __( 'hour', $this->plugin_name ),
                    'hours'         => __( 'hours', $this->plugin_name ),
                    'minute'        => __( 'minute', $this->plugin_name ),
                    'minutes'       => __( 'minutes', $this->plugin_name ),
                    'second'        => __( 'second', $this->plugin_name ),
                    'seconds'       => __( 'seconds', $this->plugin_name ),
                    'restart'       => __( 'Restart', $this->plugin_name ),
                    'refresh'       => __( 'Refresh', $this->plugin_name ),
                    'thank_message' => __( 'Your answer has been successfully sent to the admin. Please wait for the approval.', $this->plugin_name ),
                )
            );
            wp_enqueue_script(  $this->plugin_name . '-datatable-min', plugin_dir_url(__FILE__) . 'js/poll-maker-datatable.min.js', array('jquery'), $this->version, true);
            wp_localize_script( $this->plugin_name . '-ajax-public', 'pollLangDataTableObj', array(
                "sEmptyTable"           => __( "No data available in table", $this->plugin_name ),
                "sInfo"                 => __( "Showing _START_ to _END_ of _TOTAL_ entries", $this->plugin_name ),
                "sInfoEmpty"            => __( "Showing 0 to 0 of 0 entries", $this->plugin_name ),
                "sInfoFiltered"         => __( "(filtered from _MAX_ total entries)", $this->plugin_name ),
                // "sInfoPostFix":          => __( "", $this->plugin_name ),
                // "sInfoThousands":        => __( ",", $this->plugin_name ),
                "sLengthMenu"           => __( "Show _MENU_ entries", $this->plugin_name ),
                "sLoadingRecords"       => __( "Loading...", $this->plugin_name ),
                "sProcessing"           => __( "Processing...", $this->plugin_name ),
                "sSearch"               => __( "Search:", $this->plugin_name ),
                // "sUrl":                  => __( "", $this->plugin_name ),
                "sZeroRecords"          => __( "No matching records found", $this->plugin_name ),
                "sFirst"                => __( "First", $this->plugin_name ),
                "sLast"                 => __( "Last", $this->plugin_name ),
                "sNext"                 => __( "Next", $this->plugin_name ),
                "sPrevious"             => __( "Previous", $this->plugin_name ),
                "sSortAscending"        => __( ": activate to sort column ascending", $this->plugin_name ),
                "sSortDescending"       => __( ": activate to sort column descending", $this->plugin_name ),
            ) );
        }


	}

    public function enqueue_styles_early(){
        wp_enqueue_style( $this->plugin_name , plugin_dir_url(__FILE__) . 'css/poll-maker-ays-public.css', array(), $this->version, 'all');
    }

	public function ays_poll_initialize_shortcode() {
	}

	public function show_chart_js() {
		wp_enqueue_script( $this->plugin_name . '-charts-google', plugin_dir_url(__FILE__) . 'js/google-chart.js', array('jquery'), $this->version, true);
	}
    
    public function show_column_chart_js() {
        // wp_enqueue_script( $this->plugin_name . '-column-chart', 'https://www.gstatic.com/charts/loader.js', array('jquery'), $this->version, true);
        wp_enqueue_script( $this->plugin_name . '-column-chart', plugin_dir_url(__FILE__) . 'js/poll-maker-chart-loader.js', array('jquery'), $this->version, true);
    }

	// Categories shortcode
	public function ays_poll_generate_categories_method($attr) {
		ob_start();
        global $wpdb;
        $id = (isset($attr['id'])) ? absint(intval($attr['id'])) : null;

        if (is_null($id)) {
            echo "<p class='wrong_shortcode_text' style='color:red;'>" . __('Wrong shortcode initialized', $this->plugin_name) . "</p>";
            return false;
        }

        $display = ( isset($attr['display']) && $attr['display'] != '' ) ? $attr['display'] : 'all';
        $layout  = ( isset($attr['layout']) && $attr['layout'] != '' ) ? $attr['layout'] : 'list';
        $count   = ( isset($attr['count']) && $attr['count'] != '' ) ? absint(intval($attr['count'])) : 5;
        $cat_polls_sorting = (isset($attr['sorting']) && $attr['sorting'] != '' ) ? $attr['sorting'] : 'date_asc';

        $style = '';
    	$conteiner_style = '';
        if ($layout == 'grid') {
        	$conteiner_style = 'display: flex; flex-wrap: wrap;';
        	$style = 'margin: 5px;';
        }

        $category = $this->ays_get_poll_category($id);

        $sql = "SELECT * FROM {$wpdb->prefix}ayspoll_polls WHERE  `categories` LIKE '%".$id."%'";

        $content = "";
        $random_poll_id = array();
        if ($display === 'random') {
            $sql .= " ORDER BY RAND() LIMIT ".$count;
        }

        $result = '';
        if($cat_polls_sorting == 'popular_asc' && $display == 'all'){
            $popular_asc_sql = "SELECT p.*
                                FROM {$wpdb->prefix}ayspoll_reports AS r
                                RIGHT JOIN {$wpdb->prefix}ayspoll_polls AS p
                                ON r.poll_id = p.id
                                WHERE  p.categories LIKE '%{$id}%'
                                GROUP BY p.id
                                ORDER BY COUNT(answer_id) ASC LIMIT ".$count;
            $result = $wpdb->get_results($popular_asc_sql, 'ARRAY_A');
        }elseif($cat_polls_sorting == 'popular_desc' && $display == 'all'){
            $popular_desc_sql = "SELECT p.id
                                FROM {$wpdb->prefix}ayspoll_reports AS r
                                RIGHT JOIN {$wpdb->prefix}ayspoll_polls AS p
                                ON r.poll_id = p.id
                                WHERE  p.categories LIKE '%{$id}%'
                                GROUP BY p.id
                                ORDER BY COUNT(answer_id) DESC LIMIT ".$count;
            $result = $wpdb->get_results($popular_desc_sql, 'ARRAY_A');
        }else if($cat_polls_sorting == 'date_asc' && $display == 'all'){
            $sql = "SELECT * FROM {$wpdb->prefix}ayspoll_polls 
                    WHERE  `categories` 
                    LIKE '%".$id."%' 
                    ORDER BY id ASC LIMIT ".$count;
            $result = $wpdb->get_results($sql, 'ARRAY_A');
        }else if($cat_polls_sorting == 'date_desc' && $display == 'all'){
            $sql = "SELECT * FROM {$wpdb->prefix}ayspoll_polls 
                    WHERE  `categories` 
                    LIKE '%".$id."%' 
                    ORDER BY id DESC LIMIT ".$count;
            $result = $wpdb->get_results($sql, 'ARRAY_A');
        }else{
            $sql = "SELECT * FROM {$wpdb->prefix}ayspoll_polls 
                    WHERE  `categories` 
                    LIKE '%".$id."%' 
                    ORDER BY RAND() LIMIT ".$count;
            $result = $wpdb->get_results($sql, 'ARRAY_A');
        }

        
        $check_poll = false;
        $all_poll_count = count($result);
        foreach ($result as $val) {
            $val = absint(intval($val['id']));
            $options = (isset($val['styles']) && $val['styles'] != null) ? json_decode($val['styles'], true) : array();
            $check_poll = $this->check_shedule_expired_poll( $val );
            
        	if (!$check_poll) {
        		continue;
        	}

            $random_poll_id[] = $val;
        }

		$cat_settings_table = esc_sql($wpdb->prefix."ayspoll_settings");
		$cat_key_meta = esc_sql('options');
		$cat_sql = "SELECT meta_value FROM ".$cat_settings_table." WHERE meta_key = %s";
		$ct_sql = $wpdb->get_var(
            $wpdb->prepare( $cat_sql, $cat_key_meta)
        );

		$cat_options_res = ($ct_sql === false) ? json_encode(array()) : $ct_sql;
		$cat_option_res = json_decode($cat_options_res, true);

        if (isset($cat_option_res['show_cat_title']) && $cat_option_res['show_cat_title'] == 'on') {
	        $content .= "<h2 class='ays-poll-category-title' style='text-align:center;'>
	            <span style='font-size:3rem;'>". __( "Category", $this->plugin_name) .":</span>
	            <em>". stripslashes($category['title']) ."</em>
	        </h2>";

	        if(isset($category['description']) && $category['description'] != ''){
	            $content .= "<div class='ays-poll-category-description'>". do_shortcode(stripslashes(wpautop($category['description']))) ."</div>";
	        }        	
        }

   		$content .= "<div class='ays-poll-category-containers' style='".$conteiner_style."'>";
        foreach ($random_poll_id as $poll_id) {
       		$content .= '<div class="ays-poll-main" id="ays-poll-container-'.$poll_id.'" style="'.$style.'">';
            	$content .= '<div class="ays-poll-category-item">';
            		$shortcode = '[ays_poll id="'.$poll_id.'"]';
            		$content .= do_shortcode($shortcode);
            	$content .= '</div>';
        	$content .= '</div>';
        }
    	$content .= '</div>';
        echo $content;
        return  str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
	}
	// Global Leaderboard Shortcode 
	public function ays_poll_generate_gleaderboard_list($attr){
        ob_start();
        global $wpdb;
        $poll_settings = $this->settings;
        $leadboard_res = ($poll_settings->ays_get_setting('leaderboard') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('leaderboard');

        $leadboard = json_decode($leadboard_res, true);

        $glob_leadboard_count   = isset($leadboard['global']['count']) ? $leadboard['global']['count'] : '5' ;
        $glob_leadboard_width   = isset($leadboard['global']['width']) ? $leadboard['global']['width'] : '0' ;
        $glob_leadboard_width   = intval($glob_leadboard_width) == 0 ? '100%' : $glob_leadboard_width ."px";
        $glob_leadboard_orderby = isset($leadboard['global']['orderby']) ? $leadboard['global']['orderby'] : 'id' ;
        $glob_leadboard_color   = isset($leadboard['global']['color']) ? $leadboard['global']['color'] : '#99BB5A' ;
        $glob_leadboard_suctom_css = (isset($leadboard['global']['gleadboard_custom_css']) && $leadboard['global']['gleadboard_custom_css'] != '') ? $leadboard['global']['gleadboard_custom_css'] : '';

        $default_glob_leadboard_columns = array(
            'pos'            => 'pos',
            'name'           => 'name',
            'attempts'  	 => 'attempts',
        );

        $default_glob_leadboard_header_value = array(
            "pos"      => "<th class='ays_poll_glb_pos'>" . __( "Pos.", $this->plugin_name ) . "</th>",
            "name"     => "<th class='ays_poll_glb_user'>" . __( "Name", $this->plugin_name ) . "</th>",
            "attempts" => "<th class='ays_poll_glb_attempts'>" . __( "Attempts", $this->plugin_name ) . "</th>",
        );

        if($glob_leadboard_orderby == 'id'){
            $sql = "SELECT
                        user_id,
                        COUNT(user_id) AS user_count,
                        other_info
                    FROM {$wpdb->prefix}ayspoll_reports
                    WHERE user_id != 0
                    GROUP BY user_id
                    ORDER BY user_count DESC
                    LIMIT ".$glob_leadboard_count;
        }elseif($glob_leadboard_orderby == 'email'){
            $sql = "SELECT
                        user_id,
                        COUNT(user_id) AS user_count,
                        user_email,
                        other_info
                    FROM {$wpdb->prefix}ayspoll_reports
                    WHERE !(user_email='' OR user_email IS NULL)
                    GROUP BY user_email
                    ORDER BY user_count DESC
                    LIMIT ".$glob_leadboard_count;
        }

        $result = $wpdb->get_results($sql, 'ARRAY_A');

        $c = 1;
        $content = '';

        $content .= '
        <style>
            '. $glob_leadboard_suctom_css .'
        </style>';

        $content .= "<div class='ays_poll_glb_container'>
        <table class='ays_poll_glb_table' style='width: ".$glob_leadboard_width.";'>
        	<thead>
            	<tr class='ays_poll_glb_li' style='background: ".$glob_leadboard_color.";'>";
        foreach ($default_glob_leadboard_header_value as $key => $value) {
            $content .= $value;
        }

        $content .="
        		</tr>
        	</thead>
        <tbody>";

        if (!empty($result)) {
            foreach ($result as $val) {
                $user_id = intval($val['user_id']);
                $attempts = (isset($val['user_count']) && $val['user_count'] != '') ? round(floatval($val['user_count']), 2) : '0';
                $options = (isset($val['other_info']) && $val['other_info'] != '') ? json_decode($val['other_info'],true) : array();

                if ($user_id == 0) {
                    $user_name = (isset($options['Name']) && $options['Name'] != '') ? $options['Name'] : __('Guest', $this->plugin_name);
                }else{
                    $user_name = (isset($options['Name']) && $options['Name'] != '') ? $options['Name'] : '';
                    if($user_name == ''){
                        $user = get_user_by('id', $user_id);
                        $user_name = $user->data->display_name ? $user->data->display_name : $user->user_login;
                    }
                }

                $ays_default_html_order = array(
                    "pos"  => "<td class='ays_poll_glb_pos'>$c</td>",
                    "name" => "<td class='ays_poll_glb_user'>$user_name</td>",
                    "attempts" => "<td class='ays_poll_glb_attempts'>$attempts</td>",
                );

                $content .= "<tr class='ays_poll_glb_li'>";
                foreach ($ays_default_html_order as $key => $value) {
                    $content .= $value;
                }

                $content .= "</tr>";
                $c++;
            }
        }

        $content .= "
        		</tbody>
        	</table>
        </div>";

        echo $content;

        return str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
    }
    // Requests Form Shortcode
    public function ays_poll_generate_requests_form_method($attr){
    	ob_start();
        global $wpdb;
        $requests_table = $wpdb->prefix . "ayspoll_requests";
        $category_table = $wpdb->prefix . "ayspoll_categories";

        if (! is_user_logged_in()) {
        	return false;
        }
        $this->enqueue_styles();
        $this->enqueue_scripts();
        wp_enqueue_style( $this->plugin_name . '-animate', POLL_MAKER_AYS_ADMIN_URL . '/css/animate.min.css', array(), $this->version, 'all');
        // wp_enqueue_style( $this->plugin_name . '-bootstrap', POLL_MAKER_AYS_ADMIN_URL . '/css/bootstrap.min.css', array(), $this->version, 'all');
        wp_enqueue_style( $this->plugin_name . '-sweetalert-css', plugin_dir_url(__FILE__) . 'css/poll-maker-sweetalert2.min.css', array(), $this->version, 'all' );
        wp_enqueue_script($this->plugin_name . '-sweetalert-js', plugin_dir_url(__FILE__) . 'js/poll-maker-sweetalert2.all.min.js', array('jquery'), $this->version, true );

        $setting_options = $this->settings->ays_get_setting('options');
        $setting_options = json_decode($setting_options , true);
        $ays_poll_request_default_cats = ( isset($setting_options['ays_poll_request_cats']) && $setting_options['ays_poll_request_cats'] != "" ) ? $setting_options['ays_poll_request_cats'] : "";
        $sql = "SELECT * FROM " . $category_table . " WHERE id IN (".$ays_poll_request_default_cats .")";
        $cat_res = $wpdb->get_results($sql , "ARRAY_A");
        $select = '';
        if(isset($cat_res) && !empty($cat_res)){
            $select = "<select name='ays_poll_select_category' class='ays-poll-select-category' id='ays-poll-request-modal-body-category'>";
            $select .= "<option value=''>".__("Select Category for Poll")."</option>";
            foreach($cat_res as $key => $cat_value){
                $select .= "<option value=".$cat_value['id'].">".$cat_value['title']."</option>";
            }
            $select .= "</select>";
        }

        if (isset($_POST['ays_poll_request_form_submit'])) {
            $user_id = get_current_user_id();
            $user_ip = $this->get_user_ip();

        	$title = (isset($_POST['ays_poll_title']) && $_POST['ays_poll_title'] != '') ? $_POST['ays_poll_title'] : __( "Poll Default Title" , $this->plugin_name);
        	$question = (isset($_POST['ays_poll_question']) && $_POST['ays_poll_question'] != '') ? $_POST['ays_poll_question'] : __( "Question Default Title" , $this->plugin_name);
        	$answers = (isset($_POST['ays_poll_answers']) && $_POST['ays_poll_answers'] != '') ? $_POST['ays_poll_answers'] : array( __( "Answer 1" , $this->plugin_name ) , __( "Answer 2" , $this->plugin_name ) );
            $cat_id = isset($_POST['ays_poll_select_category']) && $_POST['ays_poll_select_category'] != '' ? intval($_POST['ays_poll_select_category']) : 1;
            $category_type = "choosing";

            $options = array(

            );

        	$request_res = $wpdb->insert(
                $requests_table,						
                array(
                    'user_id'       => $user_id,
                    'user_ip'       => $user_ip,
                    'title'         => $title,
                    'question'      => $question,
                    'answers'       => json_encode($answers),
                    'category_type' => $category_type,
                    'request_date'  => current_time( 'mysql' ),
                    'unread'        => 1,
                    'category_id'   => $cat_id,
                    'options'       => json_encode($options),
                ),
                array(
                    '%d', // user_id
                    '%s', // user_ip
                    '%s', // title
                    '%s', // question
                    '%s', // answers
                    '%s', // category_type
                    '%s', // request_date
                    '%d', // unread
                    '%d', // category_id
                    '%s', // options
                )
            );

            $req_last_id = $wpdb->insert_id;
            $get_g_options = $this->settings->ays_get_setting('options');
            $get_g_options = json_decode($get_g_options, true);
            if(!empty($get_g_options)){
                $check_approve_status = isset($get_g_options['enable_auto_approve']) && $get_g_options['enable_auto_approve'] == 'on' ? true : false;
                if($check_approve_status){
                    Pma_Requests_List_Table::ays_poll_add_bulk_approve($req_last_id);
                }
            }
        }

       	$content = '';

       	$content .= '
        <div id="ays-poll-request-modal-main" class="ays_poll_modal">
		    <div class="ays-poll-modal-content" id="ays-poll-request-modal-content">
		        <div class="ays-poll-modal-header" id="ays-poll-request-modal-header">
		            <h4>'.  __("Build your poll request in few seconds", $this->plugin_name) .' </h4>
		        </div>
		        <div class="ays-poll-modal-body" id="poll-request-modal-body">
                    <form method="post" enctype="multipart/form-data" autocomplete="off" id="ays_poll_request_form">
		                <div class="ays_modal_element" id="ays-poll-request-modal-body-title">
		                    <div class="">
		                        <div class="">
		                            <label class="ays-label ays-poll-request-modal-label-title" for="ays-poll-request-modal-title-main">' .__('Poll Title', $this->plugin_name) .'</label>
		                        </div>
		                        <div class="">
		                            <input type="text" class="ays-text-input ays_poll_title" name="ays_poll_title" value="" id="ays-poll-request-modal-title-main"/>
		                        </div>';
                                $content .= '<div class="" style="margin-top: 15px;">
                                                <div>
                                                '.$select.'
                                                </div>';
                                $content .= '</div>
		                    </div>
		                </div>
		                <div class="ays-quick-questions-container" id="ays-poll-request-modal-body-question">
                            <div id="ays-poll-request-modal-body-question-hr"></div>
		                    <div class="ays_modal_element ays_modal_question active_question_border" id="ays_question_id">
		                        <div>
			                        <div>
			                            <label class="ays-label ays-poll-request-modal-label-question" for="ays-poll-request-modal-question-text">' .__('Question', $this->plugin_name) .'</label>
			                        </div>
		                            <div>
		                                <input type="text" class="ays_poll_question" name="ays_poll_question" value="'. __( 'Question Default Title' , $this->plugin_name) .'" id="ays-poll-request-modal-question-text">
		                            </div>
		                        </div>
		                        <div class="ays-modal-flexbox" id="ays-poll-request-modal-answer-box">
		                            <table class="ays_poll_answers_table">
		                                <tr class="ays_poll_answers_td">
			                                <td>
			                                    <input type="text" class="ays_poll_answer ays-poll-request-modal-body-answer-texts" name="ays_poll_answers[]" placeholder="'. __( 'Answer text' , $this->plugin_name ) .'">
			                                </td>
		                                    <td class="ays_poll_remove_answer">
		                                        <i class="ays_poll_fas ays_poll_fa-times" aria-hidden="true"></i>
		                                    </td>
		                                </tr>
		                                <tr class="ays_poll_answers_td">
		                                	<td>
			                                    <input type="text" class="ays_poll_answer ays-poll-request-modal-body-answer-texts" name="ays_poll_answers[]" placeholder="'. __( 'Answer text' , $this->plugin_name ) .'">
			                                </td>
		                                    <td class="ays_poll_remove_answer">
		                                        <i class="ays_poll_fas ays_poll_fa-times" aria-hidden="true"></i>
		                                    </td>
		                                </tr>
		                                <tr class="ays_poll_answers_td">
		                                    <td>
			                                    <input type="text" class="ays_poll_answer ays-poll-request-modal-body-answer-texts" name="ays_poll_answers[]" placeholder="'. __( 'Answer text' , $this->plugin_name ) .'">
			                                </td>
		                                    <td class="ays_poll_remove_answer">
		                                        <i class="ays_poll_fas ays_poll_fa-times" aria-hidden="true"></i>
		                                    </td>
		                                </tr>
		                                <tr class="show_add_answer">
		                                    <td colspan="2" class="ays-poll-request-modal-add-answer">
	                                            <i class="ays_poll_fas ays_poll_fa-plus-square ays_poll_add_answer" aria-hidden="true"></i>
		                                    </td>
		                                </tr>
		                            </table>
		                        </div>
		                    </div>
		                </div>
                        <div class="ays-quick-poll-container-footer" id="ays-poll-request-modal-footer">
		                    <input type="submit" name="ays_poll_request_form_submit" class="ays_submit_button ays_request_submit_button" value="'. __('Submit',$this->plugin_name) .'" id="ays-poll-request-modal-submit"/>
                        </div>
		            </form>
		        </div>
		    </div>
		</div>';

        $default_request_table_columns = array(
            'poll_name' => 'poll_name',
            'request_date' => 'request_date',
            'approved' => 'approved',
        );

        $ays_default_header_value = array(
            "poll_name" => "<th>" . __( "Poll Name", $this->plugin_name ) . "</th>",
            "request_date" => "<th>" . __( "Date", $this->plugin_name ) . "</th>",
            "approved" => "<th>" . __( "Approved", $this->plugin_name ) . "</th>",
        );

        $results = $this->get_user_requests_info();

        if($results !== null && !empty($results)){
            $content .= "<div class='ays-poll-user-results-container'>
            <table id='ays-poll-user-score-page' class='display'>
                <thead>
                    <tr>";

            foreach ($default_request_table_columns as $key => $value) {
                if (isset($default_request_table_columns[$value])) {
                    $content .= $ays_default_header_value[$value];
                }
            }

            $content .= "
                    </tr>
                </thead>";


            foreach($results as $result){
                $title        = isset($result['title']) ? $result['title'] : "";
                $request_date = date_create($result['request_date']);
                $request_date = date_format($request_date, 'H:i:s M d, Y');
                $approved     = isset($result['approved']) ? $result['approved'] : 0;

                $ays_svg = '';
                if ($approved) {
                    $ays_svg .= '<td>
                        <svg class="ays_poll_svg" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 130.2 130.2">
                            <circle class="path circle" fill="none" stroke="#73AF55" stroke-width="6" stroke-miterlimit="10" cx="65.1" cy="65.1" r="62.1"/>
                            <polyline class="path check" fill="none" stroke="#73AF55" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" points="100.2,40.2 51.5,88.8 29.8,67.5 "/>
                        </svg>
                    </td>';
                } else {
                    $ays_svg .= '<td>
                        <svg class="ays_poll_svg" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 130.2 130.2">
                            <circle class="path circle" fill="none" stroke="#D06079" stroke-width="6" stroke-miterlimit="10" cx="65.1" cy="65.1" r="62.1"/>
                            <line class="path line" fill="none" stroke="#D06079" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" x1="34.4" y1="37.9" x2="95.8" y2="92.3"/>
                            <line class="path line" fill="none" stroke="#D06079" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" x1="95.8" y1="38" x2="34.4" y2="92.2"/>
                        </svg>
                    </td>';
                }

                $ays_default_html_order = array(
                    "poll_name" => "<td>$title</td>",
                    "request_date" => "<td>$request_date</td>",
                    "approved" => $ays_svg,
                );

                $content .= "<tr>";
                foreach ($default_request_table_columns as $key => $value) {   
                    if (isset($default_request_table_columns[$value])) {
                        $content .= $ays_default_html_order[$value];
                    }
                }
                $content .= "</tr>";
            }
            $content .= "</table>
                </div>";
        }else{
            $content .= "";
        }

        echo $content;

        return str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
    }

    public function ays_poll_get_range_type_results($id,$type){
        global $wpdb;
        $answer_count = '';
        $answer_sum = '';
        $answer_avg = '';
        if($type == 'range'){            
            $answer_id_sql = "SELECT id FROM {$wpdb->prefix}ayspoll_answers WHERE poll_id=".$id;
            $answer_id_res = $wpdb->get_var($answer_id_sql);
            
            if(isset($answer_id_res)){
                $answer_count_sum_sql = "SELECT SUM(`answer_value`) AS sum, COUNT(`answer_value`) AS count FROM {$wpdb->prefix}ayspoll_reports WHERE answer_id=".$answer_id_res;
                $answer_count_sum_res = $wpdb->get_row($answer_count_sum_sql);

                $answer_count = (isset($answer_count_sum_res->count) && $answer_count_sum_res->count != '') ? intval($answer_count_sum_res->count) : '';
                $answer_sum = (isset($answer_count_sum_res->sum) && $answer_count_sum_res->sum != '') ? intval($answer_count_sum_res->sum) : '';
                if($answer_count != 0){
                    $answer_avg = number_format($answer_sum / $answer_count,2);
                } else{
                    $answer_avg = 0;
                }
            }
        }
        return $answer_avg;
    }   

	public function ays_poll_results_generate_shortcode($attr) {
		ob_start();

        $this->enqueue_styles();
        $this->enqueue_scripts();

		global $wpdb;
		$id = absint(intval($attr['id']));
		$ans_sql  = "SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE poll_id =".$id." AND show_user_added = 1 ORDER BY votes DESC";
		$poll_answers = $wpdb->get_results($ans_sql, 'ARRAY_A');
		$poll_sql  = "SELECT * FROM {$wpdb->prefix}ayspoll_polls WHERE id =".$id;
		$polls = $wpdb->get_row($poll_sql, 'ARRAY_A');
		$show_title = isset($polls['show_title']) && $polls['show_title'] == 0 ? false : true;
		$poll_title = isset($polls['title']) ? $polls['title'] : '';
		$votes_count = $this->get_poll_results_count_by_id($id);
		$poll = $this->get_poll_by_id($id);
        $polls_options = isset($poll['styles']) && !empty($poll['styles']) ? $poll['styles'] : array();
        // $polls_bg_color = isset($polls_options['bg_color']) && $polls_options['bg_color'] != '' ? $polls_options['bg_color'] : '';
        // $polls_main_color = isset($polls_options['text_color']) && $polls_options['text_color'] != '' ? $polls_options['text_color'] : '';
        // $poll_fake_votes  = isset($polls_options['fake_votes']) && $polls_options['fake_votes'] == 'on' ? true : false;
        // $poll_show_percent  = isset($polls_options['show_res_percent']) && $polls_options['show_res_percent'] == '1' ? true : false;
        // $poll_social_buttons   = isset($polls_options['show_social']) && $polls_options['show_social'] == 1 ? true : false;
        $poll_fake_votes  = isset($polls_options['fake_votes']) && $polls_options['fake_votes'] == 'on' ? true : false;
        $fake_added_votes = 0;
        $real_added_votes = 0;
        $sum_of_votes = 0;
        if($poll_fake_votes){
            foreach($poll_answers as $f_key => $_value){
                $r_votes = intval($_value['votes']);
                $f_votes = intval($_value['fake_votes']);
                if($r_votes + $f_votes < 0){
                    $sum_of_votes += $r_votes;
                }
                else{
                    $sum_of_votes += ($f_votes + $r_votes);
                }
            }
        }
        /*******************************************************************************************************/

        $settings_options = $this->settings->ays_get_setting('options');
        $result_options_res = ($settings_options === false) ? json_encode(array()) : $settings_options;
        $result_option_res = json_decode($result_options_res, true);
            
        /*******************************************************************************************************/
        
        $chart_style = false;
        if (isset( $result_option_res['show_result_view']) && ( $result_option_res['show_result_view'] == 'pie_chart' ||  $result_option_res['show_result_view'] == 'column_chart' )) {
            $this->show_chart_js();
            $chart_style = true;
        }

        if (intval($votes_count['res_count']) > 0) {
			$one_percent = 100/intval($votes_count['res_count']);
        }else{
        	$one_percent = 1;
        }

        $poll_inherit_options = isset($result_option_res['ays_poll_results_inherit']) && $result_option_res['ays_poll_results_inherit'] == 'on' ? true : false;

        $add_answer_not_show_up = isset($polls_options['add_answer_show_up']) && $polls_options['add_answer_show_up'] == 0 ? true : false;
        $polls_bg_color =  '';
        $polls_main_color = '';
        $poll_fake_votes  = false;
        $poll_show_percent  = false;
        $poll_social_buttons =  false;
        $poll_hide_result =  false;            
        $polls_bg_color = isset($polls_options['bg_color']) && $polls_options['bg_color'] != '' ? $polls_options['bg_color'] : '';
        $polls_main_color = isset($polls_options['text_color']) && $polls_options['text_color'] != '' ? $polls_options['text_color'] : '';
        if($poll_inherit_options){
            
            $poll_show_percent  = isset($polls_options['show_res_percent']) && $polls_options['show_res_percent'] == '1' ? true : false;
            $poll_social_buttons = isset($polls_options['show_social']) && $polls_options['show_social'] == 1 ? true : false;
            $poll_hide_result = isset($polls_options['hide_results']) && $polls_options['hide_results'] == 1 ? true : false;
        }
        $poll_hide_result_message = isset($polls_options['hide_results_text']) && $polls_options['hide_results_text'] != "" ? wpautop($polls_options['hide_results_text']) : "";
        $show_result_view = isset($result_option_res['show_result_view']) && $result_option_res['show_result_view'] != '' ? $result_option_res['show_result_view'] : 'standart';
        
        // Poll question font size
        $poll_question_font_size_pc     = isset($polls_options['question_font_size']) && $polls_options['question_font_size'] != "" ? esc_attr($polls_options['question_font_size']) : "16"; 
        $poll_question_font_size_mobile = isset($polls_options['question_font_size_mobile']) && $polls_options['question_font_size_mobile'] != "" ? esc_attr($polls_options['question_font_size_mobile']) : "16";


        $content = "";
        $content .= "<style>
            .ays-poll-main .ays_question p{
                font-size: ".$poll_question_font_size_pc."px;
            }
            
            @media only screen and (max-width: 768px){
                .ays-poll-main .ays_question p{
                    font-size: ".$poll_question_font_size_mobile."px;
                }
            }
        </style>";

		$content = '<div class="ays-poll-main" style="border:2px solid; background-color: '.$polls_bg_color.';color: '.$polls_main_color.';padding:20px;" id="ays-poll-container-'.$id.'">';
        $poll_question = isset($polls['question']) ? esc_attr(strip_tags($polls['question'])) : "";
		if($show_title){
			$content .= '<div class="apm-title-box">
							<h5 style="text-align:center;margin: 1rem;">'.stripslashes($poll_title).'</h5>
						</div>';
		}		
		$content .= '<div class="ays_question">
						'.wpautop($poll_question).'
					 </div>';
		if ($votes_count['res_count'] == 0) {
			$content .= '<p style="text-align:center; margin: 0;">No ratings yet</p>';	 	
		}
        $poll_type_for_range_type = isset($polls['type']) ? $polls['type'] : "";
        $avg_ans_range = $this->ays_poll_get_range_type_results($id,$poll_type_for_range_type);

        $aysChartData = array(['','']);
        $poll_range_type_votes = 0;
        $poll_title_position = "";
        foreach ($poll_answers as $key => $c_value) {
            $all_votes_chart = 0;
            $real_votes = isset($c_value['votes']) ? intval($c_value['votes']) : 0;
            if($polls['type'] == 'choosing'){
                $fake_votes = isset($c_value['fake_votes']) ? intval($c_value['fake_votes']) : 0;
                if($poll_fake_votes){
                    if($fake_votes + $real_votes < 0){
                        $all_votes_chart += $real_votes;
                    }
                    else{
                        $all_votes_chart += ($real_votes + $fake_votes);
                    }
                }
                else{
                    $all_votes_chart += $real_votes;
                }

            }
            elseif($polls['type'] == 'range'){
                $poll_title_position = "style='position:relative;'";
                $poll_range_avg = 0;
                $answer_id = isset($c_value['id']) && $c_value['id'] != "" ? intval($c_value['id']) : "";
                $ans_sql  = "SELECT answer_value FROM {$wpdb->prefix}ayspoll_reports WHERE poll_id =".$id." AND answer_id =".$answer_id;
                $poll_range_answer = $wpdb->get_results($ans_sql, 'ARRAY_A');
                if(isset($poll_range_answer) && count($poll_range_answer) > 0){
                    $poll_range_answers_count = count($poll_range_answer);
                    foreach($poll_range_answer as $r_key => $r_value){
                        $poll_range_type_votes += isset($r_value['answer_value']) && $r_value['answer_value'] != "" ? intval($r_value['answer_value']) : 0;
                    }
                    if($poll_range_type_votes > 0){
                        $poll_range_avg = absint($poll_range_type_votes/$poll_range_answers_count);
                        $all_votes_chart = $poll_range_avg;
                        if($show_result_view == 'pie_chart'){
                            $c_value['answer'] = "AVG ".$all_votes_chart;
                        }
                        elseif($show_result_view == 'column_chart'){
                            $c_value['answer'] = "AVG Rate";
                        }
                    }
                }
            }
            else{
                $all_votes_chart += $real_votes;
            }
            $arr = array($c_value['answer'] , $all_votes_chart);
                array_push($aysChartData,$arr);
        }
        $poll_res_style = !$poll_hide_result && !$poll_inherit_options ? "style='height: 425px;display: flex;justify-content: center;'" : '';
        $ays_chart_data = stripcslashes(json_encode($aysChartData, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        if($chart_style){
            $content .= '<div class="results-apm" id="pollAllResultId'.$id.'" '. $poll_res_style .'>';
        }
        else{            
            $content .= '<div class="results-apm" '.$poll_title_position.'>';
        }
        if($poll_hide_result){
            $content .= "<div style='text-align:center;'>" . $poll_hide_result_message . "</div>";
        }
        else{            
            $chart_font_size = "fontSize:15";
            if(isset($poll["type"]) && ($poll["type"] == "voting" || $poll["type"] == "rating" )){
                $chart_font_size = "fontSize:18";
            }
            $title_bg_color = isset($polls_options['main_color']) ? $polls_options['main_color'] : '#fff';
            if($show_result_view == 'pie_chart'){
                $content .=  '
                <script> 
                    window.addEventListener("DOMContentLoaded" , function(){
                        (function ($) {
                            "use strict";    
                            $(document).ready(function () {
                            
                            var aysChartData = '. $ays_chart_data .';
                                google.charts.load("current", {packages:["corechart"]});
                                google.charts.setOnLoadCallback(drawChart);

                                function drawChart() {
                                    var dataGoogle = google.visualization.arrayToDataTable(aysChartData);

                                    var options = {
                                        legend: {position: "right",},
                                        pieSliceText: "label",
                                        chartArea: { 
                                            width: "80%",
                                            height: "80%"
                                        },
                                        height: 400,
                                        '.$chart_font_size.',
                                        legend: {textStyle :{color:"'.$title_bg_color.'"}},
                                        backgroundColor: { fill:"transparent" },
                                    };

                                    var chart = new google.visualization.PieChart(pollAllResultId'.$id.');
                                    chart.draw(dataGoogle, options);
                                }
                            });
                        })(jQuery);
                    });
                </script>';
            }elseif($show_result_view  == 'column_chart'){
                $content .=  '
                <script> 
                    window.addEventListener("DOMContentLoaded" , function(){
                        (function ($) {
                            "use strict";
                            $(document).ready(function () {
                                var aysChartData = '. $ays_chart_data .';
                                google.charts.load("current", {"packages":["bar"]});
                                google.charts.setOnLoadCallback(drawStuff);

                                function drawStuff() {
                                    var dataColumnChart = new google.visualization.arrayToDataTable(aysChartData);

                                    var options = {
                                        maxWidth: "100%",
                                        height: 400,
                                        legend: { position: "none" },
                                        axes: {
                                        x: {
                                        0: { side: "bottom"} 
                                        }
                                    },
                                    bar: { groupWidth: "90%" }
                                    };

                                    var chart = new google.charts.Bar(pollAllResultId'.$id.');
                                
                                    chart.draw(dataColumnChart, google.charts.Bar.convertOptions(options));
                                }
                            });
                        })(jQuery);
                    });
                </script>';
            }else{
                $poll_answers_count = count($poll_answers);
                foreach ($poll_answers as $ans_key => $ans_val) {
                    $real_votes = 0;
                    $percent = round($one_percent*intval($ans_val['votes']));
                    $all_votes_bar = 0;
                    if($polls['type'] == 'choosing'){
                        $real_votes = isset($ans_val['votes']) ? intval($ans_val['votes']) : 0;
                        $fake_votes = isset($ans_val['fake_votes']) ? intval($ans_val['fake_votes']) : 0;
                        if($poll_fake_votes){
                            if($fake_votes + $real_votes < 0){
                                $all_votes_bar += $real_votes;
                            }
                            else{
                                $all_votes_bar += ($real_votes + $fake_votes);
                            }
                        }
                        else{
                            $all_votes_bar += $real_votes;
                        }

                        if($sum_of_votes > 0){
                            $percent = round((100*$all_votes_bar)/$sum_of_votes);
                        }
                    }
                    else{
                        $all_votes_bar = $ans_val['votes'];
                    }
                    
                    $perc_cont = '';
                    $perc_cont_added = '';
                    if($poll_show_percent){
                        if ($percent == 0) {
                            $perc_cont = '';
                            $perc_cont_added = '';
                            
                        }else{
                            $perc_cont = $percent.' %';
                            $perc_cont_added = '('.$percent.'%'.')';
                        }
                    }
                    switch ($polls['type']) {
                        case 'choosing':
                            if ($ans_val['user_added'] == 1 && $add_answer_not_show_up) {
                                break;
                            }else{
                                if ($ans_val['show_user_added'] ==  0){
                                    break;
                                }else{
                                    $content .= '<div class="answer-title flex-apm">
                                    <span class="answer-text">'.stripslashes($ans_val['answer']).'</span>
                                    <span class="answer-votes">'.$all_votes_bar.' '.$perc_cont_added.'</span>
                                    </div>
                                    <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';
                                }
                            }
                            break;
                        case 'text':
                                $content .= '<div class="answer-title flex-apm">
                                <span class="answer-text">'.stripslashes($ans_val['answer']).'</span>
                                <span class="answer-votes">'.$all_votes_bar.' '.$perc_cont_added.'</span>
                                </div>
                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';
                            break;
                        case 'rating':
                            switch ($polls['view_type']) {
                                case 'star':
                                    $star_type  = '';
                                    for ($i=0; $i < intval($ans_val['answer']); $i++) { 
                                        $star_type .= '<i class="ays_poll_far ays_poll_fa-star far"></i>';
                                    }
                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$star_type.'</span>
                                                    <span class="answer-votes">'.$ans_val['votes'].' '.$perc_cont_added.'</span>
                                                </div>
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';
                                    break;
                                case 'emoji':
                                    $emojy_type  = '';
                                    
                                    if ($poll_answers_count == 3) {
                                        switch (intval($ans_val['answer'])) {
                                            case 1:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-frown far"></i>';
                                                break;
                                            case 2:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-meh far"></i>';
                                                break;
                                            case 3:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-smile far"></i>';
                                                break;
                                            default:
                                                break;
                                        }
                                    }else{
                                        switch (intval($ans_val['answer'])) {
                                            case 1:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-tired far"></i>';
                                                break;
                                            case 2:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-frown far"></i>';
                                                break;
                                            case 3:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-meh far"></i>';
                                                break;
                                            case 4:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-smile far"></i>';
                                                break;
                                            case 5:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-dizzy far"></i>';
                                                break;
                                            default:
                                                break;
                                        }
                                    }

                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$emojy_type.'</span>
                                                    <span class="answer-votes">'.$ans_val['votes'].' '.$perc_cont_added.'</span>
                                                </div>
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';
                                    break;
                            }
                            break;
                        case 'voting':
                            switch ($polls['view_type']) {
                                case 'hand':
                                    $hand_type  = '';
                                    if (intval($ans_val['answer'] == 1)) {
                                        $hand_type = '<i class="ays_poll_far ays_poll_fa-thumbs-up far"></i>';
                                    }else{
                                        $hand_type = '<i class="ays_poll_far ays_poll_fa-thumbs-down far"></i>';
                                    }
                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$hand_type.'</span>
                                                    <span class="answer-votes">'.$ans_val['votes'].' '.$perc_cont_added.'</span>
                                                </div>
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';
                                    break;
                                case 'emoji':
                                    $emojy_type  = '';
                                    if (intval($ans_val['answer'] == 1)) { 
                                        $emojy_type = '<i class="ays_poll_far ays_poll_fa-smile far"></i>';
                                    }else{
                                        $emojy_type = '<i class="ays_poll_far ays_poll_fa-frown far"></i>';
                                    }
                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$emojy_type.'</span>
                                                    <span class="answer-votes">'.$ans_val['votes'].' '.$perc_cont_added.'</span>
                                                </div>
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';

                                    break;
                            }
                            break;
                        case 'dropdown':
                            $content .= '<div class="answer-title flex-apm">
                                <span class="answer-text">'.stripslashes($ans_val['answer']).'</span>
                                <span class="answer-votes">'.$ans_val['votes'].' '.$perc_cont_added.'</span>
                                </div>
                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$polls_options['main_color'].'; color: '.$polls_options['bg_color'].';">'.$perc_cont.'</div>';
                            break;
                        case 'range':
                            $content .= '<div class="answer-title flex-apm">
                                </div>
                                <div class="answer-percent_range">
                                    <input type="range" min="0" max="100" value="'.$poll_range_avg.'" class="apm_range_answer_res" disabled title="'.$poll_range_avg.'"> 
                                    
                                </div>
                                <div class="range-value"><span class="range_value_span">'.$poll_range_avg.'</span></div>
                                ';
                            break;

                    }
                    
                }
            }
        }
        if($poll_social_buttons){
            $content .= "<div class='apm-social-btn' style='opacity: 1;'>";
                $content .= "<a class='fb-share-button-res ays-share-btn ays-share-btn-branded ays-share-btn-facebook' title='Share on Facebook'>
                                <span class='ays-share-btn-text'>Facebook</span>
                            </a>";
                $content .= "<a class='twt-share-button-res ays-share-btn ays-share-btn-branded ays-share-btn-twitter' title='Share on Twitter'>
                                <span class='ays-share-btn-text'>Twitter</span>
                            </a>";
                $content .= "<a class='linkedin-share-button-res ays-share-btn ays-share-btn-branded ays-share-btn-linkedin' title='Share on LinkedIn'>
                                <span class='ays-share-btn-text'>LinkedIn</span>
                            </a>";
            $content .= '</div>';
        }

		$content .= '</div>
					</div>';

        echo $content;

		return str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
	}
	
	public function ays_poll_all_generate_shortcode( $attr ) {
		ob_start();
		global $wpdb;
		$all_polls_count = (isset($attr['count']) && $attr['count'] != '' ) ? absint(intval($attr['count'])) : 1844674;
        $all_polls_display = (isset($attr['display']) && $attr['display'] != '' ) ? $attr['display'] : 'all';
        $all_polls_layout = (isset($attr['layout']) && $attr['layout'] != '' ) ? $attr['layout'] : 'list';
        $all_polls_sorting = (isset($attr['sorting']) && $attr['sorting'] != '' ) ? $attr['sorting'] : 'date_asc';
        $poll = '';
        if($all_polls_sorting == 'popular_asc' && $all_polls_display == 'all'){
            $popular_asc_sql = "SELECT p.id
                                FROM {$wpdb->prefix}ayspoll_reports AS r
                                RIGHT JOIN {$wpdb->prefix}ayspoll_polls AS p
                                ON r.poll_id = p.id
                                GROUP BY p.id
                                ORDER BY COUNT(answer_id) ASC LIMIT ".$all_polls_count;
            $poll = $wpdb->get_results($popular_asc_sql, 'ARRAY_A');
        }elseif($all_polls_sorting == 'popular_desc' && $all_polls_display == 'all'){
            $popular_desc_sql = "SELECT p.id
                                FROM {$wpdb->prefix}ayspoll_reports AS r
                                RIGHT JOIN {$wpdb->prefix}ayspoll_polls AS p
                                ON r.poll_id = p.id
                                GROUP BY p.id
                                ORDER BY COUNT(answer_id) DESC LIMIT ".$all_polls_count;
            $poll = $wpdb->get_results($popular_desc_sql, 'ARRAY_A');
        }else if($all_polls_sorting == 'date_asc' && $all_polls_display == 'all'){
            $sql = "SELECT id FROM {$wpdb->prefix}ayspoll_polls ORDER BY id ASC LIMIT ".$all_polls_count;
            $poll = $wpdb->get_results($sql, 'ARRAY_A');
        }else if($all_polls_sorting == 'date_desc' && $all_polls_display == 'all'){
            $sql = "SELECT id FROM {$wpdb->prefix}ayspoll_polls ORDER BY id DESC LIMIT ".$all_polls_count;
            $poll = $wpdb->get_results($sql, 'ARRAY_A');
        }else{
            $sql = "SELECT id FROM {$wpdb->prefix}ayspoll_polls ORDER BY RAND() LIMIT ".$all_polls_count;
            $poll = $wpdb->get_results($sql, 'ARRAY_A');
        }
        $container_style = '';
        $container_divs = '';
        $content_start = '';
        $content_end = '';
        $style = '';
        if($all_polls_layout == 'grid'){
            $container_style = 'display:flex;flex-wrap:wrap';
            $content_start = '<div class="ays_poll_container_all" style="'.$container_style.'">';
            $content_end = '</div>';
            $style = '<style>
                        .ays_poll_container_all>div{
                            margin-left: 5px;
                            width:49% !important;
                        }
                    </style>';
        }else{
            $content_start = '';
            $content_end = '';
            $style  = '';
        }
		
		$this->enqueue_styles();
        $this->enqueue_scripts();
        $checker = array();
        echo $content_start;
        echo $style;
		foreach ($poll as $poll_id) {
            $check_poll = $this->check_shedule_expired_poll( $poll_id['id'] );
            $checker[] = $check_poll;
            if ($check_poll) {
                $this->show_poll($poll_id);                
            }
		}
        echo $content_end;
        echo $style;

        if(array_sum($checker) == 0){
            $poll_settings   = $this->settings;
            $general_options = ($poll_settings->ays_get_setting('options') !== false) ? json_decode($poll_settings->ays_get_setting('options') , true) : array();
            $message = '';
            if(!empty($general_options)){
                $message = (isset($general_options['all_shortcode_message']) && $general_options['all_shortcode_message'] != '') ? esc_html($general_options['all_shortcode_message']) : '';
            }
            echo '<div class="ays_all_res_none_message">'.$message.'</div>';
        }

		return str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
	}

	public function ays_poll_generate_shortcode( $attr ) {
		ob_start();
        $this->enqueue_styles();
        $this->enqueue_scripts();
		$this->show_poll($attr);

		return str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
	}

	public function show_poll( $attr ) {
		if (isset($attr['id'])) {
			return $this->ays_poll_generate_html($attr['id']);
		} elseif (isset($attr['cat_id'])) {
			return $this->ays_poll_category_generate_html($attr);			
		}
	}

	public function ays_poll_generate_html( $poll_id, $echo = true, $width = -1 ) {
		if (!isset($poll_id) || null == $poll_id) {
			return "";
		}

		$id   = absint($poll_id);
		$poll = $this->get_poll_by_id($id);
        $cats = $this->ays_get_poll_category($id);
        $cat_opt = isset($cat['options']) ? json_decode($cat['options'], true) : array();
        $poll_disable_prev = (isset($cat_opt['poll_disable_prev']) && $cat_opt['poll_disable_prev'] == 'on' ) ? true : false;

		if (empty($poll)) {
			return "";
		}

		$this_poll_id = uniqid("ays-poll-id-");
		$options      = $poll['styles'];
        
        $poll_settings = $this->settings;
		$general_options = ($poll_settings->ays_get_setting('options') === false) ? json_encode(array()) : json_decode($poll_settings->ays_get_setting('options'), true);


        if (isset($options['show_result_view']) && ($options['show_result_view'] == 'pie_chart' || $options['show_result_view'] == 'column_chart' )) {
        	$this->show_chart_js();
            $this->show_column_chart_js();
        }
		if (isset($options['published']) && intval($options['published']) === 0) {
			return "";
		}

		$is_expired = false;
		$is_start_soon = false;
		$startDate = '';
		$endDate = '';
		$current_time = strtotime(current_time( "Y:m:d H:i:s" ));
        // ==== ADDED NEW ====

        // Dont show poll cont in schedule
        $poll_check_exp_cont = isset($options['dont_show_poll_cont']) && $options['dont_show_poll_cont'] == 'on' ? true : false;

        // Poll see results button in limitations
        $poll_see_result_button_check = (isset($options['see_result_button']) && $options['see_result_button'] == 'on') ? true : false;
        if(!isset($options['see_result_button'])){
            $poll_see_result_button_check = true;
        }
        $poll_see_result_radio = (isset($options['see_result_radio']) && $options['see_result_radio'] != '') ? esc_attr($options['see_result_radio']) : 'ays_see_result_button';
        $poll_show_result_button_limit = isset($poll_see_result_radio) && $poll_see_result_radio == 'ays_see_result_button' ? true : false;
        $poll_see_result_immediately = isset($poll_see_result_radio) && $poll_see_result_radio == 'ays_see_result_immediately' ? 'checked' : '';
        $poll_show_avatars = isset($options['show_passed_users']) && $options['show_passed_users'] == "on" ? true : false;

        // Loading font size 
		$poll_loader_font_size = (isset($options['loader_font_size']) && $options['loader_font_size'] != '') ? esc_attr($options['loader_font_size']) : '';

        // Show answers numbering
		$show_answers_numbering = (isset($options['show_answers_numbering']) && sanitize_text_field( $options['show_answers_numbering'] ) != '') ? sanitize_text_field( $options['show_answers_numbering'] ) : 'none';


        // ==== ====
        $poll_type_for_range_type = isset($polls['type']) ? $polls['type'] : "";
        $avg_ans_range = $this->ays_poll_get_range_type_results($id,$poll_type_for_range_type);
		if (isset($options['active_date_check']) && !empty($options['active_date_check'])) {
			if (isset($options['activeInterval']) && isset($options['deactiveInterval'])) {
				if (isset($options['activeIntervalSec']) && !empty($options['activeIntervalSec'])) {
					$startDate = strtotime($options['activeInterval']." ".$options['activeIntervalSec']);
					$startDate_atr = $startDate - $current_time;			
				}
				else{
					$startDate = strtotime($options['activeInterval']);
					$startDate_atr = $startDate - $current_time;
				}

				if (isset($options['deactiveIntervalSec']) && !empty($options['deactiveIntervalSec'])) {
					$endDate   = strtotime($options['deactiveInterval']." ".$options['deactiveIntervalSec']);
					$endDate_atr = $endDate - $current_time;
				}
				else{
					$endDate   = strtotime($options['deactiveInterval']);
					$endDate_atr = $endDate - $current_time;
				}

				if ($startDate > $current_time) {
					$is_start_soon = true;
				}
								
				if ($startDate > $current_time || $endDate < $current_time) {
					$is_expired = true;
				}
			}
		}

		$password_check = false;
		$password_right = false;
		$enable_password = false;
        $password_message = '';
		$options['enable_password'] = !isset($options['enable_password']) ? 'off' : $options['enable_password'];
        $poll_password_message = (isset($options['poll_password_message']) &&  $options['poll_password_message'] != '') ? stripslashes( wpautop( $options['poll_password_message'] ) ) : "<p>" . __( "Please enter password", $this->plugin_name ) . "</p>";
        // Enable toggle password visibility
		$options['poll_enable_password_visibility'] = isset($options['poll_enable_password_visibility']) ? $options['poll_enable_password_visibility'] : 'off';
		$poll_enable_password_visibility = (isset($options['poll_enable_password_visibility']) && $options['poll_enable_password_visibility'] == 'on') ? true : false;

        $password_message_with_toggle = "";
		$password_message_with_toggle_class = "";
        $poll_password_message_input = "<input type='password' class='ays-poll-password-input' id='ays_poll_password_val_". $id ."' name='ays_poll_password_val_". $id ."' required autocomplete='off'>";
        if ( $poll_enable_password_visibility ) {
			$password_message_with_toggle_class = "ays-poll-password-input-box-visibility";
			$password_message_with_toggle .= "<img src='". POLL_MAKER_AYS_PUBLIC_URL ."/images/poll-maker-eye-visibility-off.svg' class='ays-poll-password-toggle ays-poll-password-toggle-visibility-off'>";
			$password_message_with_toggle .= "<img src='". POLL_MAKER_AYS_PUBLIC_URL ."/images/poll-maker-eye-visibility.svg' class='ays-poll-password-toggle ays-poll-password-toggle-visibility ays_poll_display_none'>";
		}


        if(isset($options['enable_password']) && $options['enable_password'] == 'on'){     
            $enable_password = true;
	        $password_message = "<div style='padding:50px;text-align:center;' id='ays-poll-password-". $id ."' >
                                <div class='ays-poll-password-title'>
                                    ". $poll_password_message . "
                                </div>
                                <div class='ays-poll-password-box '>
                                    <div class='ays-poll-password-input-box ays-poll-password-input-box-visibility'>
                                        ".$poll_password_message_input."
                                        ".$password_message_with_toggle."
                                    </div>
                                    <div class='ays-poll-password-button-box'>
                                        <input type='submit' class='ays-poll-password-button' name='ays_poll_password_sub_". $id ."'  class='ays_poll_password' value='".__( "Submit", $this->plugin_name )."'>    
                                    </div>
                                </div>
                            </div></div></form></div>";

        }
        
        $password_poll = isset($options['password_poll']) ? $options['password_poll'] : null;

        $password_input_val =  !empty($_POST['ays_poll_password_val_'. $id ]) ? $_POST['ays_poll_password_val_'. $id ] : '';
        $password_check = ($password_input_val == $password_poll) ? true : false;

        if($password_check){
        	$password_right = true;
        }

		$poll_directions = isset($options['poll_direction']) && $options['poll_direction'] != '' ? $options['poll_direction'] : 'ltr';
		$direct_icon_center = false;
		$direct_icon_right = false;
		switch ($poll_directions) {
			case 'ltr':
				$poll_direction = 'ltr';
				break;

			case 'center':
				$poll_direction = 'center';
				$direct_icon_center = true; 
				break;

			case 'rtl':
				$poll_direction = 'rtl';
				$direct_icon_right = true; 
				break;			
		}

		$load_effect = isset($options['load_effect']) ? $options['load_effect'] : "opacity";
		if ($load_effect == 'custom') {
			$load_effect = $options['custom_load'];
		}
		$load_gif = isset($options['load_effect']) && $options['load_effect'] == 'load_gif' && isset($options['load_gif']) ? $options['load_gif'] : "";
        $poll_load_message_data = "";
		if(isset($options['load_effect']) && $options['load_effect'] == "message"){
			$poll_load_message = isset($options['effect_message']) && $options['effect_message'] != "" ?  esc_attr($options['effect_message']) : "";
			$poll_load_message_data = 'data-load-message="'.$poll_load_message.'"';
		}


		if (isset( $options['redirect_after_submit'] ) && $options['redirect_after_submit'] == 1) {
			if (isset($options['redirect_users']) && $options['redirect_users'] != 0 && !empty($options['redirect_after_vote_url'])) {
				$redirect_after_vote_url = stripslashes($options['redirect_after_vote_url']);
				$redirect_users          = $options['redirect_users'];
				$redirect_delay          = $options['redirect_after_vote_delay'];
			}else{
				$redirect_after_vote_url = '';
				$redirect_users          = 0; 
				$redirect_delay          = 0;
			}
			$redirect_url_href       = '';
			$redirect_url_checked    = $options['redirect_after_submit'];
			$redirect_after_vote     = "<p class='redirectionAfterVote'>" . __("You will be redirected ".($redirect_delay <= 0 ? "" : " after <span>".$redirect_delay."</span> seconds "), $this->plugin_name) . "</p>";
		}elseif (isset($options['redirect_users']) && $options['redirect_users'] != 0 && !empty($options['redirect_after_vote_url'])) {
			$redirect_after_vote_url = stripslashes($options['redirect_after_vote_url']);
			$redirect_url_href       = '';
			$redirect_users          = $options['redirect_users'];
			$redirect_delay          = $options['redirect_after_vote_delay'];
			$redirect_url_checked    = 0;
			$redirect_after_vote     = "<p class='redirectionAfterVote'>" . __("You will be redirected ".($redirect_delay <= 0 ? "" : " after <span>".$redirect_delay."</span> seconds "), $this->plugin_name) . "</p>";
		} else {
			$redirect_after_vote_url = '';
			$redirect_url_href       = '';
			$redirect_users          = 0;
			$redirect_delay          = 0;
			$redirect_url_checked    = 0;
			$redirect_after_vote     = "";
		}		

		if (!empty($options['info_form']) && !empty($poll['fields'])) {
			$fields          = $poll['fields'];
			$required_fields = $poll['required_fields'];
			$form_title      = isset($options['info_form_title']) ? stripslashes($options['info_form_title']) : "<h5>" . __("Please fill out the form:", $this->plugin_name) . "</h5>";
		}
		if (isset($options['show_social']) && $options['show_social'] == 1) {
			$show_social = true;
		} else {
			$show_social = false;
		}

		$without_vote = isset($options['enable_vote_btn']) && $options['enable_vote_btn'] == 0 ? 'apm-answers-without-submit' : "";
		$allow_add_answer   = isset($options['user_add_answer']) && $options['user_add_answer'] == 1 ? true : false;
		$add_answer_not_show_up = isset($options['add_answer_show_up']) && $options['add_answer_show_up'] == 0 ? true : false;

		if (isset($options['hide_results']) && $options['hide_results'] == 1) {
			$hide_results = "1";
			if (!empty($options['hide_results_text'])) {
				$hide_results_text = wpautop($options['hide_results_text']);
			} else {
				$hide_results_text = "Thanks for your answer";
			}
		} else {
			$hide_results      = "0";
			$hide_results_text = "";
		}
		$limit_users        = 0;
		$load_poll          = false;
		$limit_users_option = (isset($options['limit_users']) && $options['limit_users'] == 1);

		$attempts_count = 0;
		if($limit_users_option){
            $attempts_count = isset($options['attempts_count']) ? intval($options['attempts_count']) : 0;
        }

		if (isset($options['vote_reason']) && $options['vote_reason'] == 1) {
			$voteReason = "<div class='voteReason'>
                                <div class='forReason'>". __("Please add vote reason", $this->plugin_name)."</div>                         
                                <div><textarea name='voteReason' id='reasonTxt'></textarea></div>
                            </div>";
		} else {
			$voteReason = "";
		}

        //limit user by country
        $enable_limit_user_by_country = (isset($options['enable_limit_by_country']) && $options['enable_limit_by_country'] == 'on') ? true : false;
        $blocked_user_country = (isset($options['limit_country']) && $options['limit_country'] != '') ? $options['limit_country'] : '';

		$answer_icons = array(
			'thumb' => array(
				"<i class='ays_poll_far ays_poll_fa-thumbs-up'></i>",
				"<i class='ays_poll_far ays_poll_fa-thumbs-down'></i>"
			),
			'emoji' => array(
				"<i class='ays_poll_far ays_poll_fa-dizzy'></i>",
				"<i class='ays_poll_far ays_poll_fa-smile'></i>",
				"<i class='ays_poll_far ays_poll_fa-meh'></i>",
				"<i class='ays_poll_far ays_poll_fa-frown'></i>",
				"<i class='ays_poll_far ays_poll_fa-tired'></i>",
			),
			'star'  => "<i class='ays_poll_far ays_poll_fa-star'></i>"
		);

		$bg_color        	= $options['bg_color'];
		$bg_image        	= isset($options['bg_image']) ? $options['bg_image'] : '';
		$main_color      	= $options['main_color'];
		$text_color      	= $options['text_color'];
		$icon_color      	= $options['icon_color'];
		$answer_bg_color 	= !empty($options['answer_bg_color']) ? $options['answer_bg_color'] : $bg_color;
        $answer_border_side = isset($options['answer_border_side']) ? $options['answer_border_side'] : 'all_sides';
		$title_bg_color  	= !empty($options['title_bg_color']) ? $options['title_bg_color'] : $bg_color;

		switch ( absint($poll['theme_id']) ) {
			case 3:
			case 4:
				$poll_theme           = 'ays-shape-theme';
				$answer_percent_color = $this->rgb2hex($main_color);
				break;
			case 5:
				$poll_theme           = 'ays-coffee-theme';
				$answer_percent_color = $this->rgb2hex($text_color);
				break;
			case 6:
				$poll_theme           = 'ays-aqua-theme';
				$answer_percent_color = $this->rgb2hex($icon_color);
				$title_bg_color       = !empty($options['title_bg_color']) ? $options['title_bg_color'] : $main_color;
				break;
			case 7:
				$poll_theme           = 'ays-minimal-theme';
				$answer_percent_color = $this->rgb2hex($icon_color);
				// $answer_bg_color      = $main_color;
				break;
			default:
				$poll_theme           = 'ays-classic-theme';
				$answer_percent_color = $this->rgb2hex($main_color);
				break;
		}

		$enable_pass_count = (isset($options['enable_pass_count']) && $options['enable_pass_count'] == 'on') ? true : false;
        $fake_votes        = (isset($options['fake_votes']) && $options['fake_votes'] == 'on') ? true : false;

		if ($enable_pass_count) {
            $poll_result_reports = $this->get_poll_results_count_by_id($id);
            if($fake_votes){
                $fake_votes_count = $this->ays_get_fake_votes($id);
                $real_votes = isset($poll_result_reports['res_count']) && $poll_result_reports['res_count'] != '' ? intval(esc_html($poll_result_reports['res_count'])) : 0;
                $all_votes = 0;
                if(isset($fake_votes_count)){
                    foreach($fake_votes_count as $f_key => $_value){
                        $r_votes = intval($_value['votes']);
                        $f_votes = intval($_value['fake_votes']);
                        if($r_votes + $f_votes < 0){
                            $all_votes += $r_votes;
                        }
                        else{
                            $all_votes += ($f_votes + $r_votes);
                        }
                    }
                }
                $poll_result_reports = "<span class='ays_poll_passed_count'><i class='ays_poll_fas ays_poll_fa-users' aria-hidden='true'></i> " . $all_votes . "</span>";
            }
            else{
                $poll_result_reports = "<span class='ays_poll_passed_count'><i class='ays_poll_fas ays_poll_fa-users' aria-hidden='true'></i> " . $poll_result_reports['res_count'] . "</span>";
            }
		} else {
			$poll_result_reports = '';
		}

		$result_sort    = isset($options['result_sort_type']) ? $options['result_sort_type'] : "none";
		$result_in_rgba = isset($options['result_in_rgba']) && $options['result_in_rgba'] == 1 ? true : false;
		if ($width < 0) {
			$poll_width = $options['width'] > 0 ? $options['width'] . "px" : "100%";
		} elseif ($width == 0) {
			$poll_width = "100%";
		} else {
			$poll_width = $width . "px";
		}

        // See Results button text
        $ays_see_result_button  = (isset($options['see_res_btn_text']) && $options['see_res_btn_text'] != '') ? stripslashes($options['see_res_btn_text']) : 'See Results';

        if ($ays_see_result_button === 'See Results') {
            $ays_see_result_button_text =  __("See Results", $this->plugin_name);
        }else{
            $ays_see_result_button_text = $ays_see_result_button;
        }

        // Vote button text
        $ays_vote_button = (isset($options['btn_text']) && $options['btn_text'] != '') ? stripslashes($options['btn_text']) : 'Vote';

        if ($ays_vote_button === 'Vote') {
            $ays_vote_button_text =  __("Vote", $this->plugin_name);
        }else{
            $ays_vote_button_text = $ays_vote_button;
        }

		$show_res_btn_sch = (isset($options['show_result_btn_schedule']) && $options['show_result_btn_schedule'] == 1) ? true : false;
		$see_result_button = '';
		$see_result_button = wp_nonce_field('ays_finish_poll', 'ays_finish_poll') . "<div class='apm-button-box'>";
        if($poll['type'] != "text"){
			$see_result_button .= "<input type='button' class='btn ays-poll-btn {$poll['type']}-btn ays-see-res-button-show' data-form='$this_poll_id' value='" . $ays_see_result_button_text . "' data-seeRes='true' data-type='".$poll['type']."'>";
		}
		$see_result_button .= '</div>';

        // Enable View more button
        $enable_view_more_button = (isset($options['enable_view_more_button']) && $options['enable_view_more_button'] == 'on' ) ? true : false;
        $poll_view_more_button_count = (isset($options['poll_view_more_button_count']) && $options['poll_view_more_button_count'] != '' ) ? absint(intval($options['poll_view_more_button_count'])) : 0;

		/* 
         * Poll container background gradient Aro
         * 
         */
        
        // Checking exists background gradient option
        $options['enable_background_gradient'] = (!isset($options['enable_background_gradient'])) ? "off" : $options['enable_background_gradient'];
        
        if(isset($options['background_gradient_color_1']) && $options['background_gradient_color_1'] != ''){
            $background_gradient_color_1 = $options['background_gradient_color_1'];
        }else{
            $background_gradient_color_1 = "#103251";
        }

        if(isset($options['background_gradient_color_2']) && $options['background_gradient_color_2'] != ''){
            $background_gradient_color_2 = $options['background_gradient_color_2'];
        }else{
            $background_gradient_color_2 = "#607593";
        }

        if(isset($options['poll_gradient_direction']) && $options['poll_gradient_direction'] != ''){
            $poll_gradient_direction = $options['poll_gradient_direction'];
        }else{
            $poll_gradient_direction = 'vertical';
        }
        switch($poll_gradient_direction) {
            case "horizontal":
                $poll_gradient_direction = "to right";
                break;
            case "diagonal_left_to_right":
                $poll_gradient_direction = "to bottom right";
                break;
            case "diagonal_right_to_left":
                $poll_gradient_direction = "to bottom left";
                break;
            default:
                $poll_gradient_direction = "to bottom";
        }

        // Poll container background gradient enabled/disabled        
        if(isset($options['enable_background_gradient']) && $options['enable_background_gradient'] == "on"){
            $enable_background_gradient = true;
        }else{
            $enable_background_gradient = false;
        }

       	if( isset($bg_image) && $bg_image != false){
            $poll_styles =  "background-image: url('".$bg_image."');";
        }elseif($enable_background_gradient) {
            $poll_styles =  "background-image: linear-gradient($poll_gradient_direction, $background_gradient_color_1, $background_gradient_color_2);";
        }elseif (isset($bg_color)) {
        	$poll_styles = "background-color: ".$bg_color.";";
        }
        else{

        	$poll_styles = "background-image: unset;";
        }
        
        $options['enable_answer_style'] = isset($options['enable_answer_style']) ? $options['enable_answer_style'] : 'on';
        $answer_style = $options['enable_answer_style'] == 'on' ? true : false;

        $disable_answer_hover = isset($options['disable_answer_hover']) && $options['disable_answer_hover'] == 1 ? 'disable_hover' : 'ays_enable_hover';

        //Bg image position
        $poll_bg_image_position = (isset($options['poll_bg_image_position']) && $options['poll_bg_image_position'] != "") ? $options['poll_bg_image_position'] : 'center center';
        $poll_bg_img_in_finish_page = (isset($options['poll_bg_img_in_finish_page']) && $options['poll_bg_img_in_finish_page'] == "on") ? 'true' : "false";

        // Poll minimal height
        $poll_min_height_val = (isset($options['poll_min_height']) && $options['poll_min_height'] != '') ? absint(intval($options['poll_min_height'])) : 0;

        if ($poll_min_height_val == 0) {
            $poll_min_height = '';
        }else{
            $poll_min_height = 'min-height: '. $poll_min_height_val .'px;';
        }

        //limit user by country
        $enable_limit_user_by_country = (isset($options['enable_limit_by_country']) && $options['enable_limit_by_country'] == 'on') ? true : false;
        $blocked_user_country = (isset($options['limit_country']) && $options['limit_country'] != '') ? $options['limit_country'] : '';

        // Poll background size
        $background_size = isset($options['background_size']) ? $options['background_size'] : 'unset'; 

        $options['show_answers_caption'] = isset($options['show_answers_caption']) ? $options['show_answers_caption'] : 'on';
		$show_answers_caption = (isset($options['show_answers_caption']) && $options['show_answers_caption'] == 'on') ? true : false;

		// Show answers icon
		$options['show_answers_icon'] = isset($options['show_answers_icon']) ? $options['show_answers_icon'] : 'off';
		$show_answers_icon = (isset($options['show_answers_icon']) && $options['show_answers_icon'] == 'on') ? true : false;
		$options['answers_icon'] = isset($options['answers_icon']) ? $options['answers_icon'] : 'radio';

        // Poll Logo
        $poll_logo_image = (isset($options['logo_image']) && $options['logo_image'] != '') ? esc_url($options['logo_image']) : '';
        $poll_logo_check = (isset($poll_logo_image) && $poll_logo_image != '') ? true : false;
        $poll_image_cont = '';
        // Poll logo image url
		$poll_logo_image_url       = isset($options['poll_logo_url']) && $options['poll_logo_url'] != "" ? esc_attr($options['poll_logo_url']) : ""; 
		$poll_logo_image_url_check = isset($options['poll_enable_logo_url']) && $options['poll_enable_logo_url'] == "on" ? true : false;
		$poll_logo_image_url_href  = "javascript:void(0)";
		if($poll_logo_image_url_check){
			if($poll_logo_image_url != ""){
				if(filter_var($poll_logo_image_url, FILTER_VALIDATE_URL)){
					$poll_logo_image_url_href = $poll_logo_image_url;
				}
			}
		}
        if($poll_logo_check){
            $poll_image_cont = "<div class='ays-image-logo-show'><a href='".$poll_logo_image_url_href."' class='ays-poll-logo-image-url-link'><img src=".$poll_logo_image." class='ays-poll-image-logo'></a></div>";
        }

        if(isset($options['enable_box_shadow']) && $options['enable_box_shadow'] == 'on'){
            $enable_box_shadow = true;
        }else{
            $enable_box_shadow = false;
        }

        if(isset($options['box_shadow_color']) && $options['box_shadow_color'] != ''){
            $box_shadow_color = $options['box_shadow_color'];
        }else{
            $box_shadow_color = "#333";
        }

        if($enable_box_shadow){
            $poll_box_shadow_css =  "box-shadow: 0 0 15px 1px " . $this->hex2rgba($box_shadow_color, '0.4') . ";";
        }else{
            $poll_box_shadow_css =  "box-shadow: none;";
        }

		// Poll container max-width for mobile
		$poll_mobile_max_width = isset($options['poll_mobile_max_width']) && $options['poll_mobile_max_width'] != '' ? esc_attr($options['poll_mobile_max_width']) . '%' : "100%";
		/*
        ==========================================
            Buttons styles
        ==========================================
		*/
		
        // Buttons font size
        $buttons_font_size = '17px';
        if(isset($options['buttons_font_size']) && $options['buttons_font_size'] != ''){
            $buttons_font_size = $options['buttons_font_size'] . 'px';
        }

        // Buttons mobile font size
        $poll_buttons_mobile_font_size = isset($options['poll_buttons_mobile_font_size']) && $options['poll_buttons_mobile_font_size'] != '' ? esc_attr($options['poll_buttons_mobile_font_size']) . 'px' : $buttons_font_size;

        // Buttons Left / Right padding
        $buttons_left_right_padding = '20px';
        if(isset($options['buttons_left_right_padding']) && $options['buttons_left_right_padding'] != ''){
            $buttons_left_right_padding = $options['buttons_left_right_padding'] . 'px';
        }

        // Buttons Top / Bottom padding
        $buttons_top_bottom_padding = '10px';
        if(isset($options['buttons_top_bottom_padding']) && $options['buttons_top_bottom_padding'] != ''){
            $buttons_top_bottom_padding = $options['buttons_top_bottom_padding'] . 'px';
        }

        // Buttons border radius
        $buttons_border_radius = '3px';
        if(isset($options['buttons_border_radius']) && $options['buttons_border_radius'] != ''){
            $buttons_border_radius = $options['buttons_border_radius'] . 'px';
        }

        /*
        ==========================================
            Ani
        ==========================================
            Answers styles
        ==========================================
            Start
        ==========================================
        */
        $ans_img = '';
        foreach ( $poll['answers'] as $index => $answer ) {
            $ans_img = $answer['answer_img'];
        }

        // Answers view
        $answer_view_class = "list";
        if(isset($options['answers_view']) && $options['answers_view'] != ''){
            $answer_view_class = $options['answers_view'];
        }

        // Answers font size
        $answers_font_size = '16';
        if(isset($options['answers_font_size']) && $options['answers_font_size'] != ""){
            $answers_font_size = $options['answers_font_size'];
        }

        // Poll answers font size on mobile
		$poll_answer_font_size_mobile  = (isset($options['poll_answer_font_size_mobile']) && $options['poll_answer_font_size_mobile'] != '') ? esc_attr($options['poll_answer_font_size_mobile']) : '16';

        // Answers padding option
        $answers_padding = '10';
        if(isset($options['answers_padding']) && $options['answers_padding'] !== ''){
            $answers_padding = $options['answers_padding'];
        }

        // Answers margin option
        $answers_margin = '10';
        if(isset($options['answers_margin']) && $options['answers_margin'] != ''){
            $answers_margin = $options['answers_margin'];
        }

        // Answers border options
        $options['answers_border'] = (isset($options['answers_border'])) ? $options['answers_border'] : 'on';
        $answers_border = false;
        if(isset($options['answers_border']) && $options['answers_border'] == 'on'){
            $answers_border = true;
        }
        $answers_border_width = '0';
        if($answers_border && isset($options['answers_border_width']) && $options['answers_border_width'] != ''){
            $answers_border_width = $options['answers_border_width'];
            if(isset($options['enable_answer_style']) && $options['enable_answer_style'] != "on"){
                $answers_border_width = "0";
            }
        }
        $answers_border_style = 'solid';
        if($answers_border && isset($options['answers_border_style']) && $options['answers_border_style'] != ''){
            $answers_border_style = $options['answers_border_style'];
        }
        $answers_border_color = '#444';
        if($answers_border && isset($options['answers_border_color']) && $options['answers_border_color'] != ''){
            $answers_border_color = $options['answers_border_color'];
        }
        
        if($answers_border == false){
            $answers_border_style = 'solid';
            $answers_border_color = '';
        }
        // Question Font Size
        $poll_question_font_size_pc     = isset($options['question_font_size']) && $options['question_font_size'] != "" ? esc_attr($options['question_font_size']) : "16"; 
        $poll_question_font_size_mobile = isset($options['question_font_size_mobile']) && $options['question_font_size_mobile'] != "" ? esc_attr($options['question_font_size_mobile']) : "16";

        // Poll question image height
		$poll_question_image_height = isset($options['poll_question_image_height']) && $options['poll_question_image_height'] != "" ? esc_attr($options['poll_question_image_height'])."px" : "100%";

        //answer border radius
        $answers_border_radius = (isset($options['answers_border_radius']) && $options['answers_border_radius'] != '') ? $options['answers_border_radius'] : '0';

        // Answers image options
        // Show answers caption
        $options['show_answers_caption'] = isset($options['show_answers_caption']) ? $options['show_answers_caption'] : 'on';
        $show_answers_caption = (isset($options['show_answers_caption']) && $options['show_answers_caption'] == 'on') ? true : false;

        $ays_poll_show_answers = '';
        if($show_answers_caption == false){
            $ays_poll_show_answers = 'display:none';
        }

        $ans_img_height = '15em';
        if(isset($options['ans_img_height']) && $options['ans_img_height'] != ''){
            $ans_img_height = $options['ans_img_height']."px";
        }

        // Poll answer image height for mobile
        $poll_answer_image_height_for_mobile = "150";
     	$poll_answer_image_height_for_mobile = (isset($options['poll_answer_image_height_for_mobile']) && $options['poll_answer_image_height_for_mobile'] != "") ? esc_attr($options['poll_answer_image_height_for_mobile']) : "150";


        $ans_img_caption_position = 'bottom';
        if(isset($options['ans_img_caption_position']) && $options['ans_img_caption_position'] != ''){
            $ans_img_caption_position = $options['ans_img_caption_position'];
        }

        $answers_object_fit = 'cover';
        if(isset($options['answers_object_fit']) && $options['answers_object_fit'] != ''){
            $answers_object_fit = $options['answers_object_fit'];
        }

        $ans_image_caption_style = 'outside';
        $ans_img_caption_style = "column-reverse";
        if(isset($options['ans_img_caption_style']) && $options['ans_img_caption_style'] != ''){
            $ans_image_caption_style = $options['ans_img_caption_style'];
        }
        $ans_image_caption_position = $ans_img_caption_position;
        $answers_grid_column = (isset($options['answers_grid_column']) && $options['answers_grid_column'] != '') ? $options['answers_grid_column'] : '2';

		// Poll title font size
		$poll_title_font_size    = (isset($options['poll_title_font_size']) && $options['poll_title_font_size'] != "") ? absint(intval(esc_attr($options['poll_title_font_size']))) : "18";

        // Poll title alignment
		$poll_title_alignment    = ( isset($options['poll_title_alignment']) && $options['poll_title_alignment'] != "" ) ? esc_attr($options['poll_title_alignment']) : "center";

        // ===== Poll text type options start =====
        $poll_view_type_text = isset($poll['view_type']) && $poll['view_type'] != "" ? $poll['view_type'] : "short_text";

        $poll_text_type_length_enable = ( isset($options['poll_text_type_length_enable']) && $options['poll_text_type_length_enable'] == "on" ) ? true : false;
		$poll_text_type_limit_type    = ( isset($options['poll_text_type_limit_type']) && $options['poll_text_type_limit_type'] != "" ) ? esc_attr($options['poll_text_type_limit_type']) : "characters";
		$poll_text_type_limit_length  = ( isset($options['poll_text_type_limit_length']) && $options['poll_text_type_limit_length'] != "" ) ? esc_attr($options['poll_text_type_limit_length']) : "";
		$poll_text_type_limit_message = ( isset($options['poll_text_type_limit_message']) && $options['poll_text_type_limit_message'] == "on" ) ?  true : false;
        $poll_text_type_width         = (isset($options['poll_text_type_width']) && $options['poll_text_type_width'] != "") ?  stripslashes(esc_attr($options['poll_text_type_width'])) : "";
		$poll_text_type_width_type    = (isset($options['poll_text_type_width_type']) && $options['poll_text_type_width_type'] != "") ?  esc_attr($options['poll_text_type_width_type']) : "percent";

        $poll_class_for_limits = $poll_text_type_length_enable ? "ays_poll_question_limit_length" : "";
		$poll_box_for_limit_message = "";
		if($poll_text_type_limit_message){
			$poll_box_for_limit_message = '<div class="ays_poll_question_text_conteiner">
												<div class="ays_poll_question_text_message">
													<span class="ays_poll_question_text_message_span">'. $poll_text_type_limit_length . '</span> ' . $poll_text_type_limit_type . ' '.  __( ' left' , $this->plugin_name ) . '
												</div>
											  </div>';
		}

        $poll_text_type_ready_width = "";
		$poll_text_type_ready_type  = "%";
		if($poll['type'] == 'text'){
			if($poll_view_type_text == "short_text"){
				if($poll_text_type_width == "" || intval($poll_text_type_width) == 0){
					$poll_text_type_ready_width = "60";
					$poll_text_type_ready_type  = "%";
				}
				else{
					$poll_text_type_ready_width = $poll_text_type_width;
					$poll_text_type_ready_type  = ($poll_text_type_width_type == "percent" ? "%" : "px");
				}
			}
			else{
				if($poll_text_type_width == "" || intval($poll_text_type_width) == 0){
					$poll_text_type_ready_width = "100";
					$poll_text_type_ready_type  = "%";
				}
				else{
					$poll_text_type_ready_width = $poll_text_type_width;
					$poll_text_type_ready_type  = ($poll_text_type_width_type == "percent" ? "%" : "px");
				}
			}
		}
        // ===== Poll text type options end =====
        $poll_align_items = '';
        $poll_answers_margin = '';
        $vote_button_margin = '';
        $poll_justify_content = '';
        if($poll['view_type']== 'list'){
            $poll_align_items = 'align-items:center';
            // $poll_answers_margin = 'margin:0 20px';
            if($ans_image_caption_position == 'top'){
                $ans_img_caption_style = "row-reverse";
            }elseif($ans_image_caption_position == 'bottom'){
                $ans_img_caption_style = "row";
            }
        }elseif($poll['view_type']== 'grid'){
            $poll_align_items = '';
            $poll_answers_margin = '';
            if($ans_img != ''){
                if($ans_image_caption_position == 'top'){
                    $ans_img_caption_style = "column-reverse";
                    if($ans_image_caption_style == 'outside'){
                        $ans_img_caption_position = "";
                    }elseif($ans_image_caption_style == 'inside'){
                        $ans_img_caption_position = "position:absolute;".$ans_img_caption_position.":0;padding:5px 0;";
                    }
                }elseif($ans_image_caption_position == 'bottom'){
                    $ans_img_caption_style = "column";
                    if($ans_image_caption_style == 'outside'){
                        $ans_img_caption_position = "";
                        $vote_button_margin = 'margin-top:30px';
                    }elseif($ans_image_caption_style == 'inside'){
                        $ans_img_caption_position = "position:absolute;".$ans_img_caption_position.":0;padding:5px 0;";
                    }
                }
            }else{
                $poll_justify_content = 'justify-content:center';
                $poll_align_items = 'align-items:center';
            }
        }

        // Answers box shadow
        $answers_box_shadow = false;
        $answers_box_shadow_color = isset($options['answers_box_shadow_color']) && $options['answers_box_shadow_color'] != '' ? $options['answers_box_shadow_color'] : '';
        $poll_answer_box_shadow_x_offset = isset($options['poll_answer_box_shadow_x_offset']) && $options['poll_answer_box_shadow_x_offset'] != '' ? intval($options['poll_answer_box_shadow_x_offset']) : 0;

		$poll_answer_box_shadow_y_offset = isset($options['poll_answer_box_shadow_y_offset']) && $options['poll_answer_box_shadow_y_offset'] != '' ? intval($options['poll_answer_box_shadow_y_offset']) : 0;

		$poll_answer_box_shadow_z_offset = isset($options['poll_answer_box_shadow_z_offset']) && $options['poll_answer_box_shadow_z_offset'] != '' ? intval($options['poll_answer_box_shadow_z_offset']) : 10;

        if(isset($options['answers_box_shadow']) && $options['answers_box_shadow'] == 'on'){
            $answers_box_shadow = true;
        }
        if($answers_box_shadow){
            $answers_box_shadow_color = 'box-shadow: '.$poll_answer_box_shadow_x_offset.'px '.$poll_answer_box_shadow_y_offset.'px '.$poll_answer_box_shadow_z_offset.'px '.$answers_box_shadow_color;
        }else{
            $answers_box_shadow_color = 'box-shadow:unset';
        }

        $answer_margin_grid_3 = $answers_margin/3;
        $answer_margin_grid_4 = $answers_margin/4;
        $answer_margin_grid_2 = $answers_margin/2;

        // Not choosing Poll type icons size 
        $not_choosing_font_size = isset($options['icon_size']) && $options['icon_size'] != "" ? esc_attr($options['icon_size']) : "15";

        $show_result_view_for_dir = isset($options['show_result_view']) && ($options['show_result_view'] != "standart" || $options['show_result_view'] != "not_reloading") ? true : false;

        // Title text shadow
        $options['enable_poll_title_text_shadow'] = (isset($options['enable_poll_title_text_shadow']) && $options['enable_poll_title_text_shadow'] == 'on') ? 'on' : 'off'; 
        $enable_poll_title_text_shadow = (isset($options['enable_poll_title_text_shadow']) && $options['enable_poll_title_text_shadow'] == 'on') ? true : false; 
        $poll_title_text_shadow = ( isset( $options['poll_title_text_shadow'] ) && $options['poll_title_text_shadow'] != '' ) ? stripslashes( esc_attr( $options['poll_title_text_shadow'] ) ) : 'rgba(255,255,255,0)';
        $poll_title_text_shadow_x_offset = (isset($options['poll_title_text_shadow_x_offset']) && $options['poll_title_text_shadow_x_offset'] != '') ? stripslashes( esc_attr( $options['poll_title_text_shadow_x_offset'] ) ) : 2;

        $poll_title_text_shadow_y_offset = (isset($options['poll_title_text_shadow_y_offset']) && $options['poll_title_text_shadow_y_offset'] != '') ? stripslashes( esc_attr( $options['poll_title_text_shadow_y_offset'] ) ) : 2;

        $poll_title_text_shadow_z_offset = (isset($options['poll_title_text_shadow_z_offset']) && $options['poll_title_text_shadow_z_offset'] != '') ? stripslashes( esc_attr( $options['poll_title_text_shadow_z_offset'] ) ) : 0;

        if( $enable_poll_title_text_shadow ){
            $title_text_shadow = 'text-shadow: '.$poll_title_text_shadow_x_offset.'px '.$poll_title_text_shadow_y_offset.'px '.$poll_title_text_shadow_z_offset.'px '.$poll_title_text_shadow;
        }else{
            $title_text_shadow = "";
        }

        /*
        ==========================================
            Ani
        ==========================================
            Answers styles
        ==========================================
            End
        ==========================================
        */
		$content = "<style>
		
        .".$this_poll_id.".box-apm {
            width: $poll_width;
            ". $poll_min_height ."
            margin: 0 auto !important;
            border-style: {$options['border_style']};
            border-color: {$main_color};
            border-radius: " . ((isset($options['border_radius']) && !empty($options['border_radius'])) ? (int) $options['border_radius'] . 'px' : '0') . ";
            border-width: " . ((isset($options['border_width']) && $options['border_width'] != '') ? (int) $options['border_width'] . 'px' : '2px') . ";" .
            $poll_box_shadow_css .
           	$poll_styles."
            background-position: ".$poll_bg_image_position.";
            background-repeat: no-repeat;
            background-size: cover;
            max-width: 100%;
            position: relative;
            padding-bottom: 60px !important;
        }

        #".$this_poll_id.".box-apm label.apm-label-with-bg{
        	background-size: ".$background_size.";
        }

        #".$this_poll_id.".box-apm span.ays_poll_passed_count{
            background-color: {$text_color};
            color: {$bg_color};
        }

        #".$this_poll_id.".box-apm span.ays_poll_passed_count i{
            color: {$bg_color};
        }
        
        #".$this_poll_id.".box-apm .apm-title-box{
            background-color: $title_bg_color;
        }

		#".$this_poll_id." .ays-poll-btn,
        #".$this_poll_id." .answer-percent,
        #".$this_poll_id." .answer-percent-res {
            background-color: {$main_color};
            color: {$bg_color};
        }

        #".$this_poll_id." .ays-poll-view-more-button{
            border: 1.5px dashed #CCC;
        }
        
        .".$this_poll_id." .ays-poll-btn, .".$this_poll_id." .apm-new-answer-apply{
			font-size: " . $buttons_font_size . ";
			padding: " . $buttons_top_bottom_padding . " " . $buttons_left_right_padding . ";
			border-radius: " . $buttons_border_radius . ";
		}

        .".$this_poll_id.".box-apm * {
            color: {$text_color};
        }
        
        #".$this_poll_id.".box-apm .apm-title-box h5 {
            color: {$text_color};
            text-transform: inherit;
            font-family: inherit;
            font-size: ".$poll_title_font_size."px;
			word-break: break-word;
			word-wrap: break-word;
            text-align: ".$poll_title_alignment.";
            padding:0 10px;
            {$title_text_shadow}
        }
        
        #".$this_poll_id.".box-apm i {
            color: {$icon_color};
            font-size: {$options['icon_size']}px;
            font-style: normal;            
        }

        #".$this_poll_id.".box-apm i.ays_poll_far{            
            font-family: 'Font Awesome 5 Free';		
        }

        #".$this_poll_id." input[type='radio'],
        #".$this_poll_id." .box-apm:not(.ays-minimal-theme) input[type='checkbox'] {
            display: none;
        }

        #".$this_poll_id." div.apm-load-message-container{            
            background-color: ".$bg_color." !important;	
        }

        #".$this_poll_id." .ays_question > p {
            font-size:".$poll_question_font_size_pc."px;
        }
        #".$this_poll_id." > .apm-answers > div{
            position:relative;
            /*border-radius:".$answers_border_radius."px;*/
        }

        #".$this_poll_id." span.ayspoll-answers-votes-count-before-voting{
            padding: 10px !important;
        }

        #".$this_poll_id." > .apm-answers > div > label {
            display:flex;
            padding:".$answers_padding."px;
            ".$answers_box_shadow_color.";
            flex-direction:".$ans_img_caption_style.";
            ".$poll_align_items.";
            border-radius:".$answers_border_radius."px;
            ".$poll_justify_content."
        }
        #".$this_poll_id." > .apm-answers > div > label> img {
            width: ".$ans_img_height.";
            max-width:100%;
            height:".$ans_img_height.";
            object-fit:".$answers_object_fit.";
        }
        #".$this_poll_id." > .apm-answers > div > label:hover > img {
            position: relative;
            z-index: 2;
        }
        #".$this_poll_id.".box-apm .apm-answers i{
            font-size:".$not_choosing_font_size."px;
        }
        
        #".$this_poll_id." > .apm-answers > div > label > span {
            font-size:".$answers_font_size."px;
            ".$poll_answers_margin.";
            ".$ans_img_caption_position.";
            ".$ays_poll_show_answers.";
            border-radius:".$answers_border_radius."px;
        }

        #".$this_poll_id." > .apm-answers > div {
            margin-bottom: ".$answers_margin."px;
        }
        
        #".$this_poll_id." .apm-button-box{
            $vote_button_margin;
        }
        
        .ays-poll-main #".$this_poll_id." .ays-poll-img {
            object-fit: cover;
			height: ".$poll_question_image_height."; 
        }
        
        #".$this_poll_id.".box-apm .ays-poll-maker-text-answer-main input,
		#".$this_poll_id.".box-apm .ays-poll-maker-text-answer-main textarea{
			min-width: 150px;
			max-width: 100%;
			width: ".$poll_text_type_ready_width.$poll_text_type_ready_type.";
        }
        
        #".$this_poll_id ." .apm-add-answer input.ays-poll-new-answer-apply-text{
            width: 100%;
			margin-bottom: 0;
			margin-right: 5px;
			border-color: ".$main_color."; 
			padding: 7px;
			font-size: 14px;
			color: black;
			height: 40px; 
			outline: none;
			display: inline-block;
        }";
        
        if($poll['view_type'] == 'grid'){
            $content .="#".$this_poll_id." > .apm-answers > div {
                margin-right: ".$answers_margin."px;
            }";
            switch($answers_grid_column){
                case '2':
                    $content .="
                    #".$this_poll_id." > .apm-answers.apm-grid{
                            display: flex;
                            flex-wrap: wrap;
                            width: 100%;
                            margin: 0 auto !important;
                            justify-content: center;
                            align-items: stretch;
                            align-content: center;
                        }
                    ";
                    break;
                case '3':
                    $content .="
                        #".$this_poll_id." > .apm-answers.apm-grid{
                            display: flex;
                            flex-wrap: wrap;
                            margin: 0 auto !important;
                            justify-content: center;
                            align-items: stretch;
                            align-content: center;
                        }
                        
                        #".$this_poll_id." > .apm-answers.apm-grid .apm-choosing {
                            width: 25%;
                            flex-basis: 30%; 
                            max-width: 40%;
                            margin: ".$answer_margin_grid_3."px;
                        }";
                        
                    break;
                case '4':
                    $content .="
                        #".$this_poll_id." > .apm-answers.apm-grid{
                            display: flex;
                            flex-wrap: wrap;
                            margin: 0 auto !important;
                            justify-content: center;
                            align-items: stretch;
                            align-content: center;
                        }
                        
                        #".$this_poll_id.">.apm-answers.apm-grid .apm-choosing {
                            width: 20%;
                            flex-basis: 20%; 
                            max-width: 40%;
                            margin: ".$answer_margin_grid_4."px;
                        }";
                    break;
            }
        }   
        $answer_border_all = '';
        switch ($answer_border_side) {
        	case 'none':
                $answer_border_type = "border: none";
                $answer_border_all  = "border: none";
        		break;
        	case 'all_sides':
                $answer_border_type = "border: 1px solid ".$main_color;
                $answer_border_all  = "border:";
        		break;
        	case 'top':
                $answer_border_type = "border-top: 1px solid ".$main_color;
                $answer_border_all  = "border-top:";
        		break;
        	case 'bottom':
                $answer_border_type = "border-bottom: 1px solid ".$main_color;
                $answer_border_all  = "border-bottom:";
        		break;
        	case 'left':
                $answer_border_type = "border-left: 1px solid ".$main_color;
                $answer_border_all  = "border-left:";
        		break;
        	case 'right':
                $answer_border_type = "border-right: 1px solid ".$main_color;
                $answer_border_all  = "border-right:";
        		break;
        }

        if($answer_border_all != '' && $poll['type'] != 'range' && $poll['type'] != 'rating'){
            $answer_border_all .= $answers_border_width."px ".$answers_border_style." ".$answers_border_color;
            $content .= "#".$this_poll_id." > .apm-answers label{
                ".$answer_border_all.";
            }";
        }

        if ( $answer_style ) {
    	 	$content .= "
	        #".$this_poll_id.".choosing-poll label:not(.ays_label_poll) {
	            background-color: $answer_bg_color;
    	 	}
	        #".$this_poll_id.".choosing-poll label {
	            text-transform: inherit;
	        }";
        }

        if ( $direct_icon_center && $show_answers_icon) {
    	 	$content .= "
	        #".$this_poll_id.".choosing-poll label.ays_label_poll:not(.apm-label-with-bg) span.ays_grid_answer_span{
	            display: inline-block;
			    width: calc(100% - 10px);
			    margin: 0 -15px;
    	 	}
	        #".$this_poll_id.".choosing-poll label.ays_label_poll span.ays_grid_answer_span{
	            display: inline-block;
			    width: calc(100% - 10px);
    	 	}";
        }

        if ( $direct_icon_right ) {
    	 	$content .= "
	        #".$this_poll_id.".choosing-poll label.ays_label_poll{
	            text-align:right;
    	 	}";
        }

        if ( !$show_answers_caption && $poll['view_type'] == 'grid' ) {
    	 	$content .= "
	        #".$this_poll_id." .apm-grid span.ays_grid_answer_span{
	            display: none;
    	 	}

    	 	.".$this_poll_id.".choosing-poll input[type='radio']:checked + label,
			.".$this_poll_id.".choosing-poll input[type='checkbox']:checked + label {
			   	border: 3px solid ". $main_color ." !important;
			    filter: drop-shadow(2px 4px 6px black);
			}

			.".$this_poll_id.".choosing-poll label.ays_enable_hover:hover {
		        filter: drop-shadow(1px 2px 3px black);
			}";    	 	
        }

        if ($poll['view_type'] == 'grid' && $poll_theme != 'ays-minimal-theme') {
        	 $content .= "
        	 	.$this_poll_id.choosing-poll label.ays_enable_hover:hover span.ays_grid_answer_span{
		            color: $bg_color;
		        }
        	 ";
        }

        if ($poll['view_type'] == 'grid') {
             $content .= "
                #$this_poll_id.choosing-poll span.ays_grid_answer_span{
                    background-color: unset;
                    word-break: break-all;
                    word-wrap: break-word;
                }
             ";
        }

        $content .= "
        .$this_poll_id .apm-grid .apm-choosing label.apm-label-with-bg span{
            background-color: " . $this->hex2rgba($answer_bg_color, 0.5) . ";
            text-transform: inherit;
            left: 0;
        }
        
        .$this_poll_id.ays-shape-theme, .$this_poll_id.ays-shape-theme {
		    border-radius: " . ((isset($options['border_radius']) && !empty($options['border_radius'])) ? (int) $options['border_radius'] . 'px' : 0) . " !important;
		}
        
        #$this_poll_id.box-apm .apm-grid .apm-choosing label.apm-label-with-bg:hover span,
        #$this_poll_id.box-apm .apm-grid .apm-choosing input[type='radio']:checked + label.apm-label-with-bg span,
		#$this_poll_id.box-apm .apm-grid .apm-choosing input[type='checkbox']:checked + label.apm-label-with-bg span,
        #$this_poll_id.choosing-poll input[type='radio']:checked + label,
		#$this_poll_id.choosing-poll input[type='checkbox']:checked + label
        #$this_poll_id.choosing-poll label.ays_enable_hover:hover {
            background-color: {$text_color};
            color: $bg_color;
        }

        #$this_poll_id.box-apm .apm-grid .apm-choosing input[type='radio']:checked + label.apm-label-with-bg > img,
        #$this_poll_id.box-apm .apm-grid .apm-choosing input[type='checkbox']:checked + label.apm-label-with-bg > img {
            position: relative;
            z-index: 2;
        }

        .".$this_poll_id.".choosing-poll label {
		    background-color: ".$answer_bg_color.";
		}

        .".$this_poll_id."_addAnswer input{           	
            height: 36px;
		    outline: none;
		    background: transparent;
		    border: 1px solid $main_color;
		    margin-right: 5px;
		    color: $text_color !important;
        }

        .".$this_poll_id." div.ays-image-logo-show{
            position: absolute;
            bottom: -5px;
            left: 1px;
            margin: 2px 0 0 0;
            padding: 2px;
            width: 100%;
            height: 65px;
            text-align: left;
        }
        .".$this_poll_id." .ays-poll-image-logo{
            width: 55px;
            height: 55px;
            object-fit: cover;
        }

        .".$this_poll_id."_addAnswer input::placeholder{
        	font-style: oblique;
        	color: #9e9e9e;
        }

        .".$this_poll_id."_addAnswer input[type='button']{           	
            padding: 0 1.44em;
		    margin-right: 0;
		    background: $main_color;
		    color: $bg_color !important;
        }

        .".$this_poll_id."_addAnswer input[type='button']:hover {            
		    box-shadow: unset;
		    -webkit-filter: opacity(0.7);
		    filter: opacity(0.7);
        }

        .$this_poll_id.choosing-poll label:hover input.apm-new-answer::placeholder {           	
            color: $answer_bg_color;
        }

        .$this_poll_id.choosing-poll input.apm-new-answer::placeholder {            
            color: {$text_color};
        }

        .$this_poll_id .apm-grid .apm-choosing input[type='radio']:checked + label.apm-label-with-bg *,
		.$this_poll_id .apm-grid .apm-choosing input[type='checkbox']:checked + label.apm-label-with-bg *,
		.$this_poll_id.choosing-poll input[type='radio']:checked + label *,
		.$this_poll_id.choosing-poll input[type='checkbox']:checked + label *,
		.$this_poll_id.choosing-poll label.ays_enable_hover:hover * {
            color: $bg_color;
        }
        
        .user-form-$this_poll_id input,
        .user-form-$this_poll_id textarea {
            background-color: $answer_bg_color;
            color: {$text_color};
            border: 1px solid {$main_color};
            font-size: 16px;
            font-weight: normal;
            padding: 5px;
        }
        
        .$this_poll_id.choosing-poll input[type='radio']:checked + label,
		.$this_poll_id.choosing-poll input[type='checkbox']:checked + label,
		.$this_poll_id.choosing-poll label.ays_enable_hover:hover {
            background-color: {$text_color};
            color: {$bg_color};
        }
        
        .$this_poll_id div.apm-loading-gif .apm-loader svg path,
        .$this_poll_id div.apm-loading-gif .apm-loader svg rect {
            fill: {$main_color};
        }
        
		.$this_poll_id .apm-versus-answer label.apm-simple-label,
		.$this_poll_id .apm-versus-answer label.apm-label-with-bg span {
		    background-color: {$bg_color};
		    border: 1px solid {$text_color};
		}
		
		.$this_poll_id .apm-versus-answer input[type='radio']:checked + label.apm-simple-label span,
		.$this_poll_id .apm-versus-answer label.apm-simple-label:hover span,
		.$this_poll_id .apm-versus-answer input[type='radio']:checked + label.apm-simple-label,
		.$this_poll_id .apm-versus-answer label.apm-simple-label:hover,
		.$this_poll_id .apm-versus-answer input[type='radio']:checked + label.apm-label-with-bg span,
		.$this_poll_id .apm-versus-answer label.apm-label-with-bg:hover span {
		    background-color: {$text_color};
		    color: {$bg_color} ;
		}
		
		.$this_poll_id .apm-versus.vs-times::after,
        .$this_poll_id .apm-versus.vs-default::after {
            background-color: {$bg_color};
		    color: {$text_color};
		    border-color: {$text_color};
        }

        @media only screen and (max-width: 768px){
            #".$this_poll_id." .ays_question p{
                font-size: ".$poll_question_font_size_mobile."px;
            }

            #".$this_poll_id." > .apm-answers > div > label > span {
                font-size: ".$poll_answer_font_size_mobile."px;
            }

            #".$this_poll_id."{
				max-width: ".$poll_mobile_max_width.";
			}

            #".$this_poll_id." > .apm-answers > div > label > img{
				height: ".$poll_answer_image_height_for_mobile."px;
			}

            .".$this_poll_id." .ays-poll-btn, .".$this_poll_id." .apm-new-answer-apply{
                font-size: " . $poll_buttons_mobile_font_size . ";
				line-height: 1;
				white-space: normal;
				word-break: break-word;
            }

            
        }";

        if($poll_theme == 'ays-coffee-theme'){
		
	    	$content .= "#$this_poll_id.ays-coffee-theme .ays-poll-btn {
	            background-color: {$text_color};
			}
			
			#$this_poll_id.ays-coffee-theme.choosing-poll .results-apm .answer-title,
			#$this_poll_id.ays-coffee-theme.choosing-poll .apm-answers div.apm-choosing {
                border: none;
	            border-bottom: 1px solid " . ($this->hex2rgba($text_color, 0.2)) . ";
	            background-color: " . ($this->hex2rgba($answer_bg_color, 0.1)) . ";
			}
			
			#$this_poll_id.ays-coffee-theme .apm-answers > div.apm-choosing input[type='radio']:checked + label,
			#$this_poll_id.ays-coffee-theme .apm-answers > div.apm-choosing input[type='checkbox']:checked + label,
			#$this_poll_id.ays-coffee-theme .apm-answers > div.apm-choosing input[type='radio']:checked + label *,
			#$this_poll_id.ays-coffee-theme .apm-answers > div.apm-choosing input[type='checkbox']:checked + label *,
			#$this_poll_id.ays-coffee-theme .apm-answers > div.apm-choosing label:hover *,
			#$this_poll_id.ays-coffee-theme .apm-answers > div.apm-choosing label:hover {
			    color: {$bg_color};
			}
			
			#$this_poll_id.ays-coffee-theme .apm-versus-answer input[type='checkbox']:checked + label.apm-label-with-bg,
			#$this_poll_id.ays-coffee-theme .apm-versus-answer input[type='radio']:checked + label.apm-label-with-bg,
			#$this_poll_id.ays-coffee-theme .apm-versus-answer label.apm-label-with-bg:hover {
			    background-color: {$text_color};
			}
			
			#$this_poll_id.ays-coffee-theme .apm-versus-answer label.apm-simple-label {
			    border: 1px solid {$text_color};
			}
			
			#$this_poll_id.ays-coffee-theme .apm-versus-answer input[type='checkbox']:checked + label.apm-simple-label,
			#$this_poll_id.ays-coffee-theme .apm-versus-answer input[type='radio']:checked + label.apm-simple-label,
			#$this_poll_id.ays-coffee-theme .apm-versus-answer label.apm-simple-label:hover {
			    background-color: {$text_color};
			}
			
			#$this_poll_id.ays-coffee-theme .apm-versus-answer input[type='checkbox']:checked + label.apm-simple-label span,
			#$this_poll_id.ays-coffee-theme .apm-versus-answer input[type='radio']:checked + label.apm-simple-label span,
			#$this_poll_id.ays-coffee-theme .apm-versus-answer label.apm-simple-label:hover span,
			#$this_poll_id.ays-coffee-theme input[type='checkbox']:checked + label.apm-label-with-bg span,
			#$this_poll_id.ays-coffee-theme input[type='radio']:checked + label.apm-label-with-bg span,
			#$this_poll_id.ays-coffee-theme label.apm-label-with-bg:hover span {
				color: {$bg_color};
			}
			
			#$this_poll_id.ays-coffee-theme.choosing-poll .results-apm .answer-title.current .apm-percent-bar::after,
			#$this_poll_id.ays-coffee-theme .apm-choosing input[type='checkbox']:checked + label:not(.apm-label-with-bg),
			#$this_poll_id.ays-coffee-theme .apm-choosing input[type='radio']:checked + label:not(.apm-label-with-bg)::after,
			#$this_poll_id.ays-coffee-theme .apm-choosing label:hover::after {
			    border-left: 5px solid {$text_color};
			    background-color: " . ($this->hex2rgba($text_color, 0.2)) . ";
			}
			
			#$this_poll_id.ays-coffee-theme.choosing-poll .results-apm .answer-title .apm-percent-bar::before {
			    background-color: " . ($this->hex2rgba($text_color, 0.5)) . ";
			}
			
			#$this_poll_id.ays-coffee-theme:not(.choosing-poll) .results-apm .answer-percent,
			#$this_poll_id.ays-coffee-theme:not(.choosing-poll) .results-apm .answer-percent-res {
			    background-color: " . ($this->hex2rgba($text_color, 0.75)) . ";
			}";
		}
		
		if($poll_theme == 'ays-aqua-theme'|| $poll_theme == 'ays-coffee-theme'){
			if ($direct_icon_center) {
				$content .= ".$this_poll_id label.ays_label_poll {
				    text-align:center !important;
				}
				";
				
			}
		}

		if($poll_theme == 'ays-aqua-theme'){
			$content .= ".$this_poll_id.ays-aqua-theme .ays_question {
			    background-color: {$main_color};
			}
			
			.$this_poll_id.ays-aqua-theme .apm-title-box {
			    background-color: {$main_color} !important;
			}
			
			.$this_poll_id.ays-aqua-theme.choosing-poll label.apm-label-with-bg span {
				background-color: $text_color !important;
				color: {$main_color};
			}
			
			.$this_poll_id.ays-aqua-theme.choosing-poll label.apm-label-with-bg:hover span {
				background-color: {$main_color} !important;
				color: $text_color;
			}			
			
			.$this_poll_id.ays-aqua-theme.choosing-poll input[type='checkbox']:checked + label.apm-label-with-bg span,
			.$this_poll_id.ays-aqua-theme.choosing-poll input[type='radio']:checked + label.apm-label-with-bg span {
				color: {$icon_color};
			    background-color: {$main_color};
			}			
			
			.$this_poll_id.ays-aqua-theme .apm-choosing input[type='checkbox']:checked + label,
			.$this_poll_id.ays-aqua-theme .apm-choosing input[type='radio']:checked + label,
			.$this_poll_id.ays-aqua-theme .apm-choosing input[type='checkbox']:checked + label span,
			.$this_poll_id.ays-aqua-theme .apm-choosing input[type='radio']:checked + label span,
			.$this_poll_id.ays-aqua-theme.choosing-poll label:hover span {
				color: {$icon_color};
			}
			
			.$this_poll_id.ays-aqua-theme .apm-versus-answer label.apm-simple-label {
			    border: 1px solid {$text_color};
			}
			
			.$this_poll_id.ays-aqua-theme .apm-versus-answer input[type='checkbox']:checked + label.apm-label-with-bg span,
			.$this_poll_id.ays-aqua-theme .apm-versus-answer input[type='radio']:checked + label.apm-label-with-bg span,
			.$this_poll_id.ays-aqua-theme .apm-versus-answer input[type='checkbox']:checked + label.apm-simple-label,
			.$this_poll_id.ays-aqua-theme .apm-versus-answer input[type='radio']:checked + label.apm-simple-label,
			.$this_poll_id.ays-aqua-theme .apm-versus-answer label.apm-simple-label:hover,
			.$this_poll_id.ays-aqua-theme .apm-versus-answer label.apm-label-with-bg:hover span {
			    background-color: {$icon_color} !important;
			    color: {$text_color} !important;
			}
			
			.$this_poll_id.ays-aqua-theme.choosing-poll label:not(.apm-label-with-bg)::before {
			    border: 1px solid {$text_color};
			}
			
			.$this_poll_id.ays-aqua-theme.choosing-poll label:not(.apm-label-with-bg)::after {
			    background: {$icon_color} !important;
			}
			
			.$this_poll_id.ays-aqua-theme .apm-choosing input[type='checkbox']:checked + label:not(.apm-label-with-bg)::before,
			.$this_poll_id.ays-aqua-theme .apm-choosing input[type='radio']:checked + label:not(.apm-label-with-bg)::before,
			.$this_poll_id.ays-aqua-theme.choosing-poll label:not(.apm-label-with-bg):hover::before {
				border-color: {$icon_color}
			}
			
			.$this_poll_id.ays-aqua-theme .apm-button-box {
			    background-color: {$text_color};
			}
			
			.$this_poll_id.ays-aqua-theme .user-form .ays-poll-btn,
			.$this_poll_id.ays-aqua-theme .apm-button-box input {
				color: {$text_color} !important;
			}
			
			.$this_poll_id.ays-aqua-theme .user-form .ays-poll-btn,
			.$this_poll_id.ays-aqua-theme input[data-seeres='true'].ays-poll-btn {
				background-color: {$icon_color} !important;
			}
			
			.$this_poll_id.ays-aqua-theme .answer-percent,
			.$this_poll_id.ays-aqua-theme .answer-percent-res {
	            background-color: {$icon_color}
	        }
	        
	        .$this_poll_id.ays-aqua-theme .voteReason .forReason {
	            color: {$icon_color}
	        }
	        
	        .$this_poll_id.ays-aqua-theme label:hover input.apm-new-answer {
	            color: {$text_color};
	        }
	        
	        .$this_poll_id.ays-aqua-theme .apm-grid label:hover input.apm-new-answer {
	            color: {$icon_color};
	        }
	        
	        .$this_poll_id.ays-aqua-theme label.apm-add-answer .apm-new-answer-apply:hover {
	            background-color: {$icon_color} !important;
	        }";
        }
        
        $content .= ".$this_poll_id label.apm-add-answer:hover .apm-new-answer-apply {
            color: {$bg_color} !important;
        }
        
        .$this_poll_id label.apm-add-answer .apm-new-answer-apply:hover {
            background-color: {$bg_color} !important;           
            color: {$text_color} !important;
        }

        .$this_poll_id .apm-info-form input {
            color: $text_color !important;
            background-color: $answer_bg_color !important;
        } 
        
        " . (isset($load_gif) && $load_gif == 'plg_4' ? "
		.$this_poll_id div.apm-loading-gif .apm-loader svg {
            stroke: {$main_color} !important;
        }

        .$this_poll_id.choosing-poll .ays_poll_cb_and_a,
        .$this_poll_id.choosing-poll .ays_poll_cb_and_a * {
            color: " . $this->hex2rgba($text_color) . ";
        }

        .$this_poll_id div.apm-loading-gif .apm-loader svg>g {
            fill: {$bg_color};
        }
        " : "") . "
		";
		if ($show_answers_icon && $poll_theme != 'ays-aqua-theme') {
			$content .= 
		   "#".$this_poll_id." label.ays_poll_answer_icon_radio:before,
			#".$this_poll_id." label.ays_poll_answer_icon_checkbox:before{
			    content: '';
			    display: inline-block;
			    background: #ddd;
			    background-clip: content-box;
			    width: 20px;
			    height: 20px;
			    border: 3px solid #ccc;
			    padding: 3px 3px 3px 3px;
			    box-sizing: border-box;
			    transition: all .4s linear;
			    vertical-align: middle;
			    margin-right: 10px;
			    margin-bottom: 2px;
			}

			#".$this_poll_id." label.ays_poll_answer_icon[for='poll_answer_icon_radio']:before,
			#".$this_poll_id." label.ays_poll_answer_icon_radio:before{
			    border-radius: 50%;
			}

			#".$this_poll_id." input[name='answer']:checked + label.ays_poll_answer_icon_radio:before,
			#".$this_poll_id." input[name='answer']:checked + label.ays_poll_answer_icon_checkbox:before{
			    background: green;
			    border: 3px solid green;
			    padding: 3px 3px 3px 3px;
			    background-clip: content-box;
			}";
		}
		
		if($poll_theme == 'ays-minimal-theme'){
			$content .= "
				.$this_poll_id.ays-minimal-theme .apm-choosing{
				    display: flex;
				    align-items: center;
				}

				.$this_poll_id.ays-minimal-theme .apm-choosing input[type=checkbox]:checked + label,
				.$this_poll_id.ays-minimal-theme .apm-choosing input[type=radio]:checked + label,
				.$this_poll_id.ays-minimal-theme .apm-choosing label.ays_enable_hover:hover{
				    background-color: initial !important;
				    color: $main_color !important;
				    border-color: $main_color !important;
				    font-weight: initial !important;
				    margin:3px 0 !important;
				}

				.$this_poll_id.ays-minimal-theme .apm-choosing label{
					border-color: $text_color !important;
				    font-weight: initial !important;
				    margin:3px 0 !important;
				}

				.$this_poll_id.ays-minimal-theme .apm-choosing input[type='checkbox'],
				.$this_poll_id.ays-minimal-theme .apm-choosing input[type='radio']{
				    display: block !important;
			        outline: none;
				}

				.$this_poll_id.ays-minimal-theme input[type='button'].ays-poll-btn:hover, .$this_poll_id.ays-minimal-theme input[type='button'].ays-poll-btn:focus{
					text-decoration: none;
				}

				.$this_poll_id.ays-minimal-theme input[type='button'].ays-poll-btn{
				    color: initial !important;
				    background: initial !important;
				    border: 1px solid $text_color;
				}

				.$this_poll_id.ays-minimal-theme .ays_poll_passed_count{
				    color: $text_color !important;
				    background: initial !important;
				    border: 1px solid $text_color;
				    border-radius: 3px;
				}

				.$this_poll_id.ays-minimal-theme .ays_poll_passed_count i.ays_poll_fa:before{
				    color: $text_color !important;		    
				}

		        .$this_poll_id.ays-minimal-theme .answer-percent{
		        	color: initial !important;
				}

				#".$this_poll_id.".box-apm span.ays_poll_passed_count i{
					color: {$text_color};
				}
				
				.user-form-$this_poll_id input,
				.user-form-$this_poll_id textarea {
					background-color: $bg_color;
					color: {$text_color};
					border: 1px solid {$main_color};
				}
				
				.$this_poll_id .apm-grid .apm-choosing label.apm-label-with-bg:hover span, 
				.$this_poll_id .apm-grid .apm-choosing input[type='radio']:checked + label.apm-label-with-bg span, 
				.$this_poll_id .apm-grid .apm-choosing input[type='checkbox']:checked + label.apm-label-with-bg span, 
				.$this_poll_id.choosing-poll input[type='radio']:checked + label, 
				.$this_poll_id.choosing-poll input[type='checkbox']:checked + label, 
				.$this_poll_id.choosing-poll label.ays_enable_hover:hover {
					background-color: {$bg_color};
					color: $text_color;
				}

				.$this_poll_id .apm-grid .apm-choosing input[type='radio']:checked + label.apm-label-with-bg *,
				.$this_poll_id .apm-grid .apm-choosing input[type='checkbox']:checked + label.apm-label-with-bg *,
				.$this_poll_id.choosing-poll input[type='radio']:checked + label *,
				.$this_poll_id.choosing-poll input[type='checkbox']:checked + label *,
				.$this_poll_id.choosing-poll label.ays_enable_hover:hover * {
		            color: $main_color;
		        }

		        .".$this_poll_id."_addAnswer input[type='button']{           	
		                padding: 0 1.44em;
					    margin-right: 0;
					    background: $bg_color;
					    color: $text_color !important;
					    text-decoration:none;
		        }

				.$this_poll_id.ays-minimal-theme.choosing-poll label.apm-label-with-bg span {
					background-color: initial;
					color: {$main_color};
				}
				.$this_poll_id.ays-minimal-theme.choosing-poll label.apm-label-with-bg:hover span {
					background-color: initial !important;
					color: $answer_bg_color;
				}
				.$this_poll_id.ays-minimal-theme.choosing-poll input[type='checkbox']:checked + label.apm-label-with-bg span, 
				.$this_poll_id.ays-minimal-theme.choosing-poll input[type='radio']:checked + label.apm-label-with-bg span {
					color: {$icon_color};
				    background-color: initial;
				}
			";
		}
		
        if($poll_loader_font_size != ''){
            $content .= ".$this_poll_id div.apm-loading-gif .apm-loader{
				display: flex;
				justify-content: center;
				align-items: center;
				padding-top: 10px;
			}
			.$this_poll_id div.apm-loading-gif{
				width: 100%;
    			height: 100%;
			}";            
        }
        if(!$poll_disable_prev){
            $poll_next_prev_width = "100%";
        }
        else{
            $poll_next_prev_width = "50%";
        }
        if($show_result_view_for_dir && $poll_direction == "rtl"){
            $content .= "#".$this_poll_id." .results-apm *{
                direction: initial;
            }";

            $content .= "#".$this_poll_id." .apm-answers > div > label{
                flex-direction: row-reverse;
            }";
        }
        if($poll_direction == "rtl"){
            $content .= "#".$this_poll_id." .ays-image-logo-show{
                text-align: right;
            }";
        }
        $content .= $poll['custom_css'];
        $content .= "</style>
        <script>
            var dataCss = {
                width: '".$poll_next_prev_width."',
                fontSize: '16px',
                padding: '10px',
                borderWidth: '2px',
                borderStyle: '{$options['border_style']}',
                borderColor: '{$main_color}',
                background: '{$bg_color}',
                color: '{$main_color}',
                transition: '.3s ease',
                };
            var hoverCss = {
                background: '{$main_color}',
                color: '{$bg_color}',
                borderColor: '{$bg_color}',
            };
        </script>";
        if ($poll_direction == 'center') {
        	$poll_direction_center = "style='text-align: center;'";
        	$poll_direction = 'ltr';
        }else{
        	$poll_direction_center = "";        	
        }

        // AV Show login form for not logged in users
        $options['show_login_form'] = isset($options['show_login_form']) ? $options['show_login_form'] : 'off';
        $show_login_form = (isset($options['show_login_form']) && $options['show_login_form'] == "on") ? true : false;

		$add_form = $show_login_form && !is_user_logged_in() ? "" : "<form style='margin-bottom: 0;' method='post'>";

		if(isset($options['show_create_date']) && $options['show_create_date'] == 1){
            $show_create_date = true;
        }else{
            $show_create_date = false;
        }

        if(isset($options['show_author']) && $options['show_author'] == 1){
            $show_author = true;
        }else{
            $show_author = false;
        }

        // Limitation tackers of poll
        $enable_tackers_count = false;
        $tackers_count = 0;
        $tackers_message = "<div style='text-align:center;'><p>" . __( "The permitted amount of votes have been already completed.", $this->plugin_name ) . "</p></div>";
        $options['enable_tackers_count'] = !isset($options['enable_tackers_count']) ? 'off' : $options['enable_tackers_count'];
        if(isset($options['enable_tackers_count']) && $options['enable_tackers_count'] == 'on'){
            $enable_tackers_count = true;
        }
        if(isset($options['tackers_count']) && $options['tackers_count'] != ''){
            $tackers_count = intval($options['tackers_count']);
        }

        //Enabled ansers sound
        $enable_asnwers_sound =  isset($options['enable_asnwers_sound']) && $options['enable_asnwers_sound'] == 'on' ? true : false;
        $answers_sound = '';
        $answers_sound_class = '';
        // ==== ADDED NEW ====
        $answers_sound_mute  = '';
        // ==== ====
        if ($enable_asnwers_sound) {
        	$poll_settings = $this->settings;
        	$settings_options = ($poll_settings->ays_get_setting('options') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('options');
            $setting_options = json_decode($settings_options, true);
            $answers_sound_path = isset($setting_options['answers_sound']) && !empty($setting_options['answers_sound']) ? $setting_options['answers_sound'] : false;
           
            if ($answers_sound_path != false) {
            	$answers_sound = "<audio id='ays_poll_ans_sound_".$id."' class='ays_poll_ans_sound' src='".$answers_sound_path."'></audio>";
         		$answers_sound_class = 'poll_answers_sound';
                $answers_sound_mute = "<span class='ays_music_sound ays_sound_active'><i class='ays_poll_far ays_poll_fa-volume_up'></i></span>";

            }
        }

        //AV show timer
        $activeDateCheck =  isset($options['active_date_check']) && !empty($options['active_date_check']) ? true : false;
        $activeDeactiveDateCheck =  isset($options['deactiveInterval']) && !empty($options['deactiveInterval']) ? true : false;
        $activeActiveDateCheck =  isset($options['activeInterval']) && !empty($options['activeInterval']) ? true : false;
        $show_timer_type = isset($options['ays_show_timer_type']) && !empty($options['ays_show_timer_type']) ? $options['ays_show_timer_type'] : 'countdown';
        $show_timer = '';
		if ( $activeDateCheck && $activeDeactiveDateCheck && !$is_start_soon) {
		    if (isset($options['ays_poll_show_timer']) && $options['ays_poll_show_timer'] == 1) {
				$show_timer .= "<div class='ays_poll_show_timer'>";
				if ($show_timer_type == 'countdown') {
                    if ($endDate_atr > 0) {
                        $show_timer .= '<p class="show_timer_countdown" data-timer_countdown="'.$endDate_atr.'"></p>';
                    }
				}else if ($show_timer_type == 'enddate') {
					$show_timer .= '<p class="show_timer_countdown">'.__('This Poll active until ',$this->plugin_name).date_i18n('H:i:s F JS, Y', intval($endDate)).'</p>';
				}
				$show_timer .= "</div>";
		    }
		}elseif ($activeDateCheck && $activeActiveDateCheck && $is_start_soon) {
			if (isset($options['ays_poll_show_timer']) && $options['ays_poll_show_timer'] == 1) {
				$show_timer .= "<div class='ays_poll_show_timer'>";
				if ($show_timer_type == 'countdown') {
					$show_timer .= '<p class="show_timer_countdown" data-timer_countdown="'.$startDate_atr.'"></p>';
				}else if ($show_timer_type == 'enddate') {
					$show_timer .= '<p class="show_timer_countdown">'.__('This Poll will start ',$this->plugin_name).date_i18n('H:i:s F JS, Y', intval($startDate)).'</p>';
				}
				$show_timer .= "</div>";
		    }
		}

		$show_cd_and_author = "<div class='ays_poll_cb_and_a'>";
        if($show_create_date){
            $poll_create_date = (isset($options['create_date']) && $options['create_date'] != '') ? $options['create_date'] : "0000-00-00 00:00:00";
            if(Poll_Maker_Ays_Admin::validateDate($poll_create_date)){
                $show_cd_and_author .= "<span>".__("Created on",$this->plugin_name)." </span><strong><time>".date_i18n("F d, Y", strtotime($poll_create_date))."</time></strong>";
            }else{
                $show_cd_and_author .= "";
            }
        }
        
        if($show_author){
            if(isset($options['author'])){
                if(is_array($options['author'])){
                    $author = $options['author'];
                }else{
                    $author = json_decode($options['author'], true);
                }
            }else{
                $author = array("name"=>"Unknown");
            }
            $user_id = 0;
            if(isset($author['id']) && intval($author['id']) != 0){
                $user_id = intval($author['id']);
            }
            $image = get_avatar($user_id, 32);
            if($author['name'] !== "Unknown"){
                if($show_create_date){
                    $text = __("By", $this->plugin_name);
                }else{
                    $text = __("Created by", $this->plugin_name);
                }
                $show_cd_and_author .= "<span>   ".$text." </span>".$image."<strong>".$author['name']."</strong>";
            }else{
                $show_cd_and_author .= "";
            }
        }

        $show_cd_and_author .= "</div>";


        // Show votes count per answers before voting
        $options['show_votes_before_voting'] = isset($options['show_votes_before_voting']) ? $options['show_votes_before_voting'] : 'off';
        $show_votes_before_voting = (isset($options['show_votes_before_voting']) && $options['show_votes_before_voting'] == 'on') ? true : false;
        $show_votes_before_voting_by = (isset($options['show_votes_before_voting_by']) && $options['show_votes_before_voting_by'] != '') ? $options['show_votes_before_voting_by'] : 'by_count';
        $poll_show_result_view = (isset($options['show_result_view']) && $options['show_result_view'] != '') ? $options['show_result_view'] : 'standart';

        $poll_login_form = "";
        if($show_login_form){
            $args = array(
                'echo' 		  => false,
                'form_id'     => 'ays_loginform_'.$this_poll_id,
                'id_username' => 'ays_user_login_'.$this_poll_id,
                'id_password' => 'ays_user_pass_'.$this_poll_id,
                'id_remember' => 'ays_rememberme_'.$this_poll_id,
                'id_submit'   => 'ays-submit_'.$this_poll_id
            );
            $poll_login_form = "<div class='ays_poll_login_form'>" . wp_login_form( $args ) . "</div>";
    	}

    	// $ays_result_message = isset($options['result_message']) ? do_shortcode(wpautop(stripslashes($options['result_message']))) : '';


        $poll_user_information = Poll_Maker_Data::get_user_profile_data();
		$user_first_name = (isset( $poll_user_information['user_first_name'] ) && $poll_user_information['user_first_name']  != "") ? $poll_user_information['user_first_name'] : '';	
        $user_last_name  = (isset( $poll_user_information['user_last_name'] ) && $poll_user_information['user_last_name']  != "") ? $poll_user_information['user_last_name'] : '';
        $user_email_name  = (isset( $poll_user_information['user_email_name'] ) && $poll_user_information['user_email_name']  != "") ? $poll_user_information['user_email_name'] : '';
        $creation_date   = (isset( $poll['styles']['create_date'] ) && $poll['styles']['create_date'] != '') ? $poll['styles']['create_date'] : '';
		$message_data = array(
			'poll_title'       => stripslashes($poll['title']),
			'users_first_name' => $user_first_name,
            'users_last_name'  => $user_last_name,
            'creation_date'    => $creation_date,
            'user_email'       => $user_email_name,
		);

		$ays_result_message = ( isset( $options['result_message'] ) ) ? trim( $options['result_message'] )  : '';

		$ays_result_message = $this->replace_message_variables($ays_result_message, $message_data);

		$ays_result_message = $this->ays_autoembed( $ays_result_message );


    	$result_message = isset($options['hide_result_message']) && $options['hide_result_message'] == 1 ? "<div class='apm-title-box ays_res_mess'>" . $ays_result_message . "</div>" : "";

        $poll_title = (isset($poll['title']) && $poll['title'] != '')  ? stripslashes($poll['title']) : '';

    	$custom_class = isset($options['custom_class']) && $options['custom_class'] != '' ? $options['custom_class'] : "";    

  		// Animation Top (px)
		$poll_animation_top = (isset($general_options['poll_animation_top']) && $general_options['poll_animation_top'] != '') ? absint(intval($general_options['poll_animation_top'])) : 100 ;
		$options['poll_enable_animation_top'] = isset($general_options['poll_enable_animation_top']) ? $general_options['poll_enable_animation_top'] : 'on';
		$poll_enable_animation_top = (isset($general_options['poll_enable_animation_top']) && $general_options['poll_enable_animation_top'] == "on") ? true : false;

		$content .= "<div style='margin-bottom: 1rem; width:$poll_width' class='ays-poll-main ". $custom_class ."' id='ays-poll-container-" . $id . "' data-load-method='".$poll_see_result_immediately."'>
        ".$add_form."
        ".$answers_sound."
		<div
		$poll_direction_center
        dir='$poll_direction'
		data-loading = '$load_effect'
		data-load-gif = '$load_gif'
        data-hide-bg-image='$poll_bg_img_in_finish_page'
        data-load-gif-font-size='$poll_loader_font_size'
        ".$poll_load_message_data."
		data-show-social = '$show_social'
		data-restart =  '" . (isset($options['enable_restart_button']) && $options['enable_restart_button'] ? 'true' : 'false') . "'
		class='box-apm $poll_theme {$poll['type']}-poll $this_poll_id'
		id = '$this_poll_id'
		data-res = '$hide_results'
		data-res-sort ='$result_sort'
		data-redirection = '$redirect_users'
		data-redirect-check = '".$redirect_url_checked."'
        data-url-href = '".$redirect_url_href."'
		data-href = '$redirect_after_vote_url'
		data-delay = '$redirect_delay'
		data-id = '{$poll['id']}'
		data-res-rgba = '". $result_in_rgba ."'
		data-percent-color = '$answer_percent_color'
        data-enable-top-animation = '". $poll_enable_animation_top ."'
        data-top-animation-scroll = '". $poll_animation_top ."'
        data-result-view = '$poll_show_result_view'
        data-avg=".$avg_ans_range."
		>" . $poll_result_reports;
		if($enable_password && !$password_right){
			$content .= $password_message;			
		}else{
			$content .= $show_cd_and_author;
            $content .= $show_timer;   
            $content .= $poll_image_cont;
            $content .= $answers_sound_mute;
			$content .= 1 == $poll['show_title'] ? "<div class='apm-title-box'><h5>" . $poll_title . "</h5></div>" : "";
			$content .= "<div class='$this_poll_id ays_question'>" . do_shortcode(wpautop(stripslashes($poll['question']))) . "</div>";
			$content .= $poll['image'] ? "<div class='apm-img-box'><img class='ays-poll-img' src='{$poll['image']}'></div>" : "";
			$content .= "<div class='$this_poll_id hideResults' style='text-align:center;'>" . $hide_results_text . "</div>";
            if(($is_expired || $is_start_soon) && $poll_check_exp_cont){
                $content = "";
                return $content;
            }
    
			if (!$is_expired) {
				//CHECK IF ENABLED ONLY LOGGED IN USERS OPTION
				if (isset($options['enable_logged_users']) && $options['enable_logged_users'] == 1 && !is_user_logged_in()) {
					$logged_users_message = isset($options['enable_logged_users_message']) && $options['enable_logged_users_message'] != '' ? stripslashes($options['enable_logged_users_message']) : "<p style='text-align: center'>" . __('You must sign in for voting.', $this->plugin_name) . "</p>";

					$content .= "<div class='apm-need-sign-in'>".$logged_users_message."</div>";

					if($logged_users_message !== null){
			            if(!is_user_logged_in()){
							$content .= "<div class='apm-need-sign-in'>". $poll_login_form ."</div>";
			            }
			        }

				} else {
					$load_poll = true;
					$load_limit = true;
					if (isset($options['enable_restriction_pass']) && $options['enable_restriction_pass'] == 1 && is_user_logged_in()) {
						$user           = wp_get_current_user();
						$user_role      = $user->roles;
						$message        = (isset($options['restriction_pass_message']) && $options['restriction_pass_message'] != '') ? stripslashes($options['restriction_pass_message']) : ("<p style='text-align: center'>" . __('You not have permissions for voting.', $this->plugin_name) . "</p>");
						$for_user_roles = (isset($options['user_role']) && $options['user_role'] != '') ? explode(',', strtolower($options['user_role'])) : array();

						foreach ($for_user_roles as $key => $role) {
							if (in_array($role, $user_role)) {
								$load_limit = false;
								break;
							}							
						}

						if($load_limit){
							$content   .= "<div style='text-align: center'>$message</div>";
							$load_poll = false;
						}
					}
                    $message = (isset($options['limitation_message']) && $options['limitation_message'] != '' ? stripslashes($options['limitation_message']) : ("<p>" . __("You have already voted.", $this->plugin_name) . "</p>"));

                    $is_in_limit_period = false;
                    $enable_vote_limitation  = (isset($options['enable_vote_limitation']) && $options['enable_vote_limitation'] == 'on') ? true : false;
					if($enable_vote_limitation === false){
						if (isset($_COOKIE['ays_vote_limitation_cookie_name_'.$id])) {
							unset($_COOKIE['ays_vote_limitation_cookie_name_'.$id]);
							$cookie_expiration =  time() - 1;   
            				setcookie('ays_vote_limitation_cookie_name_'.$id, null, $cookie_expiration, '/');
                            
						}
					}
                    else{
                        if (isset($_COOKIE['ays_vote_limitation_cookie_name_'.$id])) {
                            $is_in_limit_period = true;
                        }
                    }

					if($enable_tackers_count){
			            $poll_tackers_count = $this->get_poll_tackers_count($id);
			            if($poll_tackers_count >= $tackers_count){
			                $content .= $tackers_message;
			                $load_poll 	= false;
			            }
			        }

                    if($enable_limit_user_by_country){
                        $user_ip = $this->get_user_ip();
                        $json    = json_decode(file_get_contents("http://ipinfo.io/{$user_ip}/json"));
                        $country = isset($json->country) && $json->country != '' ? $json->country : "";
            
                        if($blocked_user_country === $country){
                            $content .= '<p style="text-align:center">This poll is not available in your country</p>';
                            $see_result_button = '';
                            $load_poll = false;
                        }
                    }

					if ($load_poll) {
						$limit_users = 0;
                        $user_id = 0;
                        if(is_user_logged_in()){
                            $user_id = get_current_user_id();
                        }

                        $limit_users_attr = array(
                            'id' => $id,
                            'name' => 'ays_this_poll_cookie_',
                            'title' => $poll_title,
                        );

                        $limit_users_period = array(
                            'id' => $id,
                            'name' => 'ays_vote_limitation_cookie_name',
                        );

                        $check_cookie = false;
                        $ays_vote_limitation = false;
                        $vote_limitation_time_method = false;
						if ($limit_users_option) {
							global $wpdb;
                            $ays_vote_limitation = (isset($options['vote_limitation']) && $options['vote_limitation'] != '') ? $options['vote_limitation'] : '';
                            $ays_vote_limitation_time_period = (isset($options['limitation_time_period']) && $options['limitation_time_period'] != '') ? $options['limitation_time_period'] : '';
                            $cookie_name = 'ays_vote_limitation_cookie_name_'.$id;
                            
                            if($enable_vote_limitation){
                                $cookie_value = 'ays_vote_limitation_cookie_value';
                                $cookie_expiration = time() + (60 * $ays_vote_limitation);
                                switch($ays_vote_limitation_time_period) {
                                    case "minute":
                                        $vote_limitation_time_method = "MINUTE";
                                        $cookie_expiration = time() + (60 * $ays_vote_limitation);
                                        break;
                                    case "hour":
                                        $vote_limitation_time_method = "HOUR";
                                        $cookie_expiration = time() + (3600 * $ays_vote_limitation);
                                        break;
                                    case "day":
                                        $vote_limitation_time_method = "DAY";
                                        $cookie_expiration = time() + (864 * 10^2 * $ays_vote_limitation);
                                        break;
                                    case "week":
                                        $vote_limitation_time_method = "WEEK";
                                        $cookie_expiration = time() + (6048 * 10^2 * $ays_vote_limitation);
                                        break;
                                    case "month":
                                        $vote_limitation_time_method = "MONTH";
                                        $cookie_expiration = time() + (2592 * 10^3 * $ays_vote_limitation);
                                        break;
                                    default:
                                        $vote_limitation_time_method = "MINUTE";
                                }
                            }

                            $limit_users_method = ( isset($options['limit_users_method']) && $options['limit_users_method'] != '' ) ? $options['limit_users_method'] : 'ip';

                            switch ($limit_users_method) {
                                case 'ip':
                                    $limit_users = $this->ays_poll_get_limit_user_count_by_ip($id, $ays_vote_limitation, $vote_limitation_time_method);
                                    if($enable_vote_limitation){
                                        $limit_users = (intval($limit_users) >= $attempts_count) ? $limit_users : 0;
                                    }
                                    $this->ays_poll_remove_cookie( $limit_users_attr );
                                    $this->ays_poll_remove_cookie( $limit_users_period );
                                    break;
                                case 'user':
                                    if(is_user_logged_in()){
                                        if( $user_id != 0 ){
                                            $limit_users = $this->ays_poll_get_limit_user_count_by_id($id, $user_id, $ays_vote_limitation, $vote_limitation_time_method);
                                            if($enable_vote_limitation){
                                                $limit_users = (intval($limit_users) >= $attempts_count) ? $limit_users : 0;
                                            }
                                        }
                                    }else{
                                        $limit_users = 0;
                                    }
                                    $this->ays_poll_remove_cookie( $limit_users_attr );
                                    $this->ays_poll_remove_cookie( $limit_users_period );
                                    break;
                                case 'cookie':
                                    $check_cookie = $this->ays_poll_check_cookie( $limit_users_attr );
                                    if ( !$check_cookie ) {
                                        $limit_users = 0;
                                    }else{
                                        $limit_users = $this->get_limit_cookie_count( $limit_users_attr );
                                    }

                                    if($enable_vote_limitation){
                                        if(!$is_in_limit_period){
                                            $limit_users = 0;
                                            if ( $check_cookie ) {
                                                $this->ays_poll_remove_cookie( $limit_users_attr );
                                            }
                                        }
                                    }
                                    else{
                                        if ( $limit_users == 0 ) {
                                            $this->ays_poll_remove_cookie( $limit_users_attr );
                                        }
                                    }
                                    break;
                                case 'cookie_ip':
                                    $check_cookie = $this->ays_poll_check_cookie( $limit_users_attr );
                                    $check_user_by_ip = $this->ays_poll_get_limit_user_count_by_ip($id, $ays_vote_limitation, $vote_limitation_time_method);
                                    if($check_cookie || $check_user_by_ip > 0){
                                        $limit_users = $check_user_by_ip;
                                    }
                                    elseif(!$check_cookie || $check_user_by_ip <= 0){
                                        $limit_users = 0;
                                    }

                                    if($enable_vote_limitation){
                                        if($check_cookie || intval($check_user_by_ip) >= $attempts_count){
                                            $limit_users = $check_user_by_ip;
                                        }
                                        else{
                                            $limit_users = 0;
                                        }
                                    }

                                    if(!$is_in_limit_period){
                                        if ( $check_cookie ) {
                                            $this->ays_poll_remove_cookie( $limit_users_attr );
                                        }
                                    }
                                    break;
                                default:
                                    if ($user_id != 0) {
                                        $limit_users = $this->ays_poll_get_limit_user_count_by_id($poll_id,$user_id, $ays_vote_limitation, $vote_limitation_time_method);
                                    }else{
                                        $limit_users = $this->ays_poll_get_limit_user_count_by_ip($poll_id, $ays_vote_limitation, $vote_limitation_time_method);
                                    }
                                    $this->ays_poll_remove_cookie( $limit_users_attr );
                                    break;
                            }
						}else{
                            $this->ays_poll_remove_cookie($limit_users_attr);
                        }
						$allow_multivote = isset($options['allow_multivote']) && $options['allow_multivote'] == 'on' ? true : false;
						$multivote_checkbox = $allow_multivote ? 'checkbox' : 'radio';						

						$multivote_answer_count = '';
						$allow_multivote_answer = '';
						$poll_multivote_min_count = '';
						$poll_multivote_min_count_content = '';
						$poll_multivote_message_content = '';
						if($allow_multivote){
							$multivote_answer_count = (isset($options['multivote_answer_count']) && $options['multivote_answer_count'] != '') ? absint(intval($options['multivote_answer_count'])) : '1';
							$multiple_select = 'multiple';
							$allow_multivote_answer = 'on';
							$poll_multivote_min_count = (isset($options['multivote_answer_min_count']) && $options['multivote_answer_min_count'] != '') ? absint(intval($options['multivote_answer_min_count'])) : '1';
                            $poll_multivote_min_count_content = "<input type='hidden' id='ays_poll_multivote_min_count' data-allow='true' value='".$poll_multivote_min_count."'/>";
                            $poll_multivote_message_content = "<div class='ays-poll-multivote-message add_answer_for_grid'>".__("Min votes count should be ".$poll_multivote_min_count."" , $this->plugin_name)."</div>";
						}else{
							$multiple_select = '';
							$allow_multivote_answer = '';
						}

						if ($show_answers_icon && $poll_theme != 'ays-minimal-theme') {
                          	switch ($options['answers_icon']) {
         	            		case 'radio':
         	            			$answer_icon_class = 'ays_poll_answer_icon_radio';
         	            			break;
         	            		case 'checkbox':
         	            			$answer_icon_class = 'ays_poll_answer_icon_checkbox';
         	            			break;	             	            		
         	            		default:
         	            			$answer_icon_class = '';
         	            			break;
         	            	}
                        }else{
                        	$answer_icon_class = '';
                        }

						if (intval($limit_users) < $attempts_count || intval($limit_users) == 0) {
                            $view_more_button_flag = false;
                            if (isset($poll['type']) && $poll['type'] == 'choosing') {
                                if ($enable_view_more_button) {
                                    if ( $poll_view_more_button_count != 0 && $poll_view_more_button_count < count($poll['answers']) ) {
                                        $view_more_button_flag = true;
                                    }
                                }
                            }

                            $poll_answer_votes = null;
                            $poll_answer_votes_sum = null;
							$randomize_answers = (isset($poll['styles']['randomize_answers']) && $poll['styles']['randomize_answers'] == 'on') ? true : false;
							switch ( $poll['type'] ) {
								case 'choosing':
									$redirect_after_submit = (isset($poll['styles']['redirect_after_submit']) && $poll['styles']['redirect_after_submit'] == 1) ? 'redirect-after-vote-url' : '';
									if ($randomize_answers) {
										shuffle($poll['answers']);
									}
                                    $numbering_type = "";
									$content .= "<div class='apm-answers $without_vote " . ($poll['view_type'] == 'grid' ? "apm-grid" : "") . "'>";
									$content .= "<input type='hidden' id='multivot_answer_count' value='".$multivote_answer_count."'/>";
									$content .= $poll_multivote_min_count_content;
                                    $answers_count = isset($poll['answers']) && $poll['answers'] != '' ? count($poll['answers']) : false;
                                    $numbering_type_arr = array();
                                    if($answers_count){
                                        $numbering_type_arr = $this->ays_answer_numbering($show_answers_numbering , $answers_count);
                                    }
                                    $poll_answer_percentages = array();
                                    $poll_answer_votes = array();
									foreach ( $poll['answers'] as $index => $answer ) {
                                        if($fake_votes){
                                            if(intval( $answer['votes'] ) + intval( $answer['fake_votes'] ) < 0){
                                                $poll_answer_votes[$answer['id']] = intval( $answer['votes'] );
                                            }
                                            else{
                                                $poll_answer_votes[$answer['id']] = intval( $answer['votes'] ) + intval( $answer['fake_votes'] );
                                            }
                                        }
                                        else{
                                            $poll_answer_votes[$answer['id']] = intval( $answer['votes'] );
                                        }
                                    }
                                    
                                    $poll_answer_votes_sum = array_sum( $poll_answer_votes );
                                    $poll_answer_percentages = array();
                                    foreach ( $poll_answer_votes as $index => $answer_vote_count ) {
                                        if( $poll_answer_votes_sum != 0 ){
                                            $poll_answer_percentages[$index] = round( ( $answer_vote_count * 100 ) / $poll_answer_votes_sum, 1);
                                        }else{
                                            $poll_answer_percentages[$index] = 0;
                                        }
                                    }

                                    $show_votes_count = isset($options['show_votes_count']) && $options['show_votes_count'] == 1 ? true : false;
                                    $show_answer_percent = isset($options['show_res_percent']) && $options['show_res_percent'] == 1 ? true : false;

                                    foreach ( $poll['answers'] as $index => $answer ) {
                                        $poll_answers_img = (isset($answer['answer_img']) && $answer['answer_img'] != '') ? $answer['answer_img'] : '';
                                        $poll_view_type = (isset($answer['view_type']) && $answer['view_type'] != '') ? $answer['view_type'] : 'list';
                                        
                                        $answers_img = '';
                                        $answers_background_img = '';
                                        if($poll_answers_img != ''){
                                            if($poll_view_type == 'list'){
                                                $answers_img = '<img src="'.$poll_answers_img.'" style="padding:10px;">';
                                                $answers_background_img = '';
                                            }elseif($poll_view_type == 'grid'){
                                                $answers_img = '';
                                                $answers_background_img = 'background-image:url("'.$poll_answers_img.'")';
                                            }
                                        }

										if ($answer['user_added'] == 1 && $answer['show_user_added'] ==  0) {
											continue;
										}else{
											if ($answer['show_user_added'] ==  0){
												continue;
											}else{
                                                $answer_style_class = '';
                                                if ($view_more_button_flag) {
                                                    if ($poll_view_more_button_count - 1 < $index) {
                                                        $answer_style_class = 'ays_poll_display_none';
                                                    }
                                                }

                                                $show_votes_before_voting_display_none = "";
                                                if( !$show_votes_before_voting ){
                                                    $show_votes_before_voting_display_none = "display:none;";
                                                }
                                                $opacity_bg_color_svbv = $poll['view_type'] == 'grid' ? 0.6 : 0.3;
                                                $show_votes_before_voting_color = $this->rgb2hex( $text_color );
                                                $show_votes_before_voting_color = $this->hex2rgba( $show_votes_before_voting_color, $opacity_bg_color_svbv );
                                                
                                                $show_votes_before_voting_display = "style='text-shadow: 0px 0px 5px " . $bg_color . ";'";
                                                $show_votes_before_voting_display_width = "";
                                                if( !$show_votes_before_voting ){
                                                    $show_votes_before_voting_display = "style='{$show_votes_before_voting_display_none}text-shadow: 0px 0px 5px " . $bg_color . ";'";
                                                    $show_votes_before_voting_display_width = "style='{$show_votes_before_voting_display_none}text-shadow: 0px 0px 5px " . $bg_color . ";'";
                                                }

                                                if( $poll['view_type'] == 'grid' ){
                                                    $show_votes_before_voting_display = "style='{$show_votes_before_voting_display_none}justify-content:center;font-weight:900;text-shadow: 0px 0px 5px " . $bg_color . ";'";
                                                    $show_votes_before_voting_display_width = "style='{$show_votes_before_voting_display_none}text-shadow: 0px 0px 5px " . $bg_color . ";'";
                                                }

                                                // Answer numbering
                                                if(!empty($numbering_type_arr)){
                                                    $numbering_type = isset($numbering_type_arr[$index]) && $numbering_type_arr[$index] != "" ? $numbering_type_arr[$index] : "";
                                                    $numbering_type = $numbering_type . " "; 
                                                }

												$content .= "
			                                        <div class='apm-choosing answer-$this_poll_id ". $answer_style_class ."'>
			                                            <input type='".$multivote_checkbox."' name='answer' id='radio-$index-$this_poll_id' value='{$answer['id']}'>
			                                            <label for='radio-$index-$this_poll_id' answers-url='".$answer['redirect']."' 
			                                            	class='ays_label_poll ".$answers_sound_class." ".$answer_icon_class." ".$disable_answer_hover." ".$redirect_after_submit." " . (!empty($answer['answer_img']) && $poll['view_type'] == 'grid' ? " apm-label-with-bg " : "") . " ' style='".$answers_background_img."'>
                                                            {$answers_img}
			                                                <span class='ays_grid_answer_span'>". $numbering_type . stripcslashes(html_entity_decode($answer['answer'])) . "</span>";

                                                $answer_votes_count_before_voting = "";
                                                switch ( $show_votes_before_voting_by ) {
                                                    case 'by_percentage':
                                                        $answer_votes_count_before_voting = $poll_answer_percentages[$answer['id']] . "%";
                                                        // if( $show_votes_count ){
                                                        //     $answer_votes_count_before_voting .= " (". intval( $answer['votes'] ) .")";
                                                        // }
                                                        break;
                                                    default:
                                                        $real_votes = isset($answer['votes']) && $answer['votes'] != "" ? intval( $answer['votes'] ) : 0;
                                                        $fake_votes_all = isset($answer['fake_votes']) && $answer['fake_votes'] != "0" ? intval( $answer['fake_votes'] ) : 0;
                                                        if($fake_votes){
                                                            if($real_votes + $fake_votes_all < 0){
                                                                $answer_votes_count_before_voting = $real_votes;
                                                            }
                                                            else{
                                                                $answer_votes_count_before_voting = $real_votes + $fake_votes_all;
                                                            }
                                                        }
                                                        else{
                                                            $answer_votes_count_before_voting = $real_votes;
                                                        }
                                                        // if( $show_answer_percent ){
                                                        //     $answer_votes_count_before_voting .= " (". $poll_answer_percentages[$answer['id']] . "%" .")";
                                                        // }
                                                        break;
                                                }

                                                $content .= "<span class='ayspoll-answers-votes-count-before-voting' ". $show_votes_before_voting_display .">". $answer_votes_count_before_voting ."</span>
                                                        <span class='ayspoll-answers-votes-count-before-voting-width' ". $show_votes_before_voting_display_width .">
                                                            <span style='width: ". $poll_answer_percentages[$answer['id']] ."%; background-color:" . $show_votes_before_voting_color . ";'></span>
                                                        </span>";
                                                $content .= "
                                                        </label>
			                                        </div>
			                                    ";		
											}
										}
									}
                                    $content .= $poll_multivote_message_content;
									$add_answer_for_grid = isset($poll['view_type']) && $poll['view_type'] == 'grid' ? 'add_answer_for_grid' : '';
									if ($allow_add_answer) {
                                        $content .= "<div class='apm-choosing answer-$this_poll_id ".$this_poll_id."_addAnswer apm-add-answer ".$add_answer_for_grid."'>
                                                        <input type='text' placeholder='" . __("Other - please specify", $this->plugin_name) . "' class='ays-poll-new-answer-apply-text' name='ays_poll_new_answer' autocomplete='off'>									          
                                                     </div>";

                                        $allow_multi_vote_for_other = isset($options["allow_multivote"]) && $options["allow_multivote"] == "on" ? true : false;
                                        
                                        if(!$allow_multi_vote_for_other){
                                            $content .= "<div class='ays-poll-add-answer-note ays-poll-add-answer-note-enable'>
                                                            <blockquote class='ays-poll-add-answer-note-text'>".__( 'Note if the other answer is filled, it will be considered as a vote and will ignore the checked answers.', $this->plugin_name)."</blockquote>
                                                        </div>";
                                        }
                                        // OLD OTHER ANSWER
										// $content .= "
	                                    //     <div class='apm-choosing answer-$this_poll_id ".$this_poll_id."_addAnswer apm-add-answer ".$add_answer_for_grid."'>
	                                    //           <input type='text' placeholder='" . __("Other - please specify", $this->plugin_name) . "'>
	                                    //           <input type='button' value='" . __("Submit", $this->plugin_name) . "' class='apm-new-answer-apply'>
	                                    //     </div>
	                                    // ";
									}
									break;
								case 'versus':
									if ($randomize_answers) {
										shuffle($poll['answers']);
									}
									$vs_icon_type = isset($options['versus_icon_type']) ? $options['versus_icon_type'] : "";
									$vs_icon_pos  = isset($options['versus_icon_position']) ? $options['versus_icon_position'] : "";
									$content      .= "<div class='apm-answers $without_vote apm-versus {$poll['view_type']} vs-$vs_icon_type vs-icon-$vs_icon_pos'>";
									foreach ( $poll['answers'] as $index => $answer ) {
										$content .= "
	                                        <div class='apm-versus-answer answer-$this_poll_id'>
	                                            <input type='radio' name='answer' id='radio-$index-$this_poll_id' value='{$answer['id']}'>
	                                            <label for='radio-$index-$this_poll_id' " . (!empty($answer['answer_img']) ? "class='apm-label-with-bg ".$answers_sound_class."' style='background-image:url({$answer['answer_img']})'" : "class='apm-simple-label'") . ">
	                                                " . ((isset($options['versus_answers_label']) && $options['versus_answers_label']) || empty($answer['answer_img']) ? "<span>" . stripcslashes(html_entity_decode($answer['answer'])) . "</span>" : "") . "
	                                            </label>
	                                        </div>
	                                    ";
									}
									break;
								case 'voting':
									$content .= "<div class='apm-answers $without_vote'>";
									switch ( $poll['view_type'] ) {
										case 'hand':
											foreach ( $poll['answers'] as $index => $answer ) {
												$content .= "<div class='apm-voting answer-$this_poll_id'><input type='radio' name='answer' id='radio-$index-$this_poll_id' value='{$answer['id']}'>
	                            	<label for='radio-$index-$this_poll_id' class='".$answers_sound_class."'>";
												$content .= ((int) $answer['answer'] > 0 ? $answer_icons['thumb'][0] : $answer_icons['thumb'][1]) . "</label></div>";
											}
											break;
										case 'emoji':
											foreach ( $poll['answers'] as $index => $answer ) {
												$content .= "<div class='apm-voting answer-$this_poll_id'><input type='radio' name='answer' id='radio-$index-$this_poll_id' value='{$answer['id']}'>
	                            	<label for='radio-$index-$this_poll_id' class='".$answers_sound_class."'>";
												$content .= ((int) $answer['answer'] > 0 ? $answer_icons['emoji'][1] : $answer_icons['emoji'][3]) . "</label></div>";
											}
											break;
									}
									break;
								case 'rating':
									$content .= "<div class='apm-answers $without_vote'>";
									switch ( $poll['view_type'] ) {
										case 'emoji':
											foreach ( $poll['answers'] as $index => $answer ) {
												$content .= "<div class='apm-rating answer-$this_poll_id'><input type='radio' name='answer' id='radio-$index-$this_poll_id' value='{$answer['id']}'>
	                            	<label class='emoji' for='radio-$index-$this_poll_id' class='".$answers_sound_class."'>" . $answer_icons['emoji'][(count($poll['answers']) / 2 - $index + 1.5)] . "</label></div>";
											}
											break;
										default:
											foreach ( $poll['answers'] as $index => $answer ) {
												$content .= "<div class='apm-rating answer-$this_poll_id'><input type='radio' name='answer' id='radio-$index-$this_poll_id' value='{$answer['id']}'>
	                            	<label for='radio-$index-$this_poll_id' class='".$answers_sound_class."'>{$answer_icons[$poll['view_type']]}</label></div>";
											}
											break;
									}
									break;
								case 'dropdown':
									$redirect_after_submit = (isset($poll['styles']['redirect_after_submit']) && $poll['styles']['redirect_after_submit'] == 1) ? 'redirect-after-vote-url' : '';
									if ($randomize_answers) {
										shuffle($poll['answers']);
									}
									$content .= "<div class='apm-answers ".$without_vote."' >";
									$content .= "<input type='hidden' id='multivote_answer_count_select' value='".$multivote_answer_count."'/>";
									$content .= "<input type='hidden' class='multivote_answer_selected_val' value=''/>";
									$content .= "<input type='hidden' class='multivote_answer_on' value='".$allow_multivote_answer."'/>";
									$content .= "<div style='text-align:center;'>
										<select class='apm-dropdown answer-$this_poll_id' id='apm_dropdown_answers' style='width: 80%' name='answer' ".$multiple_select.">";
									foreach ( $poll['answers'] as $index => $answer ) {
											$content .= "
												<option value='{$answer['id']}'>".stripcslashes(html_entity_decode($answer['answer']))."</option>
			                                ";
									}
									$content .= "</select></div>";
									break;
                                case 'range':
                                    $content .= "<div class='apm-answers $without_vote'>";
                                        $content .= "<div class='apm-range answer-$this_poll_id'>
                                                        <div class='range-value' id='rangeV'><span class='range_value_span'>0</span></div>
                                                        <input type='range' name='answer' id='apm_range_answer_$this_poll_id' min='0' max='100' value='0' class='".$answers_sound_class." apm_range_answer apm_range'>
                                                    </div>";
                                    break;
                                case 'text':
                                    $content .= "<div class='apm-answers $without_vote'>";                                    
                                    $poll_text_type_placeholder = ( isset($options['poll_text_type_placeholder']) && $options['poll_text_type_placeholder'] != "" ) ?  stripslashes(esc_attr($options['poll_text_type_placeholder'])) : "";
                                    switch ( $poll_view_type_text ) {
                                        case 'short_text':
                                            $content .= "<div class='ays-poll-maker-text-answer-main answer-".$this_poll_id."'>
                                                            <div class='ays-poll-maker-text-answer-main-for-text'>
                                                                <input type='text' id='ays-poll-text-type-short-".$this_poll_id."' class='ays-poll-text-types-inputs ".$poll_class_for_limits."' placeholder='".$poll_text_type_placeholder."' name='answer' data-max-length='".$poll_text_type_limit_length."' data-limit-type='".$poll_text_type_limit_type."' autocomplete='off'>
                                                                
                                                            </div>
                                                            ".$poll_box_for_limit_message."
                                                        </div>";											
                                            break;
                                        case 'paragraph':
                                            $content .= "<div class='ays-poll-maker-text-answer-main answer-".$this_poll_id."'>
                                                            <div class='ays-poll-maker-text-answer-main-for-text'>
                                                                <textarea id='ays-poll-text-type-paragraph-".$this_poll_id."' class='ays-poll-text-types-inputs ays-poll-text-types-inputs-only-textarea ".$poll_class_for_limits."' placeholder='".$poll_text_type_placeholder."' name='answer' data-max-length='".$poll_text_type_limit_length."' data-limit-type='".$poll_text_type_limit_type."'></textarea>
                                                                
                                                            </div>
                                                            ".$poll_box_for_limit_message."
                                                        </div>";
                                            break;
                                        default:
                                            break;
                                    }
                                    break;
        

							}
                            if ($view_more_button_flag) {
                                $content .= '
                                <div class="ays-poll-view-more-button-box">
                                    <input type="button" class="btn ays-poll-btn ays-poll-view-more-button" value="'. __( "View more" , $this->plugin_name ) .'">
                                </div>';
                            }

							$content .= "</div>";
							$content .= "<div class='apm-cashed-fa'>";
							foreach ( $poll['answers'] as $index => $answer ) {
								$content .= "<div>
	                            <i class='ays_poll_fas ays_poll_fa-star' style='font-size: 0'></i>
	                        </div>";
							}
							$content .= "</div>";
							if (isset($options['info_form']) && $options['info_form'] == 1 && !empty($poll["fields"])) {
                                $this->fields_placeholders = $this->ays_set_poll_fields_placeholders_texts();
								$content .= "<div class='user-form user-form-$this_poll_id'>
											$form_title";
                                            
								foreach ( $fields as $field ) {
									if($field['type'] == "checkbox"){
						                $attr_description = isset($field['options']) ? $field['options'] : '';
						                $content .= "<div class='ays_poll_checkbox_for_label'>";
						                $content .= "<label class='ays_poll_for_checkbox'>". $field['name'];
						                $content .= "<input type='checkbox' class='ays_poll_form_input ays_animated_xms' name='". $field['slug'] ."' " . $field['slug'] . " " . ((array_search($field['slug'], array_column($required_fields, 'slug')) !== false) ? "required" : "") . " />";
						                $content .= "</label>";
						                if($attr_description != ''){
						                    $content .= "<span class='ays_poll_checkbox_for_span'>".stripslashes(html_entity_decode($attr_description))."</span>";
						                }
						                $content .= "</div>";
						            }else{
                                        $field_placeholder = "";
                                        // if($field['type'] == "text"){
                                        //     $field_placeholder = $this->fields_placeholders['namePlaceholder'];
                                        // }
                                        if($field['type'] == "email"){
                                            $field_placeholder = $this->fields_placeholders['emailPlaceholder'];
                                        }
                                        else {
                                            $field_placeholder = (isset( $field['name'] ) && $field['name'] != "") ? stripslashes( esc_attr( $field['name'] ) ) : "";

                                        }
						            	$check_id_email = isset($field['type']) && $field['type'] == 'email' ? " check_id='".$this_poll_id."' " : '';
                                        $phone_type = isset($field['type']) && $field['type'] == 'tel' ? " phone_type_id='tel_".$this_poll_id."' " : '';
										$content .= "<input type='{$field['type']}' class='ays_animated_xms' ".$check_id_email." ".$phone_type." name='user-form-{$field['slug']}' " . ((array_search($field['slug'], array_column($required_fields, 'slug')) !== false) ? "required" : "") . " placeholder='".$field_placeholder."'>";
									}
								}
								$content .= "<input type='button' name='ays_finish_poll' class='btn ays-poll-btn {$poll['type']}-btn' data-form='$this_poll_id' data-id='{$poll['id']}'" . 'value="' . __("Send", $this->plugin_name) . '">';
								$content .= "</div>";
							}
						} else {
							$content .= "<div class='ays-poll-vote-message'>" . (isset($options['limitation_message']) && $options['limitation_message'] != '' ? stripslashes($options['limitation_message']) : ("<p>" . __("You have already voted.", $this->plugin_name) . "</p>")) . "</div>";
							if (isset($options['redirect_url']) && $options['redirect_url'] != '' && isset($options['redirection_delay']) && $options['redirection_delay'] != 0) {
								$content .= "<div class='apm-redirection apm-redirection-$this_poll_id'>
	                                        <p data-id='$this_poll_id' data-href='" . stripslashes($options['redirect_url']) . "' data-delay='{$options['redirection_delay']}'>" . __('Redirecting after', $this->plugin_name)
								            . " <b>{$this->secondsToWords($options['redirection_delay'])}</b>
	                                        </p>
	                                    </div>";
							}
						}
					}
				}
				
				$show_res_button = !is_user_logged_in() && !$show_login_form ? true : false;
				
				if (is_user_logged_in() || $show_res_button) {
					$content .= $voteReason;			
					if($limit_users > 0){
                        $content .= wp_nonce_field('ays_finish_poll', 'ays_finish_poll');
                    }
                    else{
                        $content .= wp_nonce_field('ays_finish_poll', 'ays_finish_poll') . "<div class='apm-button-box'>";
                    }
                    if (!empty($options['allow_not_vote']) && $limit_users == 0 && $poll['type'] != "text") {
                        $content .= "<input type='button' class='btn ays-poll-btn ays-poll-not-send-email {$poll['type']}-btn' data-form='$this_poll_id' value='" . $ays_see_result_button_text . "' data-seeRes='true' data-type='".$poll['type']."'>";
                    }
                    if($limit_users != 0 && intval($limit_users) >= $attempts_count){
                        if($poll_see_result_button_check){
                            if($poll_show_result_button_limit){
                                $content .= "<div class='apm-button-box'>";
                                if($poll['type'] != "text"){
                                    $content .= "<input type='button' class='btn ays-poll-btn {$poll['type']}-btn ays-see-res-button-show' data-form='$this_poll_id' value='" . $ays_see_result_button_text . "' data-seeRes='true' data-type='".$poll['type']."'>";
                                }
                                $content .= "</div>";
    
                            }
                            elseif($poll_see_result_immediately){							
                                $result_content = $this->ays_poll_get_results($id);
                                $content .= $result_content;
                                if($poll_show_avatars){
                                    $content .= "<script>
                                        var resLoader = '".POLL_MAKER_AYS_ADMIN_URL."/images/loaders/tail-spin.svg';
                                        var idChecker = 'ays-poll-container-" . $id . "';
                                    </script>";
                                }
                            }
                            
                        }
                    }
    
    
					if ((intval($limit_users) < $attempts_count || intval($limit_users) == 0) && $load_poll) {
                        if(intval($limit_users) != 0){
                            $content .= "<div class='apm-button-box'>";
                        }
						$content .= "<input type='button' 
		                    name='ays_finish_poll'
		                    class='btn ays-poll-btn {$poll['type']}-btn ays_finish_poll'
		                    data-form='$this_poll_id'
		                    " . (!$load_poll ? "data-allow='false'" : "") .
						            'value="' . $ays_vote_button_text . '"
		                    >';
                        if(intval($limit_users) != 0){
                            $content .= "</div>";
                        }
					}
				
				}
				if(!$limit_users > 0){
                    $content .= '</div>';
                }
    
				$content .= $result_message;
				$content .= $redirect_after_vote;
			} elseif ($is_start_soon) {
				$poll_is_start_message = isset($options['active_date_message_soon']) ? stripslashes($options['active_date_message_soon']) : "<p>" . __('The poll will be available soon.', $this->plugin_name) . "</p>";
				$content              .= "<div class='apm_expired_poll'>".$poll_is_start_message."</div>";

					if ($show_res_btn_sch) {
						$content .=  $see_result_button;
					}

			} else {
				$expired_poll_message = isset($options['active_date_message']) ? stripslashes($options['active_date_message']) : "<p>" . __('The poll has expired.', $this->plugin_name) . "</p>";
				$content              .= "<div class='apm_expired_poll'>$expired_poll_message</div>";
				
				if ($show_res_btn_sch) {
					$content .=  $see_result_button;
				}

			}


            unset($poll['styles']);
            $poll_options = $options;
            foreach($poll as $k => $q){
                $poll_options[$k] = $q;
            }
            
            foreach($poll_options as $k => $q){
                if(strpos($k, 'smtp') !== false || strpos($k, 'email') !== false ){
                    if($k == 'form_email'){
                        continue;
                    }
                    unset($poll_options[$k]);
                }
            }

            if( isset($poll_answer_votes) ){
                $poll_options['answer_votes'] = $poll_answer_votes;
            }
            if( isset($poll_answer_votes_sum) ){
                $poll_options['answer_votes_sum'] = $poll_answer_votes_sum;
            }

            $content .= "<script>";
                $content .= "
                    if(typeof aysPollOptions === 'undefined'){
                        var aysPollOptions = [];
                    }
                    aysPollOptions['".$id."']  = '" . base64_encode(json_encode($poll_options)) . "';";
            $content .= "
                </script>";

            $content .= '</div></form></div>';
		}

		if ($echo) {
			echo $content;

			return true;
		} else {
			return $content;
		}

	}

	public function ays_poll_category_generate_html($attr, $echo = true){
		$id = absint($attr['cat_id']);
		global $wpdb;
		$sql    = "SELECT id FROM {$wpdb->prefix}ayspoll_polls WHERE categories LIKE '%$id,%';";
		$result = $wpdb->get_results($sql, 'ARRAY_A');
        $poll_id = "";
		if (!empty($result)) {
            if(isset($result[0])){
                $poll_id = isset($result[0]['id']) && $result[0]['id'] != "" ? $result[0]['id'] : "";
            }
			
		}
		$cat = $this->ays_get_poll_category($id);
        $poll = array();
        if($poll_id != ""){
            $poll = $this->get_poll_by_id($poll_id);
        }
        if(isset($poll['styles']) && !empty($poll['styles'])){            
            $poll_width = isset($poll['styles']['width']) && $poll['styles']['width'] > 0 ? $poll['styles']['width']."px" : "100%";
        }  
        $cat_opt       = json_decode($cat['options'], true);
		if (empty($cat)) {
			return "";
		}
		//AV Check expired polls
        $check_poll = false;
        $new_res = array();
        $checker = array();
        foreach ($result as $key => $value) {
            $check_poll = $this->check_shedule_expired_poll( $value['id'] );

            if ($check_poll) {
                $new_res[] = $result[$key];
            }
            $checker[] = $check_poll;
        }
        // ==== ADDED NEW ====
        if(array_sum($checker) == 0){
            $default_message = __('The polls that belong to this category are expired or unpublished', $this->plugin_name);
		    $exp_message = isset($cat_opt['exp_message']) && $cat_opt['exp_message'] != '' ? stripslashes(esc_html($cat_opt['exp_message'])) : $default_message;
			echo "<div class='ays_exp_cat_message'>".$exp_message."</div>";
		}
        // ==== ====

        if (empty($new_res)) {
            return "";
        }

        $polls_pool    = $this->ays_get_polls_pool($new_res);
		// $cat_opt       = json_decode($cat['options'], true);

        $ays_next_button = (isset($cat_opt['next_text']) && $cat_opt['next_text'] != '') ? stripslashes($cat_opt['next_text']) : 'Next';

        if ($ays_next_button === 'Next') {
            $ays_next_button_text =  __("Next", $this->plugin_name);
        }else{
            $ays_next_button_text = $ays_next_button;
        }

        $ays_previous_button = (isset($cat_opt['previous_text']) && $cat_opt['previous_text'] != '') ? stripslashes($cat_opt['previous_text']) : 'Previous';

        $ays_previous_button_text = '';
        if ($ays_previous_button === 'Previous') {
            $ays_previous_button_text =  __("Previous", $this->plugin_name);
        }else{
            $ays_previous_button_text = $ays_previous_button;
        }

        $cat_opt['allow_autonext'] = isset($cat_opt['allow_autonext']) ? $cat_opt['allow_autonext'] : 'off';
        $allow_autonext = (isset($cat_opt['allow_autonext']) && $cat_opt['allow_autonext'] == 'on' ) ? 'on' : 'off';
        $poll_disable_prev = (isset($cat_opt['poll_disable_prev']) && $cat_opt['poll_disable_prev'] == 'on' ) ? "true" : "false";
		$show_next     = isset($cat_opt['allow_skip']) && $cat_opt['allow_skip'] == 'allow' ? 'true' : 'false';
        $show_next_val = ($show_next == 'true') ? 'true' : 'false'; 
		$cat_id        = uniqid('ays-poll-category-pool-');
		$j             = uniqid('JsVariable');
		$content       = "
            <div style='margin:1rem auto;' class='ays_poll_category-container' data-autoNext='". $allow_autonext ."' data-var='".$j."' id='$cat_id' data-prev-disable='".$poll_disable_prev."'>
            </div>
            <style>
                #".$cat_id." div.previous_next_buttons{
                    display:flex;
                    max-width: 100%;
                }
            </style>
            <script>
                var catContainer".$j." = '".$cat_id."';
                var pollsGlobalPool".$j." = ".$polls_pool.";
                var showNext".$j." = ".$show_next.";
                var showPrev".$j." = false;
                var showNextVal".$j." = ".$show_next_val.";
                var catIndex".$j." = 0;
                var aysPollBtnText".$j." = '" . $ays_next_button_text . "';
                var aysPollPreviousBtnText".$j." = '" . $ays_previous_button_text . "';
            </script>";
		if ($echo) {
			echo $content;
		} else {
			return $content;
		}
	}

	public function get_poll_by_id( $id ) {
		global $wpdb;
        $poll_table = esc_sql($wpdb->prefix."ayspoll_polls");
        $sql  = "SELECT * FROM ".$poll_table." WHERE id=" . absint($id);
        $ordering = 'ORDER BY ordering ASC, id ASC';
        $poll = $wpdb->get_row($sql, 'ARRAY_A');
        if (empty($poll)) {
            return $poll;
        }
        $json = $poll['styles'];
        $poll['styles'] = json_decode($json, true);
        $poll_type = (isset($poll['type']) && $poll['type'] != '') ? $poll['type'] : '';
        if($poll_type == 'choosing'){
            $answer_ordering = (isset($poll['styles']['answer_sort_type']) && $poll['styles']['answer_sort_type'] != '') ? $poll['styles']['answer_sort_type'] : '';      
            if($answer_ordering != ''){
                switch ($answer_ordering){
                    case 'ascending':
                        $ordering = 'ORDER BY answer ASC';
                    break;
                    case 'descending':
                        $ordering = 'ORDER BY answer DESC';
                    break;
                    case 'votes_asc':
                        $ordering = 'ORDER BY votes DESC, id ASC';
                    break;
                    case 'votes_desc':
                        $ordering = 'ORDER BY votes ASC, id ASC';
                    break;
                    default:
                        $ordering = "ORDER BY ordering ASC, id ASC";
                    break;
                }
            }
        }
        $answ_table = esc_sql($wpdb->prefix."ayspoll_answers");
        $sql = "SELECT * FROM ".$answ_table." WHERE poll_id=" . absint($id) . " AND show_user_added = 1 ".$ordering;
        $poll['answers']    = $wpdb->get_results($sql, 'ARRAY_A');
        $poll['categories'] = trim($poll['categories'], ',');
        $cats               = explode(',', $poll['categories']);
        $poll['categories'] = !empty($cats) ? $cats : [];
        $all_fields         = $this->get_all_formfields();
        if (isset($poll['styles']['fields'])) {
            $poll['fields'] = array();
            $fields         = explode(',', $poll['styles']['fields']);
            foreach ( $fields as $field ) {
                $index = array_search($field, array_column($all_fields, 'slug'));
                if ($index !== false) {
                    $poll['fields'][] = $all_fields[$index];
                }
            }
        }
        if (isset($poll['styles']['required_fields'])) {
            $poll['required_fields'] = array();
            $fields                  = explode(',', $poll['styles']['required_fields']);
            foreach ( $fields as $field ) {
                $index = array_search($field, array_column($all_fields, 'slug'));
                if ($index !== false) {
                    $poll['required_fields'][] = $all_fields[$index];
                }
            }
        }
        return $poll;
	}

	public function get_all_formfields() {
		global $wpdb;
		$all = array(
			array(
				"id"        => 0,
				"name"      => "Name",
				"type"      => "text",
				"slug"      => "apm-name",
				"published" => 1,
                "sendgrid"  => "name",
			),
			array(
				"id"        => 0,
				"name"      => "E-mail",
				"type"      => "email",
				"slug"      => "apm-email",
				"published" => 1,
                "sendgrid"  => "email",
			),
		);
		$sql = "SELECT * FROM {$wpdb->prefix}ayspoll_formfields WHERE published='1'";
		$res = $wpdb->get_results($sql, 'ARRAY_A');

		return array_merge($all, $res);
	}

	public function get_user_requests_info(){
        global $wpdb;

        $current_user = wp_get_current_user();
        $id = $current_user->ID;
        if($id == 0){
            return null;
        }

        $requests_table = $wpdb->prefix . "ayspoll_requests";
        $sql = "SELECT * FROM ".$requests_table." WHERE `user_id`= ".$id." ORDER BY request_date DESC";
        $results = $wpdb->get_results($sql, "ARRAY_A");

        return $results;

    }

    public function rgb2hex( $rgba ) {
        if ( strpos( $rgba, '#' ) === 0 ) {
            return $rgba;
        }

        preg_match( '/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i', $rgba, $by_color );

        return sprintf( '#%02x%02x%02x', $by_color[1], $by_color[2], $by_color[3] );
    }

    public function get_poll_results_count_by_id( $id ) {
		global $wpdb;

		$sql = "SELECT * FROM `{$wpdb->prefix}ayspoll_reports` WHERE poll_id=$id";
		$result = $wpdb->get_results($sql, "ARRAY_A");

		$multivote_answers_ids = array();
		$multivote_answers = array();

		foreach ($result as $r_key => $r_value) {

			$r_value['multi_answer_id'] = json_decode($r_value['multi_answer_id'], true);

			$multivote_res = false;
			if (isset($r_value['multi_answer_id']) && count($r_value['multi_answer_id']) > 0) {
				$multivote_res = true;
			}

			if ($multivote_res) {
				foreach ($r_value['multi_answer_id'] as $m_key => $m_val) {
					$multivote_answers_ids[] = $m_val;
					$multi_answer = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE id=".$m_val, "ARRAY_A");
					$multivote_answers[ $m_val ] = $multi_answer['answer'];
				}
				$answ_poll_id = $multi_answer['poll_id'];
			} else {
				$answer = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}ayspoll_answers WHERE id={$r_value['answer_id']}", "ARRAY_A");
				$multivote_answers_ids[] = $r_value['answer_id'];
				$multivote_answers[ $r_value['answer_id'] ] = $answer['answer'];
				$answ_poll_id = $answer['poll_id'];
			}
		}

		$multivote_answers_count_arr = array_count_values( $multivote_answers_ids );
		
		$res = 0;
		foreach ($multivote_answers_count_arr as $key => $value) {
			$res += $value;
		}

		if ( is_null( $res ) || empty( $res ) ) {
			$res = 0;
		}
        
        

		return array("res_count" => $res);
	}

    public function check_shedule_expired_poll( $args ) {
        $id = absint(intval($args));
        $poll_options = $this->get_poll_by_id($id);
        $options = $poll_options['styles'];
            
        $is_expired = true;
        $startDate = '';
        $endDate = '';
        $current_time = strtotime(current_time( "Y:m:d H:i:s" ));
        if (isset($options['active_date_check']) && !empty($options['active_date_check'])) {
            if (isset($options['activeInterval']) && isset($options['deactiveInterval'])) {
                if (isset($options['activeIntervalSec']) && !empty($options['activeIntervalSec'])) {
                    $startDate = strtotime($options['activeInterval']." ".$options['activeIntervalSec']);
                }
                else{
                    $startDate = strtotime($options['activeInterval']);                 
                }

                if (isset($options['deactiveIntervalSec']) && !empty($options['deactiveIntervalSec'])) {
                    $endDate   = strtotime($options['deactiveInterval']." ".$options['deactiveIntervalSec']);
                }
                else{
                    $endDate   = strtotime($options['deactiveInterval']);                   
                }
                             
                if ($startDate < $current_time && $endDate > $current_time) {
                    $is_expired = true;
                }else{
                    $is_expired = false;
                }
            }
        }
        $published = (isset($options['published']) && intval($options['published']) === 0) ? false : true;
        return $is_expired && $published ? true : false;
    }

	public function hex2rgba( $color, $opacity = false ) {

		$default = 'rgba(80, 24, 1, 0.5)';
		/**
		 * Return default if no color provided
		 */
		if (empty($color)) {
			return $default;
		}
		/**
		 * Sanitize $color if "#" is provided
		 */
		if ($color[0] == '#') {
			$color = substr($color, 1);
		} else {
			return $color;
		}

		/**
		 * Check if color has 6 or 3 characters and get values
		 */
		if (strlen($color) == 6) {
			$hex = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
		} elseif (strlen($color) == 3) {
			$hex = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
		} else {
			return $default;
		}

		/**
		 * [$rgb description]
		 * @var array
		 */
		$rgb = array_map('hexdec', $hex);
		/**
		 * Check if opacity is set(rgba or rgb)
		 */
		if ($opacity) {
			if (abs($opacity) > 1) {
				$opacity = 1;
			}
			$output = 'rgba( ' . implode(",", $rgb) . ',' . $opacity . ' )';
		} else {
			$output = 'rgb( ' . implode(",", $rgb) . ' )';
		}

		/**
		 * Return rgb(a) color string
		 */
		return $output;
	}

	private static function get_user_ip() {
		$ipaddress = '';
		if (getenv('HTTP_CLIENT_IP')) {
			$ipaddress = getenv('HTTP_CLIENT_IP');
		} else if (getenv('HTTP_X_FORWARDED_FOR')) {
			$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		} else if (getenv('HTTP_X_FORWARDED')) {
			$ipaddress = getenv('HTTP_X_FORWARDED');
		} else if (getenv('HTTP_FORWARDED_FOR')) {
			$ipaddress = getenv('HTTP_FORWARDED_FOR');
		} else if (getenv('HTTP_FORWARDED')) {
			$ipaddress = getenv('HTTP_FORWARDED');
		} else if (getenv('REMOTE_ADDR')) {
			$ipaddress = getenv('REMOTE_ADDR');
		} else {
			$ipaddress = 'UNKNOWN';
		}

		return $ipaddress;
	}

	public function secondsToWords( $seconds ) {
		$ret = "";
		/*** get the days ***/
		$days = intval(intval($seconds) / (3600 * 24));
		if ($days > 0) {
			$ret .= "$days days ";
		}
		/*** get the hours ***/
		$hours = (intval($seconds) / 3600) % 24;
		if ($hours > 0) {
			$ret .= "$hours hours ";
		}
		/*** get the minutes ***/
		$minutes = (intval($seconds) / 60) % 60;
		if ($minutes > 0) {
			$ret .= "$minutes minutes ";
		}
		/*** get the seconds ***/
		$seconds = intval($seconds) % 60;
		if ($seconds > 0) {
			$ret .= "$seconds seconds";
		}

		return $ret;
	}

	public function ays_get_polls_pool( $array_of_poll_id ) {
		$pool = array();
		foreach ( $array_of_poll_id as $poll ) {
			$pool[] = $this->ays_poll_generate_html($poll['id'], false);
		}

		return json_encode($pool);
	}

	public function ays_get_poll_category( $id ) {
		global $wpdb;

		$sql = "SELECT * FROM {$wpdb->prefix}ayspoll_categories WHERE id=" . absint(intval($id));

		$result = $wpdb->get_row($sql, 'ARRAY_A');

		return $result;
	}

	public function ays_add_answer_poll() {
		$poll_id    = absint($_REQUEST['poll_id']);
		$new_answer = wp_filter_kses($_REQUEST['new_answer']);
		global $wpdb;
		$poll = $this->get_poll_by_id($poll_id);

		if (empty($poll)) {
			return "";
		}

		$options      	 = $poll['styles'];
		$answer_message  = $poll['answer_message'];
        $add_answer_not_show_up = isset($options['add_answer_show_up']) && $options['add_answer_show_up'] == 0 ? true : false;
        $show_user_added = 0;
        if($add_answer_not_show_up){
            $show_user_added = 1;
        }
		$wpdb->insert(
			"{$wpdb->prefix}ayspoll_answers",
			array(
				'poll_id'    => $poll_id,
				'answer'     => $new_answer,
				'answer_img' => "",
				'user_added' => 1,
				'show_user_added' => $show_user_added
			),
			array(
				'%d',
				'%s',
				'%s',
				'%d',
				'%d'
			)
		);
		$last_id = $wpdb->insert_id;
		$answ_message = json_decode($answer_message, true);

		$answ_message[$last_id] = array(
									"answer" => "",
									"answer_image"=> ""
								);

		$answer_mess = json_encode($answ_message, true);
		$wpdb->update(
					"{$wpdb->prefix}ayspoll_polls",
					array('answer_message' => $answer_mess),
					array('id' => $poll_id),
					array('%s'), array('%d')
				);

		ob_end_clean();
		$ob_get_clean = ob_get_clean();		
		echo json_encode(array(
							"new_id" => $last_id,
							"options" => $options,
							"show_user_added" => $show_user_added
						));
		wp_die();
	}

    public function ays_add_answer_poll_new($data) {
		global $wpdb;
		$poll_id    = absint($data['poll_id']);
		$new_answer = wp_filter_kses($data['new_answer']);
        $poll_add_answer_require = $data['admin_require'];
        $poll_answers_count = isset($data['answers_count']) && $data['answers_count'] > 0 ? intval($data['answers_count']) : 1;
        $if_text_type = isset($data['if_text_type']) && $data['if_text_type'] ? true : false;

        $show_user_added = 0;
		$votes = 0;
		if($if_text_type){
			$votes = 1;
		}
        if(!$poll_add_answer_require){
            $show_user_added = 1;
        }
		$wpdb->insert(
			"{$wpdb->prefix}ayspoll_answers",
			array(
				'poll_id'    => $poll_id,
				'answer'     => $new_answer,
				'votes'      => $votes,
				'ordering'   => ($poll_answers_count + 1),
				'user_added' => 1,
				'show_user_added' => $show_user_added
			),
			array(
				'%d',
				'%s',
				'%d',
				'%d',
				'%d',
				'%d',
			)
		);

		$last_id = $wpdb->insert_id;
		return array(
				"new_id" => strval($last_id)
			);
	}

	public function ays_finish_poll() {
		if (isset($_POST["ays_finish_poll"]) && wp_verify_nonce($_POST["ays_finish_poll"], 'ays_finish_poll')) {
            $poll_id    = absint($_POST['poll_id']);
            
            $ays_send_mail_to_user  = null;
            $ays_send_mail_to_admin = null;

            $title_ids = array();
            $answer_titless = array();
			if (isset($_POST['answer']) && is_array($_POST['answer'])) {
				$answer_id = $_POST['answer'];
				$multi_answer_id = $_POST['answer'];
                $title_ids = implode(',' , $multi_answer_id);
			} else {
				$answer_id[]  = !isset($_POST['answer']) || $_POST['answer'] === null ? false : absint($_POST['answer']);
                $multi_answer_id = array();
                $title_ids = implode(',' , $answer_id);
            }
            if(!empty($title_ids)){
                $answer_titles = $this->get_answer_by_ids($title_ids);
                if(isset($answer_titles) && $answer_titles != null){
                    foreach($answer_titles as $t_key => $t_value){
                        foreach ($t_value as $r_key => $r_value) {
                            if($r_key == 'answer'){
                                $answer_titless[] = $r_value;
                            }
                        }
                    }
                }
            }
			$user_form  = array();
			$user_email = '';
			$poll       = $this->get_poll_by_id($poll_id);
            $poll_title = (isset($poll['title']) && $poll['title'] != '')  ? stripslashes( sanitize_text_field( $poll['title'] ) ) : '';
			$options    = $poll['styles'];
            $poll_answers_count  = isset($poll['answers']) ? count($poll['answers']) : 0;
            $added_answer_id = array();
            $show_answers_numbering = (isset($options['show_answers_numbering']) && sanitize_text_field( $options['show_answers_numbering'] ) != '') ? sanitize_text_field( $options['show_answers_numbering'] ) : 'none';
			if (isset($options['vote_reason']) && $options['vote_reason'] == 1 && isset($_POST['voteReason'])) {
				$user_form['voteReason'] = $_POST['voteReason'];
			}

            // Send Mail to User
            $options['ays_enable_mail_user'] = (isset($options['ays_enable_mail_user'])) ? $options['ays_enable_mail_user'] : 'off';
            $ays_enable_mail_user = (isset($options['ays_enable_mail_user']) && $options['ays_enable_mail_user'] == 'on') ? true : false;

            // Message ( Send Mail to User )
            $mail_usr_msg  = (isset($options['vote_notification_email_msg']) && $options['vote_notification_email_msg'] != '') ? $options['vote_notification_email_msg'] : '';

            // Send mail type Custom / SendGrid
            $poll_send_mail_type = (isset($options['poll_send_mail_type']) && $options['poll_send_mail_type'] != '') ? sanitize_text_field( $options['poll_send_mail_type'] ) : 'custom';

            // SendGrid email from
            $poll_sendgrid_email_from = (isset($options['poll_sendgrid_email_from']) && $options['poll_sendgrid_email_from'] != '') ? sanitize_email( $options['poll_sendgrid_email_from'] ) : '';
            $poll_sendgrid_email_name = (isset($options['poll_sendgrid_email_name']) && $options['poll_sendgrid_email_name'] != '') ? sanitize_text_field( $options['poll_sendgrid_email_name'] ) : '';

            // SendGrid template id
            $poll_sendgrid_template_id = (isset($options['poll_sendgrid_template_id']) && $options['poll_sendgrid_template_id'] != '') ? $options['poll_sendgrid_template_id'] : '';

            // Results notification by email
            $options['notify_email_on'] = (isset($options['notify_email_on'])) ? sanitize_text_field( $options['notify_email_on'] ) : '0';
            $notify_email_on = (isset($options['notify_email_on']) && $options['notify_email_on'] == '1') ? true : false;

            // Additional emails | Notify email
            $notify_email = (isset($options[ 'notify_email' ]) && $options[ 'notify_email' ] != '') ? stripslashes ( esc_attr( $options[ 'notify_email' ] ) ) : '';

            // Send mail to super Admin
            $options['poll_send_mail_to_site_admin'] = isset($options['poll_send_mail_to_site_admin']) ? $options['poll_send_mail_to_site_admin'] : 'on';
            $poll_send_mail_to_site_admin = (isset($options['poll_send_mail_to_site_admin']) && $options['poll_send_mail_to_site_admin'] == 'on') ? true : false;

            // Allow Add Answer
            $allow_multi_vote = isset($options["allow_multivote"]) && $options["allow_multivote"] == "on" ? true : false; 
			$allow_add_answer = isset($options["user_add_answer"]) && $options["user_add_answer"] == 1 ? true : false;
			$check_admin_approval = false;
			$flag_for_added_answer = false;
            
			if($allow_add_answer && (isset($_POST['ays_poll_new_answer']) && $_POST['ays_poll_new_answer'] != "")){
				$flag_for_added_answer = true;
				$poll_allow_answer_require = isset($options['add_answer_show_up']) && $options['add_answer_show_up'] == 1 ? true : false;
				if($poll_allow_answer_require){
					$check_admin_approval = true;
				}
				$new_anwer_data = array(
					'poll_id'       => $poll_id,
					'new_answer'    => sanitize_text_field($_POST['ays_poll_new_answer']),
					'admin_require' => $poll_allow_answer_require,
					'answers_count' => $poll_answers_count,
					'if_text_type'  => false
				);
				
				$added_answer_id = $this->ays_add_answer_poll_new($new_anwer_data);
				if((is_array($answer_id) && !empty($answer_id)) && $allow_multi_vote){
					$answer_id[] = $added_answer_id['new_id'];
				}
				elseif(isset($answer_id) && !is_array($answer_id) && $answer_id > 0  && $allow_multi_vote){						
					$answer_id = explode(" " , $answer_id);
					array_push($answer_id , $added_answer_id['new_id']);
				}
				else{
					$answer_id = array_values($added_answer_id);
				}
			}

            $poll_type_for_text_type = isset($poll['type']) && $poll['type'] == "text" ? true : false; 
			if($poll_type_for_text_type){
				$text_anwer_data = array(
					'poll_id'       => $poll_id,
					'new_answer'    => isset($_POST['answer']) && $_POST['answer'] != '' ? sanitize_text_field($_POST['answer']) : "",
					'admin_require' => false,
					'answers_count' => $poll_answers_count,
                    'if_text_type'  => true
				);
				
				$added_answer_id = $this->ays_add_answer_poll_new($text_anwer_data);
				$answer_id = $added_answer_id['new_id'];
                
			}
            

            //---- Email configuration Start  ---- //

            $nsite_url_base = parse_url( get_site_url(), PHP_URL_HOST );
            $nsite_url = trim( $nsite_url_base, '/' );
            
            //$nsite_url = "levon.com";
            $nno_reply = "noreply@".$nsite_url;


            if( isset( $options[ 'poll_email_configuration_from_name' ] ) ) {
                $uname = stripslashes( $options[ 'poll_email_configuration_from_name' ] );
            } else {
                $uname = 'Poll Maker';
            }
            
            if( isset( $options[ 'poll_email_configuration_from_email' ] ) && !empty( $options[ 'poll_email_configuration_from_email' ] ) && filter_var( $options[ 'poll_email_configuration_from_email' ], FILTER_VALIDATE_EMAIL ) ) {
                $nfrom = "From: " . $uname . " <".stripslashes( $options[ 'poll_email_configuration_from_email' ] ).">";
            }else{
                $nfrom = "From: " . $uname . " <poll_maker@".$nsite_url.">";
            }

            if( isset( $options[ 'poll_email_configuration_from_subject' ] ) ) {
                $subject = stripslashes( $options[ 'poll_email_configuration_from_subject' ] );
            } else {
                $subject = $poll_title;
            }
            
            if( isset( $options[ 'poll_email_configuration_replyto_name' ] ) ) {
                $replyto_name = stripslashes( $options[ 'poll_email_configuration_replyto_name' ] );
            } else {
                $replyto_name = '';
            }

            $nreply = "";
            if( isset( $options[ 'poll_email_configuration_replyto_email' ] ) ) {
                if( !empty( $options[ 'poll_email_configuration_replyto_email' ] ) && filter_var( $options[ 'poll_email_configuration_replyto_email' ], FILTER_VALIDATE_EMAIL ) ){
                    $nreply = "Reply-To: " . $replyto_name . " <" . stripslashes( $options[ 'poll_email_configuration_replyto_email' ] ) . ">";
                }
            }

            //---- Email configuration End ---- //

            if ( isset($_POST['answer']) && isset($options['limit_users']) && $options['limit_users'] == 1) {
                //poll vote limitation
                $enable_vote_limitation  = (isset($options['enable_vote_limitation']) && $options['enable_vote_limitation'] == 'on') ? true : false;
                $ays_vote_limitation     = (isset($options['vote_limitation']) && $options['vote_limitation'] != '') ? $options['vote_limitation'] : '';
                $ays_vote_limitation_time_period = (isset($options['limitation_time_period']) && $options['limitation_time_period'] != '') ? $options['limitation_time_period'] : '';
                $cookie_name  = 'ays_vote_limitation_cookie_name_'.$poll_id;
                $is_in_limit_period = false;
                $vote_limitation_time_method = false;
                $cookie_value = "";
                $cookie_expiration = 0;
                if($enable_vote_limitation){
                    $is_in_limit_period = true;
                    $cookie_value = 'ays_vote_limitation_cookie_value';
                    switch($ays_vote_limitation_time_period) {
                        case "minute":
                            $vote_limitation_time_method = "MINUTE";
                            $cookie_expiration = time() + (60 * $ays_vote_limitation);
                            break;
                        case "hour":
                            $vote_limitation_time_method = "HOUR";
                            $cookie_expiration = time() + (3600 * $ays_vote_limitation);
                            break;
                        case "day":
                            $vote_limitation_time_method = "DAY";
                            $cookie_expiration = time() + (864 * 10^2 * $ays_vote_limitation);
                            break;
                        case "week":
                            $vote_limitation_time_method = "WEEK";
                            $cookie_expiration = time() + (6048 * 10^2 * $ays_vote_limitation);
                            break;
                        case "month":
                            $vote_limitation_time_method = "MONTH";
                            $cookie_expiration = time() + (2592 * 10^3 * $ays_vote_limitation);
                            break;
                        default:
                            $vote_limitation_time_method = "MINUTE";
                            $cookie_expiration = time() + (60 * $ays_vote_limitation);
                    }
                }
                $user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
                $limit_users_method = isset($options['limit_users_method']) ? sanitize_text_field($options['limit_users_method']) : 'ip';
                $attempts_count = (isset($options['attempts_count']) && $options['attempts_count'] != '') ? absint(intval($options['attempts_count'])) : 1;
                $user_voted_count = 0;

                $limit_users_attr = array(
                    'id' => $poll_id,
                    'name' => 'ays_this_poll_cookie_',
                    'title' => $poll_title,
                );

                switch ( $limit_users_method ) {
                    case 'ip':
                        $user_voted_count = $this->ays_poll_get_limit_user_count_by_ip($poll_id, $ays_vote_limitation, $vote_limitation_time_method);
                        break;
                    case 'user':
                        if ($user_id != 0) {
                            $user_voted_count = $this->ays_poll_get_limit_user_count_by_id($poll_id,$user_id, $ays_vote_limitation, $vote_limitation_time_method);
                        }
                        break;
                    case 'cookie':
                        $user_voted_count = $this->get_limit_cookie_count( $limit_users_attr );
                        if( $attempts_count > $user_voted_count){
                            $limit_users_attr['increase_count'] = true;
                        }
                        $check_cookie = $this->ays_poll_check_cookie( $limit_users_attr );
                        if ( !$check_cookie ) {
                            $set_cookie = $this->ays_poll_set_cookie( $limit_users_attr );
                        }

                        if(!isset($_COOKIE['ays_vote_limitation_cookie_name_'.$poll_id]) && $enable_vote_limitation){
                            setcookie($cookie_name, $cookie_value, $cookie_expiration, '/');
                        }
                        break;
                    case 'cookie_ip':
                        $check_user_by_ip = $this->ays_poll_get_limit_user_count_by_ip($poll_id, $ays_vote_limitation, $vote_limitation_time_method);
                        $user_voted_count = $this->get_limit_cookie_count($limit_users_attr);
                        if ( $attempts_count > $user_voted_count) {
                            $limit_users_attr['increase_count'] = true;
                        } 
                        $check_cookie = $this->ays_poll_check_cookie( $limit_users_attr );
                        if ( !$check_cookie || $check_user_by_ip <= 0 ) {
                            if ( !$check_cookie ) {
                                $set_cookie = $this->ays_poll_set_cookie( $limit_users_attr );
                            }
                        }
                        if(!isset($_COOKIE['ays_vote_limitation_cookie_name_'.$poll_id]) && $enable_vote_limitation){
                            setcookie($cookie_name, $cookie_value, $cookie_expiration, '/');
                        }
                        break;
                    default:
                        if ($user_id != 0) {
                            $user_voted_count = $this->ays_poll_get_limit_user_count_by_id($poll_id,$user_id, $ays_vote_limitation, $vote_limitation_time_method);
                        }else{
                            $user_voted_count = $this->ays_poll_get_limit_user_count_by_ip($poll_id, $ays_vote_limitation, $vote_limitation_time_method);
                        }
                        break;
                }
                $user_voted_count = absint(intval(($user_voted_count)));

                if ( $user_voted_count + 1 > $attempts_count && !$is_in_limit_period) {
                    $res = $this->get_poll_by_id($poll_id);
                    $res['voted_status'] = false;
                    ob_end_clean();
                    $ob_get_clean = ob_get_clean();
                    echo json_encode($res);
                    wp_die();
                }
            }
            
			if (isset($options['info_form']) && $options['info_form'] == 1) {
				$fields = $poll['fields'];
				foreach ( $fields as $field ) {
					if ($field['slug'] == "apm-email") {
						continue;
					}
					if ($field['type'] == 'date') {
						$user_form[$field['name']] = isset($_POST["user-form-{$field['slug']}"]) ? date("d.m.Y", strtotime(wp_filter_post_kses($_POST["user-form-{$field['slug']}"]))) : "";
					}elseif ($field['type'] == 'checkbox') {
						$user_form[$field['name']] = isset($_POST[$field['slug']]) && $_POST[$field['slug']] == 'on' ? 'On' : 'Off';
					}else {
						$user_form[$field['name']] = isset($_POST["user-form-{$field['slug']}"]) ? wp_filter_post_kses($_POST["user-form-{$field['slug']}"]) : "";
					}
				}
            }
            
            $check_allowing = (isset($options['allow_collect_user_info']) && $options['allow_collect_user_info'] == 'on') ? true : false;
			$check_fields   = (isset($options['info_form']) && $options['info_form'] == 1) ? true : false;
			if($check_allowing && !$check_fields){
				$this_user = wp_get_current_user();
				if($this_user->ID != 0){
					$_POST["user-form-apm-email"] = $this_user->data->user_email;
                    $_REQUEST["user-form-apm-email"] = $this_user->data->user_email;
					$user_form['Name'] = $this_user->data->display_name;
				}                
            }


            //GamiPress
            if(in_array('gamipress/gamipress.php', apply_filters('active_plugins', get_option('active_plugins')))){ 
                do_action( 'ays_poll_before_save_entry' );
            }

			if (isset($_POST["user-form-apm-email"])) {
				$user_email = sanitize_email($_POST["user-form-apm-email"]);

				// MailChimp

                if (isset($options['enable_mailchimp']) && $options['enable_mailchimp'] == 'on') {
                    if (isset($options['mailchimp_list']) && $options['mailchimp_list'] != "") {

                        $poll_settings = $this->settings;
                        $mailchimp_res = ($poll_settings->ays_get_setting('mailchimp') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('mailchimp');
                        $mailchimp = json_decode($mailchimp_res, true);
                        $mailchimp_username = isset($mailchimp['username']) ? $mailchimp['username'] : '';
                        $mailchimp_api_key = isset($mailchimp['apiKey']) ? $mailchimp['apiKey'] : '';
                        $mailchimp_list = (isset($options['mailchimp_list'])) ? $options['mailchimp_list'] : '';
                        $mailchimp_email = $user_email;
                        $user_name = isset($_POST['user-form-apm-name']) ? explode(" ", wp_filter_post_kses($_POST['user-form-apm-name'])) : array();
                        $mailchimp_fname = (isset($user_name[0]) && $user_name[0] != "") ? $user_name[0] : "";
                        $mailchimp_lname = (isset($user_name[1]) && $user_name[1] != "") ? $user_name[1] : "";
                        if ($mailchimp_username != "" && $mailchimp_api_key != "") {
                            $args = array(
                                "email" => $mailchimp_email,
                                "fname" => $mailchimp_fname,
                                "lname" => $mailchimp_lname,
                            );
                            $mresult = $this->ays_add_mailchimp_transaction($mailchimp_username, $mailchimp_api_key, $mailchimp_list, $args);
                        }
                    }
                }

                // Campaign Monitor
                if (isset($options['enable_monitor']) && $options['enable_monitor'] == 'on' && $options['monitor_list'] != "" ) {
                    $poll_settings = $this->settings;
                    $monitor_res     = ($poll_settings->ays_get_setting('monitor') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('monitor');
                    $monitor         = json_decode($monitor_res, true);
                    $monitor_client  = isset($monitor['client']) ? $monitor['client'] : '';
                    $monitor_api_key = isset($monitor['apiKey']) ? $monitor['apiKey'] : '';
                    $monitor_list    = (isset($options['monitor_list'])) ? $options['monitor_list'] : '';
                    $monitor_email   = (isset($_REQUEST['user-form-apm-email']) && $_REQUEST['user-form-apm-email'] != "") ? sanitize_email($_REQUEST['user-form-apm-email']) : "";
                    $monitor_name    = sanitize_text_field($_REQUEST['user-form-apm-name']);
                    if ($monitor_client != "" && $monitor_api_key != "") {
                        $args    = array(
                            "EmailAddress" => $monitor_email,
                            "Name"         => $monitor_name,
                        );
                        $mresult = $this->ays_add_monitor_transaction($monitor_client, $monitor_api_key, $monitor_list, $args);
                    }
                }

                // ActiveCampaign
                if (isset($options['enable_active_camp']) && $options['enable_active_camp'] == "on") {
                    $poll_settings = $this->settings;
                    $active_camp_res = ($poll_settings->ays_get_setting('active_camp') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('active_camp');
                    $active_camp = json_decode($active_camp_res, true);
                    $active_camp_url = isset($active_camp['url']) ? $active_camp['url'] : '';
                    $active_camp_api_key = isset($active_camp['apiKey']) ? $active_camp['apiKey'] : '';
                    $active_camp_list = (isset($options['active_camp_list'])) ? $options['active_camp_list'] : '';
                    $active_camp_automation = (isset($options['active_camp_automation'])) ? $options['active_camp_automation'] : '';
                    $active_camp_email = (isset($_REQUEST['user-form-apm-email']) && $_REQUEST['user-form-apm-email'] != "") ? sanitize_email($_REQUEST['user-form-apm-email']) : "";
                    $user_name = explode(" ", $_REQUEST['user-form-apm-name']);
                    $active_camp_fname = (isset($user_name[0]) && $user_name[0] != "") ? $user_name[0] : "";
                    $active_camp_lname = (isset($user_name[1]) && $user_name[1] != "") ? $user_name[1] : "";
                    if ($active_camp_url != "" && $active_camp_api_key != "") {
                        $args    = array(
                            "email"     => $active_camp_email,
                            "firstName" => $active_camp_fname,
                            "lastName"  => $active_camp_lname,
                        );
                        $mresult = $this->ays_add_active_camp_transaction($active_camp_url, $active_camp_api_key, $args, $active_camp_list, $active_camp_automation);

                    }
                }

                // Zapier
                if (isset($options['enable_zapier']) && $options['enable_zapier'] == 'on' && $options['zapier_hook'] != "") {
                    $poll_settings = $this->settings;
                    $zapier_res = ($poll_settings->ays_get_setting('zapier') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('zapier');
                    $zapier = json_decode($zapier_res, true);
                    $zapier_hook = isset($zapier['hook']) ? $zapier['hook'] : '';
                    $zapier_data = array();
                    $zapier_data['E-mail'] = (isset($_REQUEST['user-form-apm-email']) && $_REQUEST['user-form-apm-email'] != "") ? sanitize_email($_REQUEST['user-form-apm-email']) : "";
                    $zapier_data['Name'] = isset($_REQUEST['user-form-apm-name']) ? sanitize_text_field($_REQUEST['user-form-apm-name']) : "";

                    foreach ($poll_settings as $key => $attr) {
                        if (array_key_exists($attr->slug, $_REQUEST) && $_REQUEST[$attr->slug] != "") {
                            $zapier_data[$attr->name] = sanitize_text_field($_REQUEST[$attr->slug]);
                        }
                    }
                    $zresult = $this->ays_add_zapier_transaction($zapier_hook, $zapier_data);
                }

                // Slack
                if ($options['enable_slack'] && $options['enable_slack'] =='on') {
                    $slack_res = ($poll_settings->ays_get_setting('slack') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('slack');
                    $slack = json_decode($slack_res, true);
                    $slack_conversation = (isset($options['slack_conversation'])) ? $options['slack_conversation'] : '';
                    $slack_token = isset($slack['token']) ? $slack['token'] : '';
                    $slack_data = array();

                    $slack_data['Name'] = isset($_REQUEST['user-form-apm-name']) ? sanitize_text_field($_REQUEST['user-form-apm-name']) : "";
                    $slack_data['E-mail'] = (isset($_REQUEST['user-form-apm-email']) && $_REQUEST['user-form-apm-email'] != "") ? sanitize_email($_REQUEST['user-form-apm-email']) : "";

                    foreach ($poll_settings as $key => $attr) {
                        if (array_key_exists($attr->slug, $_REQUEST) && $_REQUEST[$attr->slug] != "") {
                            $slack_data[$attr->name] = sanitize_text_field($_REQUEST[$attr->slug]);
                        }
                    }
                    if ($slack_token != "") {
                        $answer = $this->get_answer_by_id($answer_id);
                        $sresult = $this->ays_add_slack_transaction($slack_token, $slack_conversation, $slack_data, $poll['title']);
                    }
                }

                // Mad Mimi
                $enable_mad_mimi = (isset($options['enable_mad_mimi']) && $options['enable_mad_mimi'] == 'on') ? true : false;
                if ($enable_mad_mimi) {
                    $poll_settings = $this->settings;
                    $mad_mimi_res = ($poll_settings->ays_get_setting('mad_mimi') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('mad_mimi');
                    $mad_mimi     = json_decode($mad_mimi_res, true);
                    $mad_mimi_user_name = isset($mad_mimi['user_name']) ? $mad_mimi['user_name'] : '' ;
                    $mad_mimi_api_key   = isset($mad_mimi['api_key']) ? $mad_mimi['api_key'] : '' ;
                    
                    $mad_mimi_list   = (isset($options['mad_mimi_list'])) ? $options['mad_mimi_list'] : '';
                    $mad_mimi_email  = (isset($_POST['user-form-apm-email']) && $_POST['user-form-apm-email'] != "") ? sanitize_email($_POST['user-form-apm-email']) : "";
                    $user_name       = isset($user_form['Name']) ? explode(" ", $user_form['Name']) : array();
                    $mad_mimi_fname  = (isset($user_name[0]) && $user_name[0] != "") ? $user_name[0] : "";
                    $mad_mimi_lname  = (isset($user_name[1]) && $user_name[1] != "") ? $user_name[1] : "";

                    $mad_mimi_data   = array(
                        "mad_mimi_user_name" => $mad_mimi_user_name,
                        "api_key"            => $mad_mimi_api_key,
                        "list"               => $mad_mimi_list,
                        "user_email"         => $mad_mimi_email,
                        "user_first_name"    => $mad_mimi_fname,
                        "user_last_name"     => $mad_mimi_lname
                    );
                    $sresult = $this->ays_poll_add_mad_mimi_contact($mad_mimi_data);
                }
                //

                // GetResponse
                $enable_getResponse  = (isset($options['enable_getResponse']) && $options['enable_getResponse'] == 'on') ? true : false;
                if($enable_getResponse){
                    $poll_settings = $this->settings;
                    $getResponse_res = ($poll_settings->ays_get_setting('get_response') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('get_response');
                    $getResponse     = json_decode($getResponse_res, true);
                    $getResponse_list_id    = (isset($options['getResponse_list']) && $options['getResponse_list'] != '') ? $options['getResponse_list'] : "";
                    $getResponse_api_key    = isset($getResponse['api_key']) ? $getResponse['api_key'] : '';
                    $getResponse_new_email  = (isset($_POST['user-form-apm-email']) && $_POST['user-form-apm-email'] != "") ? sanitize_email($_POST['user-form-apm-email']) : "";
                    $getResponse_user_name  = isset($user_form['Name']) ? explode(" ", $user_form['Name']) : array();
                    $getResponse_fname      = (isset($getResponse_user_name[0]) && $getResponse_user_name[0] != "") ? $getResponse_user_name[0] : "";
                    $getResponse_lname      = (isset($getResponse_user_name[1]) && $getResponse_user_name[1] != "") ? $getResponse_user_name[1] : "";
                    
                    $getResponse_data = array(
                        "api_key" => $getResponse_api_key,
                        "list_id" => $getResponse_list_id,
                        "email"   => $getResponse_new_email,
                        "fname"   => $getResponse_fname,
                        "lname"   => $getResponse_lname,
                    );
                    $sresult = $this->ays_poll_add_getResponse_contact($getResponse_data);
                }

                // ConvertKit
                $enable_convertKit   = (isset($options['enable_convertKit']) && $options['enable_convertKit'] == 'on') ? true : false;
                if($enable_convertKit){
                    $covertKit_res       = ($poll_settings->ays_get_setting('convertKit') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('convertKit');
                    $covertKit           = json_decode($covertKit_res, true);
                    $convertKit_form_id  = (isset($options['poll_convertKit_form_id']) && $options['poll_convertKit_form_id'] != "") ? $options['poll_convertKit_form_id'] : '';
                    $convertKit_api_key  = isset($covertKit['api_key']) && $covertKit['api_key'] != "" ? $covertKit['api_key'] : '';
                    $convertKit_data     = array();

                    $covertKit_email = (isset($_POST['user-form-apm-email']) && $_POST['user-form-apm-email'] != "") ? sanitize_email($_POST['user-form-apm-email']) : "";
                    $covertKit_name  = isset($user_form['Name']) ? explode(" ", $user_form['Name']) : array();
                    $covertKit_fname = (isset($covertKit_name[0]) && $covertKit_name[0] != "") ? $covertKit_name[0] : "";
                    $covertKit_lname = (isset($covertKit_name[1]) && $covertKit_name[1] != "") ? $covertKit_name[1] : "";

                    $convertKit_data = array(
                        "api_key" => $convertKit_api_key,
                        "form_id" => $convertKit_form_id,
                        "email"   => $covertKit_email,
                        "fname"   => $covertKit_fname,
                        "lname"   => $covertKit_lname
                    );
                    $cresult = $this->ays_poll_convertKit_add_user($convertKit_data);
                }

            }

            // Google sheet 
            $google_res                 = ($this->settings->ays_get_setting('google_sheet') === false) ? json_encode(array()) : $this->settings->ays_get_setting('google_sheet');
            $google                     = json_decode($google_res, true);
            $enable_google              = (isset($options['enable_google_sheets']) && $options['enable_google_sheets'] == 'on') ? true : false;

            $sheet_id                   = (isset($options['spreadsheet_id']) && $options['spreadsheet_id'] != '') ? $options['spreadsheet_id'] : '';
            $google_token               = isset($google['token']) ? $google['token'] : '';
            $google_refresh_token       = isset($google['refresh_token']) ? $google['refresh_token'] : '';
            $google_client_id           = isset($google['client']) ? $google['client'] : '';
            $google_client_secret       = isset($google['secret']) ? $google['secret'] : '';
            $google_data = array(
                "refresh_token" => $google_refresh_token,
                "google_client" => $google_client_id,
                "google_secret" => $google_client_secret,
                "sheet_id"      => $sheet_id,
                "id"            => $poll_id,
                "answer_id"     => $answer_id
            );

            if ( $notify_email_on && !isset($_REQUEST['see_res_for_email'])) {

                $admin_email = get_option( 'admin_email' );

                if ( filter_var( $admin_email, FILTER_VALIDATE_EMAIL ) ) {

                    $use_answered = '';
                    if(isset($answer_titless) && !empty($answer_titless)){
                        $use_answered = implode(', ', $answer_titless);
                    }

                    $mail_text = 
                    sprintf( __( "Someone answer %s in your %s poll on %s.", $this->plugin_name ), 
                        $use_answered,
                        '"' . $poll_title . '"',
                        "<a href='" . home_url() . "' target='_blank'>" . home_url() . "</a>"
                    );

                    if ( $poll_send_mail_to_site_admin ) {
                        $sp_admin_email = "<$admin_email>";
                    }else{
                        $sp_admin_email = "";
                    }
                    
                    $add_emails_array = array();
                    if( $poll_send_mail_to_site_admin ){
                        $add_emails_array[] = $sp_admin_email;
                    }

                    $add_emails = "";
                    if( $notify_email != "" ) {

                        $additional_emails = explode(", ", $notify_email);

                        foreach($additional_emails as $key => $additional_email){
                            $add_emails_array[] = "<$additional_email>";
                        }
                    }
                    $add_emails = implode( ', ', $add_emails_array );
                    
                    $to = $add_emails;
                    $headers = $nfrom."\r\n";

                    if($nreply != ""){
                        $headers .= $nreply."\r\n";
                    }
                    $headers .= "MIME-Version: 1.0\r\n";
                    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
                    $attachment = array();

    				$ays_send_mail_to_admin = ( wp_mail($to, $subject, $mail_text, $headers, $attachment) ) ? true : false;
                }
			}


			// AV  Allow Anonymity
			$allow_anonymity = isset($options['allow_anonymity']) && $options['allow_anonymity'] == 1 ? true : false;
			if ($allow_anonymity) {
				$not_show_user_id = array('not_show_user_id' => 1);
				$user_form = array_merge($user_form,$not_show_user_id);
			}

			// AV  IP Storing
			global $wpdb;
			$settings_table = esc_sql($wpdb->prefix."ayspoll_settings");
			$key_meta = esc_sql('options');
			$sql_ip = "SELECT meta_value FROM ".$settings_table." WHERE meta_key = %s";
    		$res_ip = $wpdb->get_var(
                $wpdb->prepare( $sql_ip, $key_meta)
            );

    		$options_res = ($res_ip === false) ? json_encode(array()) : $res_ip;
			$option_res = json_decode($options_res, true);

            $user_location = '';

			if (isset($option_res['disable_ip_storing']) && $option_res['disable_ip_storing'] == 'on') {
				$user_ips = '';
			}else{
                $connection_url = "www.google.com";
                $connection_status = $this->ays_poll_is_connected( $connection_url );
                $user_ips = '';
                if ($connection_status) {
                    include_once( POLL_MAKER_ADMIN_PATH . '/partials/polls/actions/poll-maker-ays-countries.php' );
                    $user_ips = $allow_anonymity ? '' : $this->get_user_ip();
                    if($user_ips != ''){
                        $json    = json_decode(file_get_contents("http://ipinfo.io/{$user_ips}/json"));
                        $country_json = isset($json->country) && $json->country != '' ? $json->country : "";
                        $city    = isset($json->city) && $json->city != '' ? $json->city : "";
                        $country = '';
                        if(in_array($country_json,array_keys($countries))){
                            $countries_arr = array_values($countries[$country_json]);
                            $country = $countries_arr[1];
                        }
                        $user_location_arr = array($country,$city);
                        if($country == '' && $city == ''){
                            $user_location = '';
                        }else{
                            $user_location = implode(",", $user_location_arr);
                        }
                    }
                }
			}

			$user_ip = esc_sql($user_ips);
            
            if(!$poll_type_for_text_type){
                foreach ($answer_id as $answ_key => $answ_val) {
                    $answer = $this->get_answer_by_id($answ_val);
                    $votes  = isset($answer['votes']) && $answer['votes'] !== null ? $answer['votes'] : 0;
                    $votes++;

                    global $wpdb;
                    $wpdb->update(
                        "{$wpdb->prefix}ayspoll_answers",
                        array('votes' => $votes),
                        array('id' => $answ_val),
                        array('%d'), array('%d')
                    );
                }
            }
           
			if (isset($_POST['answer']) || (isset($_POST['ays_poll_new_answer']) && $_POST['ays_poll_new_answer'] != "")) {
                $vote_date = isset($_REQUEST['end_date']) ? esc_sql($_REQUEST['end_date']) : current_time( "Y-m-d H:i:s" );
                $poll_answer_id = '';
                $answer_value = '';
                if($poll['type'] == 'range'){
                    $answer_table = "{$wpdb->prefix}ayspoll_answers";
                    $answer_id_sql = 'SELECT id FROM '.$answer_table.' WHERE poll_id='.$poll['id'];
                    $answer_id_res = $wpdb->get_var($answer_id_sql);
                    $poll_answer_id = $answer_id_res;
                    $answer_value = $answer_id[0];
                }elseif($poll['type'] == 'text'){
                    $poll_answer_id = intval($answer_id);
                }
                else{
                    $poll_answer_id = $answer_id[0];
                    $answer_value = '';
                }

                $this_user_id = is_user_logged_in() ? wp_get_current_user()->ID : 0;
                if($allow_anonymity){
                    $this_user_id = 0;
                }

				$wpdb->insert(
					"{$wpdb->prefix}ayspoll_reports",
					array(
						'answer_id'  	  => $poll_answer_id,
						'user_ip'    	  => $user_ip,
						'user_id'    	  => $this_user_id,
						'vote_date'  	  => $vote_date,
						'user_email' 	  => $user_email,
						'other_info' 	  => sanitize_text_field(json_encode($user_form)),
						'multi_answer_id' => json_encode($multi_answer_id),
						'poll_id' 		  => $poll_id,
                        'country'         => $user_location,
                        'answer_value'    => $answer_value,
					),
					array(
                        '%d', // answer_id
                        '%s', // user_ip
                        '%s', // user_id
                        '%s', // vote_date
                        '%s', // user_email
                        '%s', // other_info
                        '%s', // multi_answer_id
                        '%d', // poll_id
                        '%s', // country
                        '%s', // answer_value
                    )
				);
			}
            $google_data['last_id'] = $wpdb->insert_id;

			if ($ays_enable_mail_user && !isset($_REQUEST['see_res_for_email'])) {

                switch ( $poll_send_mail_type ) {
                    case 'custom':
                        // Custom
                        $poll_user_information = Poll_Maker_Data::get_user_profile_data();
                        $user_first_name = (isset( $poll_user_information['user_first_name'] ) && $poll_user_information['user_first_name']  != "") ? $poll_user_information['user_first_name'] : '';	
                        $user_last_name  = (isset( $poll_user_information['user_last_name'] ) && $poll_user_information['user_last_name']  != "") ? $poll_user_information['user_last_name'] : '';
                        $creation_date   = (isset( $poll['styles']['create_date'] ) && $poll['styles']['create_date'] != '') ? $poll['styles']['create_date'] : '';
                        $user_answered_all = (isset( $answer_titless ) && !empty($answer_titless)) ? implode("," , $answer_titless) : '';
                        $message_data = array(
                            'poll_title'       => stripslashes($poll['title']),
                            'users_first_name' => $user_first_name,
                            'users_last_name' => $user_last_name,
                            'creation_date'    => $creation_date,
                            'user_answer'    => $user_answered_all,
                        );
                        
                        if(isset($_REQUEST["user-form-apm-email"]) && filter_var($_REQUEST['user-form-apm-email'], FILTER_VALIDATE_EMAIL)){
                            $message_content = '';
                            $message_content = $mail_usr_msg;
                            $message_data['user_email'] = $_REQUEST["user-form-apm-email"];
                            $message_content = $this->replace_message_variables($message_content, $message_data);
                            $message_content = $this->ays_autoembed( $message_content );

                            $email = sanitize_email( $_REQUEST["user-form-apm-email"] );

                            $headers = $nfrom."\r\n";

                            if($nreply != ""){
                                $headers .= $nreply."\r\n";
                            }
                            $headers    .= "MIME-Version: 1.0\r\n";
                            $headers    .= "Content-Type: text/html; charset=UTF-8\r\n";
                            $attachment  = array();

                            $ays_send_mail_to_user = ( wp_mail($email, $subject, $message_content, $headers, $attachment) ) ? true : false;
                        }

                        break;
                    case 'sendgrid':
                        // SendGrid
                        if(isset($_REQUEST["user-form-apm-email"]) && filter_var($_REQUEST['user-form-apm-email'], FILTER_VALIDATE_EMAIL)){
                            if ( $poll_sendgrid_template_id != "") {

                                $poll_settings = $this->settings;
                                $sendgrid_formfield = $this->get_all_formfields();
                                $poll_sendgrid_sub = array();

                                foreach ($sendgrid_formfield as $key => $sendgrid_field) {
                                    if($sendgrid_field['sendgrid'] != ''){
                                        $poll_sendgrid_sub["-".$sendgrid_field['sendgrid']."-"] = isset($_POST[ "user-form-" . $sendgrid_field['slug'] ]) ? sanitize_text_field( $_POST[ "user-form-" . $sendgrid_field['slug'] ] ) : '';
                                    }else{
                                        $poll_sendgrid_sub["-".$sendgrid_field['slug']."-"] = isset($_POST[ "user-form-" . $sendgrid_field['slug'] ]) ? sanitize_text_field( $_POST[ "user-form-" . $sendgrid_field['slug'] ] ) : ''    ;                               
                                    }
                                }
                                // General Settings Sendgrid
                                $sendgrig_res = ($poll_settings->ays_get_setting('sendgrid') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('sendgrid');
                                $sendgrid     = json_decode($sendgrig_res, true);

                                $poll_sendgrid_api_key   = (isset($sendgrid['apiKey'])) ? $sendgrid['apiKey'] : '';
                                $poll_sendgrid_user_name = (isset($_POST['user-form-apm-name'])) ? $_POST['user-form-apm-name'] : '';
                                $poll_sendgrid_email     = sanitize_email( $_POST["user-form-apm-email"] );
                                $poll_sendgrid_subject   = $poll_title;

                                $poll_sendgrid_reply_to_name   = $replyto_name;

                                $poll_sendgrid_reply_to_email  = '';
                                if( isset( $options[ 'poll_email_configuration_replyto_email' ] ) ) {
                                    if( !empty( $options[ 'poll_email_configuration_replyto_email' ] ) && filter_var( $options[ 'poll_email_configuration_replyto_email' ], FILTER_VALIDATE_EMAIL ) ){
                                        $poll_sendgrid_reply_to_email  = stripslashes( $options[ 'poll_email_configuration_replyto_email' ] );
                                    }
                                }

                                if ($poll_sendgrid_api_key != "") {
                                    $args = array(
                                        "email_from"    => $poll_sendgrid_email_from,
                                        "email_name"    => $poll_sendgrid_email_name,
                                        "email_to"      => $poll_sendgrid_email,
                                        "name"          => $poll_sendgrid_user_name,
                                        "subject"       => $poll_sendgrid_subject,
                                        "substitutions" => $poll_sendgrid_sub,
                                        "template"      => $poll_sendgrid_template_id,
                                        "reply_to_name" => $poll_sendgrid_reply_to_name,
                                        "reply_to_email"=> $poll_sendgrid_reply_to_email,
                                    );
                                    $sgresult = $this->ays_add_sendgrid_transaction($poll_sendgrid_api_key,$args);
                                }
                            }
                        }

                        break;
                    default:
                        break;
                }
			}

            if ($enable_google && $google_token != "") {
                $sresult = $this->ays_poll_add_google_sheets($google_data);
            }

            $res = $this->get_poll_by_id($poll_id);
            $res['voted_status'] = true;
            $res['mail_to_user'] = $ays_send_mail_to_user;
            $res['mail_to_admin'] = $ays_send_mail_to_admin;
            $check_user = false;
            $numbering_arr = array();
			$res['numbering'] = "none";
			if($show_answers_numbering != "none"){
				$answer_count = isset($res['answers']) && !empty($res['answers']) ? count($res['answers']) : false;
				if($answer_count){
					$numbering_arr = $this->ays_answer_numbering($show_answers_numbering , $answer_count);
					$res['numbering'] = $numbering_arr;
				}
			}

            // Added new by Aros task
            $result_sort_type = (isset($options['result_sort_type']) && $options['result_sort_type'] != '') ?  sanitize_text_field( $options['result_sort_type'] ) : "none";
			if ( $result_sort_type != "none" ) {
				$res_answers = $res['answers'];

				$final_votes_count = array();
				foreach ($res_answers as $key => $res_answer) {

					$u_votes = absint( sanitize_text_field( $res_answer['votes'] ) );
					$f_votes = absint( sanitize_text_field( $res_answer['fake_votes'] ) );

					$final_votes_count[ $res_answer['id'] ] = $u_votes + $f_votes;
				}

				switch ( $result_sort_type ) {
					case 'DESC':
						uasort($final_votes_count, function ($x, $y) {
						    if ($x === $y) {
						        return 0;
						    }
						    return $x > $y ? -1 : 1;
						});
						break;
					case 'ASC':
					default:
						uasort($final_votes_count, function ($x, $y) {
						    if ($x === $y) {
						        return 0;
						    }
						    return $x < $y ? -1 : 1;
						});
					break;
				}

				$final_votes_count_arr = array();
				foreach ($final_votes_count as $answer_id => $v_count) {

					foreach ($res_answers as $key => $res_answer) {

                        $res_answer['answer'] = stripslashes($res_answer['answer']);
						if ( $res_answer['id'] == $answer_id ) {
							$final_votes_count_arr[] = $res_answer;
						}
					}
				}

				$res['answers'] = $final_votes_count_arr;

			}

            if(isset($options['show_passed_users']) && $options['show_passed_users'] == 'on'){
                $check_user = true;
                $poll_avatar_user_count = isset($options['poll_show_passed_users_count']) && $options['poll_show_passed_users_count'] != "" ? $options['poll_show_passed_users_count'] : 3;
                $results_table = $wpdb->prefix."ayspoll_reports";
                $all_answers = isset($res['answers']) && !empty($res['answers']) ? $res['answers'] : array();
                $answer_ids = array();
                if(isset($all_answers) && !empty($all_answers)){
                    foreach($all_answers as $answer => $value){
                        $answer_ids[] = $value['id'];                   
                    }
                }
                $answer_ids = implode(',' , $answer_ids);
                $sql_users = "SELECT `user_id` , `answer_id`
                              FROM ".$results_table."
                              WHERE `answer_id` IN (".$answer_ids.")
                              GROUP BY user_id, answer_id
                              ORDER BY vote_date DESC";
                              $user_res = $wpdb->get_results($sql_users , ARRAY_A);

                $user_pic_args = array(
                    "class" => "ays-user-profile-pic"
                );

                $users_res_array = array();
                foreach($user_res as $ar){
                    // if( isset( $users_res_array[$ar['answer_id']] ) && count( $users_res_array[$ar['answer_id']] ) >= $poll_avatar_user_count ){
                    //     continue;
                    // }
                    $users_res_array[$ar['answer_id']][] = intval( $ar['user_id'] );
                }

                if(isset($all_answers) && !empty($all_answers)){        
                    foreach($all_answers as $key => $answer){
                        $user_answers = array();
                        if( array_key_exists( $answer['id'], $users_res_array ) ){
                            foreach($users_res_array[$answer['id']] as $res_key => $res_value){
                                if($res_value == 0){
                                    continue;
                                }                               
                                $user_avatars = get_avatar($res_value, 24, $default = '', $alt = '', $user_pic_args);
                                $user_avatars = isset($user_avatars) && $user_avatars ? $user_avatars : '' ;
                                $user_answers[] = "<div class='ays-users-profile-pics'>".$user_avatars."</div>";                                
                            }
                        }
                        $res['answers'][$key]['avatar'] = $user_answers;
                    }   
                }
                $res['check_user_pic'] = $check_user;
                $res['check_user_pic_count'] = $poll_avatar_user_count;
                $res['check_user_pic_url'] = POLL_MAKER_AYS_PUBLIC_URL.'/images/more.png';
                $res['check_user_pic_loader'] = POLL_MAKER_AYS_ADMIN_URL.'/images/loaders/tail-spin.svg';
            }
            $res['check_admin_approval'] = $check_admin_approval;
			ob_end_clean();
			$ob_get_clean = ob_get_clean();
			echo json_encode($res);
			wp_die();
		}
	}

    // === INTEGRATIONS start ===
    // Campaign Monitor
    public function ays_add_monitor_transaction( $client, $api_key, $list_id, $args ) {
        if ($client == "" || $api_key == "") {
            return false;
        }

        $default_options = array(
            "CustomFields" => array(
                array(
                    "Key"   => "from",
                    "Value" => $this->plugin_name
                ),
                array(
                    "Key"   => "date",
                    "Value" => date("Y/m/d")
                )
            ),

            "Resubscribe"                            => true,
            "RestartSubscriptionBasedAutoresponders" => true,
            "ConsentToTrack"                         => "Yes"
        );

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL            => "https://api.createsend.com/api/v3.2/subscribers/$list_id.json",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_USERPWD        => "$api_key:x",
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => json_encode(array_merge($args, $default_options)),
            CURLOPT_HTTPHEADER     => array(
                "Content-Type: application/json",
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);

        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return "cURL Error #: " . $err;
        } else {
            return $response;
        }
    }
    //
    // ActiveCampaign
    public function ays_add_active_camp_transaction( $url, $api_key, $args, $list_id, $automation_id, $data = "contact" ) {
        if ($url == "" || $api_key == "") {
            return false;
        }

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL            => "$url/api/3/{$data}s",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => json_encode(array("$data" => $args)),
            CURLOPT_HTTPHEADER     => array(
                "Content-Type: application/json",
                "cache-control: no-cache",
                "Api-Token: $api_key"
            ),
        ));

        $response = curl_exec($curl);

        $err = curl_error($curl);

        curl_close($curl);

        $res = $err ? array(
            'Code'       => 0,
            'cURL Error' => $err
        ) : json_decode($response, true)["$data"];

        if ($data == "contactList" || $data == "contactAutomation") {
            return $res;
        } else {
            if ($list_id) {
                $list_args = array(
                    "list"    => $list_id,
                    "contact" => $res['id'],
                    "status"  => 1
                );

                return $this->ays_add_active_camp_transaction($url, $api_key, $list_args, $list_id, $automation_id, 'contactList');
            }
            if ($automation_id) {
                $automation_args = array(
                    "automation" => $automation_id,
                    "contact"    => $res['id']
                );

                return $this->ays_add_active_camp_transaction($url, $api_key, $automation_args, $list_id, $automation_id, 'contactAutomation');
            }

            return $res;
        }

    }
    //
    // Zapier
    public function ays_add_zapier_transaction( $hook, $data ) {
        if ($hook == "") {
            return false;
        }

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL            => $hook,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => json_encode(array("AysPoll" => $data)),
            CURLOPT_HTTPHEADER     => array(
                "Content-Type: application/json",
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);

        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return "cURL Error #: " . $err;
        } else {
            return $response;
        }
    }
    //
    // Slack
    public function ays_add_slack_transaction( $token, $channel, $data, $poll = "") {
        if ($token == "" || $channel == "") {
            return false;
        }
        global $wpdb;

        $text = __($data['Name'] . " passed the `" . stripslashes($poll) . "` Poll ", $this->plugin_name) . "\n";
        foreach ( $data as $key => $value ) {
            if ( $value == "" ) {
                continue;
            }
            $text .= __(ucfirst($key) . ":", $this->plugin_name) . " `$value`\n";
        }
        $text .= home_url();
        $args = array(
            "channel"  => $channel,
            "text"     => $text,
            "username" => "Ays PollMaker"
        );

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL            => "https://slack.com/api/chat.postMessage",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => "",
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => json_encode($args),
            CURLOPT_HTTPHEADER     => array(
                "Content-Type: application/json",
                "Authorization: Bearer $token",
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);

        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return "cURL Error #: " . $err;
        } else {
            return $response;
        }
    }
    //
    // Google Sheets / Xcho / add values in sheet
    public function ays_poll_add_google_sheets($data) {
        global $wpdb;
        error_reporting(0);
        if(empty($data)){
            return false;
        }

        $poll_question = '';

        $user_ip     = '';
        $user_email  = '';
        $vote_date   = '';
        $user_name   = '';
        $vote_reason = '';
        $new_token   = '';
        $answer_name = '';

        $reports_table = $wpdb->prefix.'ayspoll_reports';

        $id = isset($data['id']) && $data['id'] != '' ? $data['id'] : null;
        $last_id = isset($data['last_id']) && $data['last_id'] != '' ? $data['last_id'] : null;

        if($id !== null){
            $get_this_poll = $this->get_poll_by_id($id);            
            $poll_question = isset($get_this_poll['question']) && $get_this_poll['question'] != '' ? strip_tags($get_this_poll['question']) : '';           
            $poll_options = isset($get_this_poll['styles']) && $get_this_poll['styles'] != '' ? $get_this_poll['styles'] : array();
            $answer_id = '';
            if(isset($_POST['answer']) && is_array($_POST['answer'])){
                $answer_id = implode(',' , $_POST['answer']);
                $answer_bulk_names = $this->get_answer_by_id_bulk($answer_id);
                $answer_name = $answer_bulk_names;
            }
            else if(isset($_POST['answer']) && !is_array($_POST['answer'])){
                $answer_id = isset($_POST['answer']) && $_POST['answer'] != '' ? $_POST['answer'] : '';
                $answer = $this->get_answer_by_id($answer_id);
                $answer_name = isset($answer['answer']) && $answer['answer'] != "" ? $answer['answer'] : ''; 
            }
            $sql = "SELECT * FROM ".$reports_table." WHERE id = ".$last_id;
            $reports = $wpdb->get_row($sql, ARRAY_A);

            $user_ip = isset($reports['user_ip']) && $reports['user_ip'] != '' ? $reports['user_ip'] : ''; 
            $user_email  = isset($reports['user_email']) && $reports['user_email'] != '' ? $reports['user_email'] : ''; 
            $vote_date   = isset($reports['vote_date']) && $reports['vote_date'] != '' ? $reports['vote_date'] : ''; 
            $other_info  = isset($reports['other_info']) ? json_decode($reports['other_info'], true) : array();
            $user_name   = isset($other_info['Name']) && $other_info['Name'] != '' ? $other_info['Name'] : '';  
            $vote_reason = isset($other_info['voteReason']) && $other_info['voteReason'] != '' ? $other_info['voteReason'] : '';
        }

        $refresh_token = isset($data['refresh_token']) && $data['refresh_token'] != '' ? $data['refresh_token'] : '';
        $client_id     = isset($data['google_client']) && $data['google_client'] != '' ? $data['google_client'] : '';
        $client_secret = isset($data['google_secret']) && $data['google_secret'] != '' ? $data['google_secret'] : '';
        $sheet_id      = isset($data['sheet_id']) && $data['sheet_id'] != '' ? $data['sheet_id'] : '';

        if($refresh_token != ''){
            $new_token = Poll_Maker_Ays_Admin::ays_poll_google_get_refresh_token($data);
        }

        $url = "https://sheets.googleapis.com/v4/spreadsheets/".$sheet_id."/values/A1:append?valueInputOption=RAW&insertDataOption=OVERWRITE&responseValueRenderOption=FORMATTED_VALUE&responseDateTimeRenderOption=SERIAL_NUMBER&access_token=". $new_token;

        $props = array(
            "range" => "A1",
            "majorDimension" => "ROWS",
            "values" => array(
                array(
                    $poll_question,
                    $answer_name,
                    $vote_date,
                    $user_ip,
                    $user_email,
                    $user_name,
                    $vote_reason
                )
            )
        );
        $properties = json_encode($props,true);
        
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $properties,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json"
            ),
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            return "cURL Error #: " . $err;
        } else {
            return $response;
        }
    }
    //
    // SendGrid / Xcho
    public function ays_add_sendgrid_transaction($api_key, $args){

        if( $api_key == '' ){
            return array(
                "Code" => 0
            );
        }
        $body = '';

        $fields = array(
            "personalizations" => array(
                array(
                    "to" => array(
                        array(
                            "email" => $args['email_to'],
                            "name"  => $args['name']
                        )
                    )
                )
            ),
            "from" => array(
                "email" => $args['email_from'],
                "name"  => $args['email_name']
            ),
            "subject" => $args['subject'],
            "content" => array(
                array(
                    "type"  => "text/html",
                    "value" => "<p></p>"
                )
            ),
            "dynamic_template_data" => $args['substitutions'],
            "template_id" => $args['template']
        );

        if ( ! empty( $args['reply_to_email'] ) ) {
            $fields['reply_to'] = array(
                "email" => $args['reply_to_email'],
                "name"  => $args['reply_to_name']
            );
        }


        $headers = array(
            'sslverify' => false,
            'body' => json_encode( $fields ),
            "headers" => array(
                "Content-Type"  => "application/json",
                "cache-control" => "no-cache",
                "Authorization" => "Bearer " . $api_key  
            )
        );

        $url = "https://api.sendgrid.com/v3/mail/send";

        $response = wp_remote_post($url, $headers);      
        $body     = wp_remote_retrieve_body( $response );

        return $body;

        // $curl = curl_init();

        // $fields = array(
        //     "personalizations" => array(
        //         array(
        //             "to" => array(
        //                 array(
        //                     "email" => $args['email_to'],
        //                     "name"  => $args['name']
        //                 )
        //             )
        //         )
        //     ),
        //     "from" => array(
        //         "email" => $args['email_from'],
        //         "name"  => $args['email_name']
        //     ),
        //     "subject" => $args['subject'],
        //     "content" => array(
        //         array(
        //             "type" => "text/html",
        //             "value"  => "<p></p>"
        //         )
        //     ),
        //     "dynamic_template_data" => $args['substitutions'],
        //     "template_id" => $args['template']
        // );

        // if ( ! empty( $args['reply_to_email'] ) ) {
        //     $fields['reply_to'] = array(
        //         "email" => $args['reply_to_email'],
        //         "name"  => $args['reply_to_name']
        //     );
        // }

        // $sendgrid_field = json_encode($fields);
        
        // $api_url = "https://api.sendgrid.com/v3/mail/send";
        // $curl = curl_init();

        // curl_setopt_array($curl, array(
        //   CURLOPT_URL => $api_url,
        //   CURLOPT_RETURNTRANSFER => true,
        //   CURLOPT_ENCODING => "",
        //   CURLOPT_MAXREDIRS => 10,
        //   CURLOPT_TIMEOUT => 0,
        //   CURLOPT_FOLLOWLOCATION => true,
        //   CURLOPT_SSL_VERIFYPEER => false,
        //   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        //   CURLOPT_CUSTOMREQUEST => "POST",
        //   CURLOPT_POSTFIELDS => $sendgrid_field,
        //   CURLOPT_HTTPHEADER => array(
        //     "Content-Type: application/json",
        //     "Authorization: Bearer ".$api_key
        //   ),
        // ));

        // $response = curl_exec($curl);

        // $err = curl_error($curl);

        // curl_close($curl);

        // if ($err) {
        //     return "cURL Error #: " . $err;
        // } else {
        //     return $response;
        // }
    }
    //
    // Mailchimp
    public function ays_add_mailchimp_transaction( $username, $api_key, $list_id, $args ) {

		$email = isset($args['email']) ? $args['email'] : null;
		$fname = isset($args['fname']) ? $args['fname'] : "";
		$lname = isset($args['lname']) ? $args['lname'] : "";

		$api_prefix = explode("-", $api_key)[1];

		$fields = array(
			"email_address" => $email,
			"status"        => "subscribed",
			"merge_fields"  => array(
				"FNAME" => $fname,
				"LNAME" => $lname
			)
		);
		$curl   = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL            => "https://" . $api_prefix . ".api.mailchimp.com/3.0/lists/" . $list_id . "/members/",
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING       => "",
			CURLOPT_MAXREDIRS      => 10,
			CURLOPT_TIMEOUT        => 30,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
			CURLOPT_USERPWD        => "$username:$api_key",
			CURLOPT_CUSTOMREQUEST  => "POST",
			CURLOPT_POSTFIELDS     => json_encode($fields),
			CURLOPT_HTTPHEADER     => array(
				"Content-Type: application/json",
				"cache-control: no-cache"
			),
		));

		$response = curl_exec($curl);

		$err = curl_error($curl);

		curl_close($curl);

		if ($err) {
			return "cURL Error #: " . $err;
		} else {
			return $response;
		}
	}
    //
    // Mad mimi 
    public function ays_poll_add_mad_mimi_contact($data){
        if(empty($data)){
            return false;
        }

        $mad_mimi_user_name = isset($data['mad_mimi_user_name']) && $data['mad_mimi_user_name'] != "" ? $data['mad_mimi_user_name'] : ""; 
        $api_key            = isset($data['api_key']) && $data['api_key'] != "" ? $data['api_key'] : ""; 
        $list               = isset($data['list']) && $data['list'] != "" ? $data['list'] : ""; 
        $user_email         = isset($data['user_email']) && $data['user_email'] != "" ? $data['user_email'] : "";
        $user_first_name    = isset($data['user_first_name']) && $data['user_first_name'] != "" ? $data['user_first_name'] : "";
        $user_last_name     = isset($data['user_last_name']) && $data['user_last_name'] != "" ? $data['user_last_name'] : "";

        if($mad_mimi_user_name == "" || $api_key == "" || $list == ""){
            return false;
        }

        $url = "https://api.madmimi.com/audience_lists/".$list."/add?";

        $data = array(
            "username"   => $mad_mimi_user_name,
            "api_key"    => $api_key,
            "email"      => $user_email,
            "first_name" => $user_first_name,
            "last_name"  => $user_last_name
        );

        $url .= http_build_query($data);

        $headers = array(
            "headers" => array(
                "Accept"  => "application/json",
                )
        );
        
        $api_call = wp_remote_post( $url , $headers);
        if(wp_remote_retrieve_response_code( $api_call ) == 200){
            $result = wp_remote_retrieve_body($api_call);
            return $result;
        }
        else{
            return false;
        }
    }
    //
    // Get Response
    public function ays_poll_add_getResponse_contact($data){
        if(empty($data)){
            return false;
        }

        $api_key = isset($data['api_key']) && $data['api_key'] != "" ? $data['api_key'] : "";
        $list_id = isset($data['list_id']) && $data['list_id'] != "" ? $data['list_id'] : "";
        if($api_key == "" || $list_id == ""){
            return false;
        }
        $user_email = isset($data['email']) && $data['email'] != "" ? $data['email'] : "";
        $user_fname = isset($data['fname']) && $data['fname'] != "" ? $data['fname'] : "";
        $user_lname = isset($data['lname']) && $data['lname'] != "" ? $data['lname'] : "";

        $url = "https://api.getresponse.com/v3/contacts";
        $headers = array(
            "headers" => array(
                "X-Auth-Token" => "api-key ".$api_key
            ),
            "body"    => array(
                "name" => $user_fname." ".$user_lname,
                "campaign" => array(
                    "campaignId" => $list_id
                ),
                "email" => $user_email
            )
        );
        $api_call = wp_remote_post($url , $headers);
        
        $response = wp_remote_retrieve_body($api_call);
        if(wp_remote_retrieve_response_code($api_call) != 200){
            return false;
        }
    }
    //
    // ConvertKit
    public function ays_poll_convertKit_add_user($data) {
        if (empty($data)) {
            return false;
        }

        $api_key = isset($data['api_key']) && $data['api_key'] != '' ? $data['api_key'] : '';
        $convertKit_fname   = (isset($data['fname']) && $data['fname'] != "") ? $data['fname'] : "";
        $convertKit_lname   = (isset($data['lname']) && $data['lname'] != "") ? $data['lname'] : "";
        $convertKit_email   = (isset($data['email']) && $data['email'] != "") ? $data['email'] : "";
        $convertKit_form_id = (isset($data['form_id']) && $data['form_id'] != "") ? $data['form_id'] : "";
        
        if($api_key == "" || $convertKit_form_id == "" || $convertKit_email == ""){
            return false;
        }

        $url = "https://api.convertkit.com/v3/forms/".$convertKit_form_id."/subscribe?";
        $url .= http_build_query(array(        
                "email"      => $convertKit_email,
                "api_key"    => $api_key,
                "first_name" => $convertKit_fname
            )
        );

        $api_call = wp_remote_post($url);
    }
    //
    // === INTEGRATIONS end ===

	private function get_answer_by_id( $id ) {
		global $wpdb;
		$sql = "SELECT * FROM {$wpdb->prefix}ayspoll_answers
                WHERE id = " . absint($id) . "
                GROUP BY id";
		return $wpdb->get_row($sql, 'ARRAY_A');
    }

    public static function get_answer_by_ids( $ids ) {
		global $wpdb;
		$sql = "SELECT * FROM {$wpdb->prefix}ayspoll_answers
                WHERE id IN (".$ids.")";
		return $wpdb->get_results($sql, 'ARRAY_A');
    }

    private function get_answer_by_id_bulk( $ids ) {
        global $wpdb;
        $sql = "SELECT * FROM {$wpdb->prefix}ayspoll_answers
                WHERE id IN (".$ids.")";
        $results =  $wpdb->get_results($sql, 'ARRAY_A');
        $answer_names = array();
        foreach ($results as $key => $value) {
            $answer_names[] = isset($value['answer']) && $value['answer'] != '' ? $value['answer'] : '';
            
        }
        $answer_name = implode(',' , $answer_names);
        return $answer_name;
    }

	private static function get_poll_tackers_count($id){
        global $wpdb;

        $sql = "SELECT COUNT(*)
                FROM {$wpdb->prefix}ayspoll_reports
                WHERE poll_id=" . $id;

        $count = intval($wpdb->get_var($sql));

        return $count;
    }

    public function ays_poll_get_limit_user_count_by_id($poll_id, $user_id, $time, $method){
        global $wpdb;
        $where_conditon = "";
        if($time && $method){
            // $where_conditon = "AND `vote_date` BETWEEN DATE_ADD(NOW(), INTERVAL -".($time)." ".$method.") AND NOW()";
            // $where_conditon = " AND `vote_date` BETWEEN DATE_SUB('" . current_time( 'mysql' ) . "', INTERVAL ".($time)." ".$method.") AND '". current_time( 'mysql' ) ."'";
            $where_conditon = " AND `vote_date` BETWEEN DATE_SUB(NOW(), INTERVAL ".($time)." ".$method.") AND NOW()";
        }
        $sql = "SELECT COUNT(*)
                FROM `{$wpdb->prefix}ayspoll_reports`
                WHERE `user_id` = $user_id
                  AND `poll_id` = $poll_id ".$where_conditon;
        $result = intval($wpdb->get_var($sql));
        return $result;
    }

    public function ays_poll_get_limit_user_count_by_ip($id, $time, $method){
        global $wpdb;
        $user_ip = self::get_user_ip();
        $where_conditon = "";
        if($time && $method){
            // $where_conditon = "AND `vote_date` BETWEEN DATE_ADD(NOW(), INTERVAL -".($time)." ".$method.") AND NOW()";
            // $where_conditon = " AND `vote_date` BETWEEN DATE_SUB('" . current_time( 'mysql' ) . "', INTERVAL ".($time)." ".$method.") AND '". current_time( 'mysql' ) ."'";
            $where_conditon = " AND `vote_date` BETWEEN DATE_SUB(NOW(), INTERVAL ".($time)." ".$method.") AND NOW()";
        }
        $sql = "SELECT COUNT(*)
                FROM `{$wpdb->prefix}ayspoll_reports`
                WHERE `user_ip` = '$user_ip'
                  AND `poll_id` = $id ".$where_conditon;
        $result = $wpdb->get_var($sql);
        return $result;
    }

    public function ays_poll_set_cookie($attr){
        $cookie_name = $attr['name'].$attr['id'];
        $cookie_value = $attr['title'];
        $cookie_value = isset( $attr['attempts_count'] ) ? $attr['attempts_count'] : 1;
        $this->ays_poll_remove_cookie( $attr );
        $cookie_expiration =  time() + (1 * 365 * 24 * 60 * 60);
        setcookie($cookie_name, $cookie_value, $cookie_expiration, '/');
    }

    public function ays_poll_remove_cookie($attr){
        $cookie_name = $attr['name'].$attr['id'];
        if(isset($_COOKIE[$cookie_name])){
            unset($_COOKIE[$cookie_name]);
            $cookie_expiration =  time() - 1;
            setcookie($cookie_name, null, $cookie_expiration, '/');
        }
    }

    public function ays_poll_check_cookie($attr){
        $cookie_name = $attr['name'].$attr['id'];
        if(isset($_COOKIE[$cookie_name])){
            if( isset( $attr['increase_count'] ) && $attr['increase_count'] == true ){
                $attr['attempts_count'] = intval( $_COOKIE[$cookie_name] ) + 1;
                $this->ays_poll_set_cookie( $attr );
            }
            return true;
        }
        return false;
    }

    public function get_limit_cookie_count($attr){
        $cookie_name = $attr['name'].$attr['id'];
        if(isset($_COOKIE[$cookie_name])){
            return intval( $_COOKIE[ $cookie_name ] );
        }
        return false;
    }

    public static function ays_poll_is_connected( $url ){
        //website, port  (try 80 or 443)
        $connected = @fsockopen($url, 80);
        if ($connected){
            $is_conn = true; //action when connected
            fclose($connected);
        }else{
            $is_conn = false; //action in connection failure
        }
        return $is_conn;
    }

    public static function ays_get_fake_votes($id){
        global $wpdb;
        $answers_table = $wpdb->prefix."ayspoll_answers";
        $sql = "SELECT votes,fake_votes FROM ".$answers_table." WHERE poll_id =".$id;
        $results = $wpdb->get_results($sql , "ARRAY_A");
        return $results;
    }

    public function ays_poll_get_results($id) {

		global $wpdb;
		$content = '';
		$id = absint(intval($id));
		$answ_table = esc_sql($wpdb->prefix."ayspoll_answers");
		$polls_table = esc_sql($wpdb->prefix."ayspoll_polls");
        $votes_count = $this->get_poll_results_count_by_id($id);
        $poll = $this->get_poll_by_id($id);
        $polls_options = isset($poll['styles']) ? $poll['styles'] : array();
        $poll_order_by = isset($polls_options['result_sort_type']) && $polls_options['result_sort_type'] != 'none' ?  "ORDER BY votes ".$polls_options['result_sort_type'] : "";
		$ans_sql  = "SELECT * FROM ".$answ_table." WHERE poll_id =%d ".$poll_order_by;
		$poll_answers = $wpdb->get_results(
			   	  	$wpdb->prepare( $ans_sql, $id),
			   	  	'ARRAY_A'
				  );

		$poll_sql  = "SELECT * FROM ".$polls_table." WHERE id =%d";
		$polls = $wpdb->get_row(
			   	  	$wpdb->prepare( $poll_sql, $id),
			   	  	'ARRAY_A'
				  );

		if ($polls == null) {
			$content = '<p style="text-align:center;">No ratings yet</p>';
		}else{
            $polls_options['fake_votes'] = isset( $polls_options['fake_votes'] ) ? sanitize_text_field( $polls_options['fake_votes'] ) : 'off';
            $enable_fake_votes = (isset($polls_options['fake_votes']) && $polls_options['fake_votes'] == 'on') ? true : false;

            if (intval($votes_count['res_count']) > 0) {
                if ( $enable_fake_votes ) {

                    $fake_votes_count = $this->ays_get_fake_votes($id);
                    $all_fake_votes_count = 0;
                    if(isset($fake_votes_count)){
                        foreach($fake_votes_count as $f_key => $_value){
                            $r_votes = intval($_value['votes']);
                            $f_votes = intval($_value['fake_votes']);
                            if($r_votes + $f_votes < 0){
                                $all_fake_votes_count += $r_votes;
                            }
                            else{
                                $all_fake_votes_count += ($f_votes + $r_votes);
                            }
                        }
                    }

                    if ( $all_fake_votes_count != 0 ) {
                        $one_percent = 100 / $all_fake_votes_count;
                    } else {
                        $one_percent = 100 / ( intval($votes_count['res_count']) );
                    }
                } else {
				    $one_percent = 100 / ( intval($votes_count['res_count']) );
                }
	        }else{
	        	$one_percent = 1;
			}
			
			$poll_show_answer_perc = isset($polls_options['show_res_percent']) && $polls_options['show_res_percent'] == 1 ? true : false;
			$poll_show_votes_count = isset($polls_options['show_votes_count']) && $polls_options['show_votes_count'] == 1 ? true : false;
			$poll_main_color = isset($polls_options['main_color']) && $polls_options['main_color'] != '' ? esc_attr($polls_options['main_color']) : '';
			$poll_bg_color = isset($polls_options['bg_color']) && $polls_options['bg_color'] != '' ? esc_attr($polls_options['bg_color']) : '';
            $poll_hide_result = isset($polls_options['hide_results']) && $polls_options['hide_results'] == 1 ? true : false;
			$poll_hide_result_message = isset($polls_options['hide_results_text']) && $polls_options['hide_results_text'] != "" ? wpautop($polls_options['hide_results_text']) : "";
            $perc_conta_hide_or_no = '';
            $poll_social_buttons   = isset($polls_options['show_social']) && $polls_options['show_social'] == 1 ? true : false;
            $poll_show_avatars     = isset($polls_options['show_passed_users']) && $polls_options['show_passed_users'] == "on" ? true : false;
            $poll_avatars_count = isset($polls_options['poll_show_passed_users_count']) && $polls_options['poll_show_passed_users_count'] != "" ? $polls_options['poll_show_passed_users_count'] : 3;
            $content .= '<div class="results-apm">';
            $poll_answers_count = count($poll_answers);
            if($poll_hide_result){
				$content .= "<div style='text-align:center;'>" . $poll_hide_result_message . "</div>";
			}
            else{
                if($poll_show_avatars){
					$results_table = $wpdb->prefix."ayspoll_reports";
					$answer_ids = array();
					if(isset($poll_answers) && !empty($poll_answers)){
						foreach($poll_answers as $answer => $value){
							$answer_ids[] = $value['id'];					
						}
					}
					$answer_ids = implode(',' , $answer_ids);
					$sql_users = "SELECT `user_id` , `answer_id`
								  FROM ".$results_table."
								  WHERE `answer_id` IN (".$answer_ids.")
								  GROUP BY user_id, answer_id
								  ORDER BY vote_date DESC";
					$user_res = $wpdb->get_results($sql_users , ARRAY_A);
					$user_pic_args = array(
						"class" => "ays-user-profile-pic"
					);
					$users_res_array = array();
					foreach($user_res as $ar){
						$users_res_array[$ar['answer_id']][] = intval( $ar['user_id'] );
					}
	
					if(isset($poll_answers) && !empty($poll_answers)){		
						foreach($poll_answers as $key => $answer){
							$user_answers = array();
							if( array_key_exists( $answer['id'], $users_res_array ) ){
									$user_answers = $this->ays_poll_get_avatars($answer['id'] , $users_res_array);
							}
							$poll_answers[$key]['avatar'] = $user_answers;
						}	
					}
				}
                foreach ($poll_answers as $ans_key => $ans_val) {
                    $perc_cont = '';
                    $poll_avatars_content = "";
					$poll_user_avatars = "";
                    if(isset($ans_val["avatar"]) && !empty($ans_val["avatar"])){
						$x = array_splice($ans_val["avatar"] , 0 ,$poll_avatars_count);
						$poll_user_avatars = implode(" " , $x);

					}
					if($poll_show_avatars && $poll_user_avatars != ""){
						$poll_avatars_content = '<div class="ays-user-count">
													'.$poll_user_avatars.' 
													<div class="ays-users-profile-pics">
														<img src="'.POLL_MAKER_AYS_PUBLIC_URL.'/images/more.png" width="24" height="24" class="ays-user-image-more" data-answer-id='.$ans_val["id"].'>
													</div>
												</div>';
					}
                    $r_votes = (isset( $ans_val['votes'] ) && $ans_val['votes'] != '') ? intval($ans_val['votes']) : 0;
                    $f_votes = (isset( $ans_val['fake_votes'] ) && $ans_val['fake_votes'] != '') ? intval($ans_val['fake_votes']) : 0;
                    if ( $enable_fake_votes ) {
                        $all_votes = 0;
                        if($r_votes + $f_votes < 0){
                            $all_votes += $r_votes;
                        }
                        else{
                            $all_votes += ($f_votes + $r_votes);
                        }
                        $percent = round( $one_percent * intval($all_votes) );
                    } else {
                        $percent = round( $one_percent * intval($r_votes) );
                    }

                    if($poll_show_answer_perc){
                        if ($percent == 0) {
                            $perc_cont = '';
                            $perc_conta_hide_or_no = '';
                        }else{
                            $perc_cont = $percent.' %';
                            $perc_conta_hide_or_no = '('.$percent.'%'.')';
                        }

                    }
                    $answer_votes_count = '';
                    if($poll_show_votes_count){
                        $answer_votes_count = $r_votes;
                        if ( $enable_fake_votes ) {
                            $all_votes = 0;
                            if($r_votes + $f_votes < 0){
                                $all_votes += $r_votes;
                            }
                            else{
                                $all_votes += ($f_votes + $r_votes);
                            }
                            $answer_votes_count = $all_votes;
                        }
                    }
                    switch ($polls['type']) {
                        case 'choosing':
                            $content .= '<div class="answer-title flex-apm">
                                            <span class="answer-text">'.stripslashes($ans_val['answer']).'</span>
                                            <span class="answer-votes">'.$answer_votes_count.' '.$perc_conta_hide_or_no.'</span>
                                        </div>
                                        '.$poll_avatars_content.'
                                        <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$poll_main_color.'; color: '.$poll_bg_color.';">'.$perc_cont.'</div>';
                            break;

                        case 'rating':
                            switch ($polls['view_type']) {
                                case 'star':
                                    $star_type  = '';
                                    for ($i=0; $i < intval($ans_val['answer']); $i++) { 
                                        $star_type .= '<i class="ays_poll_far ays_poll_fa-star far"></i>';
                                    }
                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$star_type.'</span>
                                                    <span class="answer-votes">'.$answer_votes_count.' '.$perc_conta_hide_or_no.'</span>
                                                </div>
                                                '.$poll_avatars_content.'
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$poll_main_color.'; color: '.$poll_bg_color.';">'.$perc_cont.'</div>';
                                    break;
                                
                                case 'emoji':
                                    $emojy_type  = '';
                                    if ($poll_answers_count == 3) {
                                        switch (intval($ans_val['answer'])) {
                                            case 1:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-frown far"></i>';
                                                break;
                                            case 2:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-meh far"></i>';
                                                break;
                                            case 3:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-smile far"></i>';
                                                break;
                                            default:
                                                break;
                                        }
                                    }else{
                                        switch (intval($ans_val['answer'])) {
                                            case 1:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-tired far"></i>';
                                                break;
                                            case 2:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-frown far"></i>';
                                                break;
                                            case 3:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-meh far"></i>';
                                                break;
                                            case 4:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-smile far"></i>';
                                                break;
                                            case 5:
                                                $emojy_type .= '<i class="ays_poll_far ays_poll_fa-dizzy far"></i>';
                                                break;
                                            default:
                                                break;
                                        }
                                    }

                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$emojy_type.'</span>
                                                    <span class="answer-votes">'.$answer_votes_count.' '.$perc_conta_hide_or_no.'</span>
                                                </div>
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$poll_main_color.'; color: '.$poll_bg_color.';">'.$perc_cont.'</div>';

                                    break;
                                default:										
                                    break;
                            }
                            break;

                        case 'voting':
                            switch ($polls['view_type']) {
                                case 'hand':
                                    $hand_type  = '';
                                    if (intval($ans_val['answer'] == 1)) {
                                        $hand_type = '<i class="ays_poll_far ays_poll_fa-thumbs-up far"></i>';
                                    }else{
                                        $hand_type = '<i class="ays_poll_far ays_poll_fa-thumbs-down far"></i>';
                                    }
                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$hand_type.'</span>
                                                    <span class="answer-votes">'.$answer_votes_count.' '.$perc_conta_hide_or_no.'</span>
                                                </div>
                                                '.$poll_avatars_content.'
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$poll_main_color.'; color: '.$poll_bg_color.';">'.$perc_cont.'</div>';
                                    break;
                                
                                case 'emoji':
                                    $emojy_type  = '';
                                    if (intval($ans_val['answer'] == 1)) { 
                                        $emojy_type = '<i class="ays_poll_far ays_poll_fa-smile far"></i>';
                                    }else{
                                        $emojy_type = '<i class="ays_poll_far ays_poll_fa-frown far"></i>';
                                    }
                                    $content .= '<div class="answer-title flex-apm">
                                                    <span class="answer-text">'.$emojy_type.'</span>
                                                    <span class="answer-votes">'.$answer_votes_count.' '.$perc_conta_hide_or_no.'</span>
                                                </div>
                                                '.$poll_avatars_content.'
                                                <div class="answer-percent-res" style="width: '.$percent.'%; background-color: '.$poll_main_color.'; color: '.$poll_bg_color.';">'.$perc_cont.'</div>';

                                    break;
                                default:										
                                    break;
                            }
                            break;
                        default:										
                            break;
                    }
                    
                }
            }
            if($poll_social_buttons){
                $content .= "<div class='apm-social-btn' style='opacity: 1;'>";
                    $content .= "<a class='fb-share-button-res ays-share-btn ays-share-btn-branded ays-share-btn-facebook' title='Share on Facebook'>
                                    <span class='ays-share-btn-text'>Facebook</span>
                                </a>";
                    $content .= "<a class='twt-share-button-res ays-share-btn ays-share-btn-branded ays-share-btn-twitter' title='Share on Twitter'>
                                    <span class='ays-share-btn-text'>Twitter</span>
                                </a>";
                    $content .= "<a class='linkedin-share-button-res ays-share-btn ays-share-btn-branded ays-share-btn-linkedin' title='Share on LinkedIn'>
                                    <span class='ays-share-btn-text'>LinkedIn</span>
                                </a>";
			    $content .= '</div>';
            }
			$content .= '</div>';
		}
        return $content;
	}

    public function ays_answer_numbering($numbering , $count){
        $keyword_arr = array();
        switch ($numbering) {
            case '1.':
                $char_min_val = 1;
                for($x = $char_min_val; $x <= $count; $x++){
                    $keyword_arr[] = $x .".";
                }
                break;
            case '1)':
                $char_min_val = 1;
                for($x = $char_min_val; $x <= $count; $x++){
                    $keyword_arr[] = $x .")";
                }
                break;
            case 'A.':
                $columns = array();
					$keyword_arr = $this->ays_poll_generate_keyword_array($count);
					foreach($keyword_arr as $key => $value){
						$columns[] = $value . ".";
					}
					$keyword_arr = $columns;
                break;
            case 'A)':
					$columns = array();
					$keyword_arr = $this->ays_poll_generate_keyword_array($count);
					foreach($keyword_arr as $key => $value){
						$columns[] = $value . ")";
					}
					$keyword_arr = $columns;
                break;
            case 'a.':
                $columns = array();
					$keyword_arr = $this->ays_poll_generate_keyword_array($count);
					foreach($keyword_arr as $key => $value){
						$columns[] = strtolower($value) . ".";
					}
					$keyword_arr = $columns;
                break;
            case 'a)':
                $columns = array();
					$keyword_arr = $this->ays_poll_generate_keyword_array($count);
					foreach($keyword_arr as $key => $value){
						$columns[] = strtolower($value) . ")";
					}
					$keyword_arr = $columns;
                break;
            default:
                break;
        }
        return $keyword_arr;
	}

	public static function ays_poll_generate_keyword_array( $max_val ) {
        if (is_null($max_val) || $max_val == '') {
            $max_val = 6; //'F';
        }
        $max_val = absint(intval($max_val)) - 1;
        $keyword_arr = array();
        $letters = range('A', 'Z');
        if($max_val <= 25){
            $max_alpha_val = $letters[$max_val];
        }
        elseif($max_val > 25){
          $dividend = ($max_val + 1);
          $max_alpha_val = '';
          $modulo;
          while ($dividend > 0){
            $modulo = ($dividend - 1) % 26;
            $max_alpha_val = $letters[$modulo] . $max_alpha_val;
            $dividend = floor((($dividend - $modulo) / 26));
          }
        }
        $keyword_arr = self::ays_poll_create_columns_array( $max_alpha_val );
        return $keyword_arr;
    }

    public static function ays_poll_create_columns_array($end_column, $first_letters = '') {
        $columns = array();
        $letters = range('A', 'Z');
        $length = strlen($end_column);
        // Iterate over 26 letters.
        foreach ($letters as $letter) {
            // Paste the $first_letters before the next.
            $column = $first_letters . $letter;
            // Add the column to the final array.
            $columns[] = $column;
            // If it was the end column that was added, return the columns.
            if ($column == $end_column)
                return $columns;
        }
        // Add the column children.
        foreach ($columns as $column) {
            // Don't itterate if the $end_column was already set in a previous itteration.
            // Stop iterating if you've reached the maximum character length.
            if (!in_array($end_column, $columns) && strlen($column) < $length) {
              $new_columns = self::ays_poll_create_columns_array($end_column, $column);
              // Merge the new columns which were created with the final columns array.
              $columns = array_merge($columns, $new_columns);
            }
        }
        return $columns;
    }
    // Users avatars
	public function ays_poll_get_current_answer_users_pics(){
		global $wpdb;
		$results_table = $wpdb->prefix."ayspoll_reports";
		
		$answer_id = isset($_POST['answer_id']) && $_POST['answer_id'] != "" ? intval($_POST['answer_id']) : null;
		$user_answers = array();
		if(isset($answer_id)){
			$sql_users = "SELECT `user_id`
							FROM ".$results_table."
							WHERE `answer_id` = ".$answer_id."
							GROUP BY user_id, answer_id
							ORDER BY vote_date DESC";
							$user_res = $wpdb->get_results($sql_users , ARRAY_A);
			if(isset($user_res)){
				$user_pic_args = array(
					"class" => "ays-user-profile-pic-popup"
				);
				
				foreach($user_res as $key => $value){
					$user_id = isset($value['user_id']) && $value['user_id'] != "" ? intval($value['user_id']) : 0;
					if($user_id == 0){
						continue;
					}
					
					$user_avatars = get_avatar($user_id, 24, $default = '', $alt = '', $user_pic_args);
					$user_data = get_userdata($user_id);
					$user_name = "";
					if(isset($user_data)){
						if(isset($user_data->data)){
							$user_name = isset($user_data->data->display_name) && $user_data->data->display_name != "" ? esc_attr($user_data->data->display_name) : ""; 
						}
					}
					$user_avatars = isset($user_avatars) && $user_avatars ? $user_avatars : '';
					$user_answers[] = "<div class='ays-users-profile-pics-popup'><div>".$user_avatars."</div><div class='ays-users-profile-pics-popup-text'><span class='ays-poll-modal-names'>".$user_name."</span></div></div>";	
				}
			}
		}
		echo json_encode($user_answers);
		wp_die();
	}

    //Get User History Shortcode Data 
    public function ays_poll_user_history_shortcode_data(){
        global $wpdb;

        $current_user = wp_get_current_user();
        $id = $current_user->ID;
        if($id == 0){
            return null;
        }

        $ays_poll_report_table = $wpdb->prefix .'ayspoll_reports';
        $ays_poll_polls_table = $wpdb->prefix .'ayspoll_polls';
        $ays_poll_answer_table = $wpdb->prefix .'ayspoll_answers';
        $sql = "SELECT p.title, r.vote_date, a.answer
                        FROM {$ays_poll_report_table} AS r
                        LEFT JOIN {$ays_poll_polls_table} AS p
                        ON r.poll_id = p.id
                        LEFT JOIN {$ays_poll_answer_table} AS a
                        ON r.answer_id = a.id
                        WHERE r.user_id=$id
                        ORDER BY r.id DESC";

        $results = $wpdb->get_results($sql,'ARRAY_A');

        return $results;
    }

    public function ays_poll_user_page_history_html(){
        $results = $this->ays_poll_user_history_shortcode_data();

        $poll_settings = $this->settings;
        $poll_settings_options = ($poll_settings->ays_get_setting('options') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('options');
        $poll_set_option = json_decode($poll_settings_options, true);
        $options = $poll_set_option;

        $default_user_history_columns = array(
            'poll_name'  => 'poll_name',
            'vote_date'  => 'vote_date',
            'vote_answer'=> 'vote_answer',
        );
        
        $options['ays_poll_user_page_columns'] = !isset( $options['ays_poll_user_page_columns'] ) ? $default_user_history_columns : $options['ays_poll_user_page_columns'];
        $ays_poll_user_page_columns = (isset( $options['ays_poll_user_page_columns'] ) && !empty($options['ays_poll_user_page_columns']) ) ? $options['ays_poll_user_page_columns'] : array();
        $ays_poll_user_page_columns_order = (isset( $options['ays_poll_user_page_columns_order'] ) && !empty($options['ays_poll_user_page_columns_order']) ) ? $options['ays_poll_user_page_columns_order'] : $default_user_history_columns;

        $default_user_history_column_names = array(
            "poll_name"   => __( 'Poll name', $this->plugin_name ),
            "vote_date"   => __( 'Vote date', $this->plugin_name ),
            "vote_answer" => __( 'Vote answer', $this->plugin_name ),
        );

        $ays_default_header_value = array(
            "poll_name"   => "<th style='width:20%;'>" . __( "Poll Name", $this->plugin_name ) . "</th>",
            "vote_date"   => "<th style='width:17%;'>" . __( "Vote Date", $this->plugin_name ) . "</th>",
            "vote_answer" => "<th style='width:17%;'>" . __( "Vote Answer", $this->plugin_name ) . "</th>",
        );

        $user_page_history_html = "";

        if($results === null){
            $user_page_history_html .= "<p style='text-align: center;font-style:italic;'>" . __( "You must log in to see your results.", $this->plugin_name ) . "</p>";
            return $user_page_history_html;
        }
        
        $user_page_history_html = "<div class='ays-poll-user-history-results-container'>";
            $user_page_history_html .= "<table id='ays-poll-user-history-result-page'>";
                $user_page_history_html .= "<thead>";
                    $user_page_history_html .= "<tr>";
                        foreach ($ays_poll_user_page_columns_order as $key => $value) {
                            if (isset($ays_poll_user_page_columns[$value]) && $ays_poll_user_page_columns[$value] != '') {
                                $user_page_history_html .= $ays_default_header_value[$value];
                            }
                        }
                    $user_page_history_html .= "</tr>";
                $user_page_history_html .= "</thead>";
                $user_page_history_html .= "<tbody>";
                    foreach($results as $result){
                        $title       = (isset($result['title']) && $result['title'] != '') ? sanitize_text_field($result['title']) : "";
                        $vote_date   = (isset($result['vote_date']) && $result['vote_date'] != '') ? $result['vote_date'] : '';
                        $vote_answer = (isset($result['answer']) && $result['answer'] != '') ? stripslashes(sanitize_text_field($result['answer'])) : "";

                        $ays_default_html_order = array(
                            "poll_name"   => "<td class='ays-poll-name-column'>".$title."</td>",
                            "vote_date"   => "<td class='ays-poll-vote-date-column'>".$vote_date."</td>",
                            "vote_answer" => "<td class='ays-poll-vote-answer-column'>".$vote_answer."</td>",
                        );
                            
                        $user_page_history_html .= "<tr>";
                            foreach ($ays_poll_user_page_columns_order as $key => $value) {
                                if (isset($ays_poll_user_page_columns[$value]) && $ays_poll_user_page_columns[$value] != '') {
                                    $user_page_history_html .= $ays_default_html_order[$value];
                                }
                            }
                        $user_page_history_html .= "</tr>";
                    }
                $user_page_history_html .= "<tbody>";
            $user_page_history_html .= "</table>";
        $user_page_history_html .= "</div>";

        return $user_page_history_html;
    }

    //User History Shortcode
    public function ays_poll_user_history_method($attr){
        $this->enqueue_styles();
        $this->enqueue_scripts();
        $user_page_history_html = $this->ays_poll_user_page_history_html();
        return $user_page_history_html;
    }

    // Global Category Leaderboard Shortcode 
    public function ays_poll_category_gleaderboard_html($attr){
        global $wpdb;
       
        $id = (isset($attr['id'])) ? absint(intval($attr['id'])) : null;

        if (is_null($id)) {
            echo "<p class='wrong_shortcode_text' style='color:red;'>" . __('Wrong shortcode initialized', $this->plugin_name) . "</p>";
            return false;
        }

        $poll_settings = $this->settings;
        $category_leaderboard_res = ($poll_settings->ays_get_setting('category_leaderboard') === false) ? json_encode(array()) : $poll_settings->ays_get_setting('category_leaderboard');

        $category_leaderboard = json_decode($category_leaderboard_res, true);

        // User Count
        $ays_poll_cat_glob_leadboard_count = (isset($category_leaderboard['cat_global']['cat_count']) && $category_leaderboard['cat_global']['cat_count'] != '') ? $category_leaderboard['cat_global']['cat_count'] : '5' ;

        // Table width
        $ays_poll_cat_glob_leadboard_width = (isset($category_leaderboard['cat_global']['cat_width']) && $category_leaderboard['cat_global']['cat_width'] != '') ? $category_leaderboard['cat_global']['cat_width'] : '0' ;
        $ays_poll_cat_glob_leadboard_width   = intval($ays_poll_cat_glob_leadboard_width) == 0 ? '100%' : $ays_poll_cat_glob_leadboard_width ."px";

        //Order By
        $ays_poll_cat_glob_leadboard_orderby = (isset($category_leaderboard['cat_global']['cat_orderby']) && $category_leaderboard['cat_global']['cat_orderby'] != '') ? $category_leaderboard['cat_global']['cat_orderby'] : 'id' ;

        //Color
        $ays_poll_cat_glob_leadboard_color = (isset($category_leaderboard['cat_global']['cat_color']) && $category_leaderboard['cat_global']['cat_color'] != '') ? $category_leaderboard['cat_global']['cat_color'] : '#99BB5A' ;

        // Custom Css
        $ays_poll_cat_glob_leadboard_suctom_css = (isset($category_leaderboard['cat_global']['cat_gleadboard_custom_css']) && $category_leaderboard['cat_global']['cat_gleadboard_custom_css'] != '') ? $category_leaderboard['cat_global']['cat_gleadboard_custom_css'] : '';

        $default_cat_glob_leadboard_columns = array(
            'pos'      => 'pos',
            'name'     => 'name',
            'attempts' => 'attempts',
        );

        $default_cat_glob_leadboard_header_value = array(
            "pos"      => "<th class='ays_poll_glb_pos'>" . __( "Pos.", $this->plugin_name ) . "</th>",
            "name"     => "<th class='ays_poll_glb_user'>" . __( "Name", $this->plugin_name ) . "</th>",
            "attempts" => "<th class='ays_poll_glb_attempts'>" . __( "Attempts", $this->plugin_name ) . "</th>",
        );

        if($ays_poll_cat_glob_leadboard_orderby == 'id'){

            $sql = "SELECT r.user_id,COUNT(r.user_id) AS user_count,r.other_info 
                    FROM {$wpdb->prefix}ayspoll_reports AS r
                    LEFT JOIN {$wpdb->prefix}ayspoll_polls AS p
                    ON r.poll_id = p.id
                    WHERE r.user_id != 0
                    AND p.categories LIKE '%{$id}%'
                    GROUP BY r.user_id
                    ORDER BY COUNT(r.user_id) DESC
                    LIMIT ".$ays_poll_cat_glob_leadboard_count;

        }elseif($ays_poll_cat_glob_leadboard_orderby == 'email'){

            $sql = "SELECT r.user_id,COUNT(r.user_id) AS user_count,r.other_info 
                    FROM {$wpdb->prefix}ayspoll_reports AS r
                    LEFT JOIN {$wpdb->prefix}ayspoll_polls AS p
                    ON r.poll_id = p.id
                    WHERE !(r.user_email='' OR r.user_email IS NULL)
                    AND p.categories LIKE '%{$id}%'
                    GROUP BY r.user_email
                    ORDER BY COUNT(r.user_id) DESC
                    LIMIT ".$ays_poll_cat_glob_leadboard_count;
        }

        $result = $wpdb->get_results($sql, 'ARRAY_A');

        $c = 1;
        $content = '';

        $content .= '
        <style>
            '. $ays_poll_cat_glob_leadboard_suctom_css .'
        </style>';

        $content .= "<div class='ays_poll_glb_container'>
        <table class='ays_poll_glb_table' style='width: ".$ays_poll_cat_glob_leadboard_width.";'>
        	<thead>
            	<tr class='ays_poll_glb_li' style='background: ".$ays_poll_cat_glob_leadboard_color.";'>";
        foreach ($default_cat_glob_leadboard_header_value as $key => $value) {
            $content .= $value;
        }

        $content .="
        		</tr>
        	</thead>
        <tbody>";

        if (!empty($result)) {
            foreach ($result as $val) {
                $user_id = intval($val['user_id']);
                $attempts = (isset($val['user_count']) && $val['user_count'] != '') ? round(floatval($val['user_count']), 2) : '0';
                $options = (isset($val['other_info']) && $val['other_info'] != '') ? json_decode($val['other_info'],true) : array();

                if ($user_id == 0) {
                    $user_name = (isset($options['Name']) && $options['Name'] != '') ? $options['Name'] : __('Guest', $this->plugin_name);
                }else{
                    $user_name = (isset($options['Name']) && $options['Name'] != '') ? $options['Name'] : '';
                    if($user_name == ''){
                        $user = get_user_by('id', $user_id);
                        $user_name = $user->data->display_name ? $user->data->display_name : $user->user_login;
                    }
                }

                $ays_default_html_order = array(
                    "pos"  => "<td class='ays_poll_glb_pos'>".$c."</td>",
                    "name" => "<td class='ays_poll_glb_user'>".$user_name."</td>",
                    "attempts" => "<td class='ays_poll_glb_attempts'>".$attempts."</td>",
                );

                $content .= "<tr class='ays_poll_glb_li'>";
                foreach ($ays_default_html_order as $key => $value) {
                    $content .= $value;
                }

                $content .= "</tr>";
                $c++;
            }
        }

        $content .= "
        		</tbody>
        	</table>
        </div>";

        return $content;
    }

    public function ays_poll_generate_category_gleaderboard_list($attr){
        ob_start();
        $this->enqueue_styles();
        $this->enqueue_scripts();

        $content = $this->ays_poll_category_gleaderboard_html($attr);

        echo $content;

        return str_replace(array("\r\n", "\n", "\r"), '', ob_get_clean());
    }

    public static function ays_autoembed( $content ) {
        global $wp_embed;
        $content = stripslashes( wpautop( $content ) );
        $content = $wp_embed->autoembed( $content );
        if ( strpos( $content, '[embed]' ) !== false ) {
            $content = $wp_embed->run_shortcode( $content );
        }
        $content = do_shortcode( $content );
        return $content;
    }

    public function ays_poll_is_elementor(){
        if( isset( $_GET['action'] ) && $_GET['action'] == 'elementor' ){
            $is_elementor = true;
        }elseif( isset( $_REQUEST['elementor-preview'] ) && $_REQUEST['elementor-preview'] != '' ){
            $is_elementor = true;
        }else{
            $is_elementor = false;
        }
        return $is_elementor;
    }

    
	public function ays_poll_get_avatars($answer , $users){
		$user_answers = array();
		$user_pic_args = array(
			"class" => "ays-user-profile-pic"
		);
		foreach($users[$answer] as $res_key => $res_value){
			if($res_value == 0){
				continue;
			}
			$user_avatars = get_avatar($res_value, 24, $default = '', $alt = '', $user_pic_args);
			$user_avatars = isset($user_avatars) && $user_avatars ? $user_avatars : '' ;
			$user_answers[] = "<div class='ays-users-profile-pics'>".$user_avatars."</div>";								
		}
		return $user_answers;
	}

    public function ays_set_poll_fields_placeholders_texts(){

        /*
         * Get Poll fields placeholders from database
         */

        $settings_placeholders_texts = $this->settings->ays_get_setting('fields_placeholders');
        if($settings_placeholders_texts){
            $settings_placeholders_texts = json_decode($settings_placeholders_texts, true);
        }else{
            $settings_placeholders_texts = array();
        }

        $poll_fields_placeholder_name  = (isset($settings_placeholders_texts['poll_fields_placeholder_name']) && $settings_placeholders_texts['poll_fields_placeholder_name'] != '') ? stripslashes( esc_attr( $settings_placeholders_texts['poll_fields_placeholder_name'] ) ) : 'Name';

        $poll_fields_placeholder_email = (isset($settings_placeholders_texts['poll_fields_placeholder_email']) && $settings_placeholders_texts['poll_fields_placeholder_email'] != '') ? stripslashes( esc_attr( $settings_placeholders_texts['poll_fields_placeholder_email'] ) ) : 'E-mail';

		$poll_fields_placeholder_name_text  = $poll_fields_placeholder_name  === 'Name'  ? __('Name',  $this->plugin_name) : $poll_fields_placeholder_name;
		$poll_fields_placeholder_email_text = $poll_fields_placeholder_email === 'Email' ? __('Email', $this->plugin_name) : $poll_fields_placeholder_email;

        $texts = array(
            'namePlaceholder'       => $poll_fields_placeholder_name_text,
            'emailPlaceholder'      => $poll_fields_placeholder_email_text,
        );

        return $texts;
    }

    // ==== Shortcode for showing random or recent polls start ====
    public function ays_generate_display_polls_method($attr){
		$recent_poll_ids = $this->ays_recent_poll_ids($attr);
		$content = '<div class="ays_poll_recent_polls">';
		$polls = array();
        foreach ($recent_poll_ids as $key => $last_poll_id) {
            $poll_id = (isset($last_poll_id['id']) && intval($last_poll_id['id']) != '') ? intval($last_poll_id['id']) : '';
            $shortcode = '[ays_poll id="'.$poll_id.'"]';
            $polls[] = do_shortcode( $shortcode );
        }
        $content .= implode( '', $polls );
		$content .= '</div>';
		return str_replace(array("\r\n", "\n", "\r"), "\n", $content);
	}

	public function ays_recent_poll_ids($data){
		global $wpdb;
        $polls_table = $wpdb->prefix.'ayspoll_polls';

        $ays_recent_poll_order_by = (isset($data['orderby']) && $data['orderby'] != '') ? sanitize_text_field($data['orderby']) : "recent";
        $ays_recent_poll_count = (isset($data['count']) && $data['count'] != '') ? intval($data['count']) : 5;

        $last_polls_sql = "SELECT id FROM {$polls_table} WHERE styles LIKE '%\"published\":1%' ";

        switch ($ays_recent_poll_order_by) {
            case 'recent':
                $last_polls_sql .= "ORDER BY id DESC LIMIT ".$ays_recent_poll_count;
                break;
            case 'random':
                $last_polls_sql .= "ORDER BY RAND() LIMIT ".$ays_recent_poll_count;
                break;
            default:
                $last_polls_sql .= "ORDER BY id DESC LIMIT ".$ays_recent_poll_count;
                break;
        }

        $last_poll_ids = $wpdb->get_results($last_polls_sql,'ARRAY_A');

        return $last_poll_ids;
	}

    // ==== Shortcode for showing random or recent polls end ====

    public function replace_message_variables($content, $data){
        foreach($data as $variable => $value){
            $content = str_replace("%%".$variable."%%", $value, $content);
        }
        return $content;
    }

}

ZeroDay Forums Mini