<?php

namespace CHT\frontend;

use CHT\admin\CHT_Admin_Base;
use CHT\admin\CHT_Social_Icons;

if (!defined('ABSPATH')) {
    exit;
}

$admin_base = CHT_ADMIN_INC . '/class-admin-base.php';
require_once($admin_base);

$social_icons = CHT_ADMIN_INC . '/class-social-icons.php';
require_once($social_icons);

class CHT_Frontend extends CHT_Admin_Base
{
    public $widget_number;
    /**
     * CHT_Frontend constructor.
     */
    public function __construct()
    {
        $this->socials = CHT_Social_Icons::get_instance()->get_icons_list();
        if (wp_doing_ajax()) {
            add_action('wp_ajax_choose_social', array($this, 'choose_social_handler'));
            add_action('wp_ajax_get_chaty_settings', array($this, 'get_chaty_settings'));     // return setting for a social media in html
            
            add_action('wp_ajax_chaty_front_form_save_data', array($this, 'chaty_front_form_save_data'));
            add_action('wp_ajax_nopriv_chaty_front_form_save_data', array($this, 'chaty_front_form_save_data'));

	        add_action('wp_ajax_remove_chaty_widget', array($this, 'remove_chaty_widget'));     // remove social media widget
	        add_action('wp_ajax_change_chaty_widget_status', array($this, 'change_chaty_widget_status'));     // remove social media widget
        }

	    if(!isset($_GET['ct_builder'])) {
		    add_action( 'wp_enqueue_scripts', array( $this, 'cht_front_end_css_and_js' ), 0 );
	    }
    }

	public function remove_chaty_widget() {
		if (current_user_can('manage_options')) {
			$widget_index = filter_input(INPUT_POST, 'widget_index', FILTER_SANITIZE_STRING);
			$widget_nonce = filter_input(INPUT_POST, 'widget_nonce', FILTER_SANITIZE_STRING);
			if (isset($widget_index) && !empty($widget_index) && !empty($widget_nonce) && wp_verify_nonce($widget_nonce, "chaty_remove_" . $widget_index)) {

				$options = array(
					'mobile' => '1',
					'desktop' => '1',
				);
                delete_option("cht_active");
                delete_option("chaty_icons_view");
                delete_option("chaty_icons_view");
                delete_option("cht_cta_text_color");
                delete_option("cht_cta_bg_color");
                delete_option("cht_pending_messages");
                delete_option("cht_number_of_messages");
                delete_option("cht_number_color");
                delete_option("cht_number_bg_color");
                delete_option("cht_cta_switcher");
                delete_option("chaty_attention_effect");
                delete_option("chaty_default_state");
                delete_option("chaty_trigger_on_time");
                delete_option("chaty_trigger_time");
                delete_option("chaty_trigger_on_exit");
                delete_option("chaty_trigger_on_scroll");
                delete_option("chaty_trigger_on_page_scroll");
                delete_option("cht_close_button");
                delete_option("cht_close_button_text");
                delete_option("chaty_updated_on");

				foreach ($this->socials as $social) {
					delete_option('cht_social_' . $social['slug']);
				}

				update_option('cht_devices', $options);
				update_option('cht_position', 'right');
				update_option('cht_cta', 'Contact us');
				update_option('cht_numb_slug', ',Phone,Whatsapp');
				update_option('cht_social_whatsapp', '');
				update_option('cht_social_phone', '');
				update_option('cht_widget_size', '54');
				update_option('widget_icon', 'chat-base');
				update_option('cht_widget_img', '');
				update_option('cht_color', '#A886CD');
				echo esc_url(admin_url("admin.php?page=chaty-app"));
				exit;
			}
		}
	}

	public function change_chaty_widget_status() {
		if (current_user_can('manage_options')) {
			$widget_index = filter_input(INPUT_POST, 'widget_index', FILTER_SANITIZE_STRING);
			$widget_nonce = filter_input(INPUT_POST, 'widget_nonce', FILTER_SANITIZE_STRING);
			if (isset($widget_index) && !empty($widget_index) && !empty($widget_nonce) && wp_verify_nonce($widget_nonce, "chaty_remove_" . $widget_index)) {
				$widget_index = trim($widget_index,"_");
				if(empty($widget_index) || $widget_index == 0) {
					$widget_index = "";
				} else {
					$widget_index = "_".$widget_index;
				}
				$status = get_option("cht_active".$widget_index);
				if($status) {
					update_option("cht_active".$widget_index, 0);
				} else {
					update_option("cht_active".$widget_index, 1);
				}
			}
		}
		echo "1"; exit;
	}

    function chaty_front_form_save_data() {
        $response = array(
            'status' => 0,
            'error' => 0,
            'errors' => array(),
            'message' => ''
        );
        $postData = filter_input_array(INPUT_POST);
        if(isset($postData['nonce']) && isset($postData['widget']) && wp_verify_nonce($postData['nonce'], "chaty-front-form".$postData['widget'])) {
            $name = isset($postData['name'])?$postData['name']:"";
            $phone = isset($postData['email'])?$postData['phone']:"";
            $email = isset($postData['phone'])?$postData['email']:"";
            $message = isset($postData['message'])?$postData['message']:"";
            $ref_url = isset($postData['ref_url'])?$postData['ref_url']:"";
            $widget = $postData['widget'];
            $channel = $postData['channel'];

            $value = get_option('cht_social_' . $channel);   //  get saved settings for button

            $errors = array();
            if(!empty($value)) {
                $field_setting = isset($value['name'])?$value['name']:array();
                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes" && isset($field_setting['is_required']) && $field_setting['is_required'] == "yes" && empty($name)) {
                    $error = array(
                        'field' => 'chaty-field-name',
                        'message' => esc_attr("this field is required", 'chaty')
                    );
                    $errors[] = $error;
                }
	            $field_setting = isset($value['phone'])?$value['phone']:array();
	            if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes" && isset($field_setting['is_required']) && $field_setting['is_required'] == "yes" && empty($phone)) {
		            $error = array(
			            'field' => 'chaty-field-phone',
			            'message' => esc_attr("this field is required", 'chaty')
		            );
		            $errors[] = $error;
	            }
                $field_setting = isset($value['email'])?$value['email']:array();
                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes" && isset($field_setting['is_required']) && $field_setting['is_required'] == "yes") {
                    if(empty($email)) {
                        $error = array(
                            'field' => 'chaty-field-email',
                            'message' => esc_attr("this field is required", 'chaty')
                        );
                        $errors[] = $error;
                    } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $error = array(
                            'field' => 'chaty-field-email',
                            'message' => esc_attr("email address is not valid", 'chaty')
                        );
                        $errors[] = $error;
                    }
                }
                $field_setting = isset($value['message'])?$value['message']:array();
                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes" && isset($field_setting['is_required']) && $field_setting['is_required'] == "yes" && empty($message)) {
                    $error = array(
                        'field' => 'chaty-field-message',
                        'message' => esc_attr("this field is required", 'chaty')
                    );
                    $errors[] = $error;
                }
                if(empty($errors)) {
                    $widget = trim($widget, "_");
                    $response['message'] = esc_attr($value['thanks_message']);
                    $response['redirect_action'] = esc_attr($value['redirect_action']);
                    $response['redirect_link'] = esc_url($value['redirect_link']);
                    $response['link_in_new_tab'] = esc_attr($value['link_in_new_tab']);
                    $response['close_form_after'] = esc_attr($value['close_form_after']);
                    $response['close_form_after_seconds'] =esc_attr( $value['close_form_after_seconds']);
                    $send_leads_in_email = $value['send_leads_in_email'];
                    $save_leads_locally = $value['save_leads_locally'];

	                date_default_timezone_set("UTC");
	                $current_date = date("Y-m-d H:i:s");

	                $new_date = get_date_from_gmt($current_date, "Y-m-d H:i:s");

                    global $wpdb;
                    $chaty_table = $wpdb->prefix . 'chaty_contact_form_leads';
                    $insert = array();
                    $field_setting = isset($value['name'])?$value['name']:array();
                    if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
                        $insert['name'] = esc_sql(sanitize_text_field($name));
                    }
                    $field_setting = isset($value['email'])?$value['email']:array();
                    if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
                        $insert['email'] = esc_sql(sanitize_text_field($email));
                    }
	                $field_setting = isset($value['phone'])?$value['phone']:array();
	                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
		                $insert['phone_number'] = esc_sql(sanitize_text_field($phone));
	                }
                    $field_setting = isset($value['message'])?$value['message']:array();
                    if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
                        $insert['message'] = esc_sql(sanitize_text_field($message));
                    }
                    $insert['ref_page'] = $ref_url;
                    $insert['ip_address'] = $this->get_user_ipaddress();
                    $insert['widget_id'] = esc_sql(sanitize_text_field($widget));
                    $insert['created_on'] = $new_date;
                    $wpdb->insert($chaty_table, $insert);


                    $response['status'] = 1;
                } else {
                    $response['errors'] = $errors;
                    $response['error'] = 1;
                }
            } else {
                $response['message'] = "Invalid request, Please try again";
            }
        } else {
            $response['message'] = "Invalid request, Please try again";
        }
        echo json_encode($response);
        exit;
    }

    function cht_front_end_css_and_js() {
        if ($this->canInsertWidget()):
            /* Initialize widget if widget is enable for current page */
            $social = $this->get_social_icon_list();            // get active icon list
            $cht_active = get_option("cht_active");

            //$bg_color = $this->get_current_color();
            // get custom background color for widget
            $def_color = get_option('cht_color' );
            $custom_color = get_option('cht_custom_color' );     // checking for custom color
            if (!empty($custom_color)) {
                $color = $custom_color;
            } else {
                $color = $def_color;
            }
            $bg_color = strtoupper($color);

            $len = count($social);                              // get total active channels
	        $cta = nl2br(get_option('cht_cta'));
//	        $cta = str_replace(array("\r", "\n"), "", $cta);
	        $cta = str_replace("&amp;#39;","'",$cta);
	        $cta = str_replace("&#39;","'",$cta);
	        $cta = esc_attr__(wp_unslash($cta));
	        $cta = html_entity_decode($cta);

            $isPro = get_option('cht_token');                                 // is PRO version
            $isPro = (empty($isPro) || $isPro == null)?0:1;

            $positionSide = get_option('positionSide');                             // get widget position
            $cht_bottom_spacing = get_option('cht_bottom_spacing');                 // get widget position from bottom
            $cht_side_spacing = get_option('cht_side_spacing');                     // get widget position from left/Right
            $cht_widget_size = get_option('cht_widget_size');                       // get widget size
            $positionSide = empty($positionSide) ? 'right' : $positionSide;         // Initialize widget position if not exists
            $cht_side_spacing = ($cht_side_spacing) ? $cht_side_spacing : '25';     // Initialize widget from left/Right if not exists
            $cht_widget_size = ($cht_widget_size) ? $cht_widget_size : '54';        // Initialize widget size if not exists
            $cht_widget_size = !is_numeric($cht_widget_size)?54:$cht_widget_size;
            $position = get_option('cht_position');
            $position = ($position) ? $position : 'right';                          // Initialize widget position if not exists
            $total = $cht_side_spacing+$cht_widget_size+$cht_side_spacing;
            $cht_bottom_spacing = ($cht_bottom_spacing) ? $cht_bottom_spacing : '25';   // Initialize widget bottom position if not exists
            $cht_side_spacing = ($cht_side_spacing) ? $cht_side_spacing : '25';     // Initialize widget left/Right position if not exists
            $image_id = "";
            $imageUrl = plugin_dir_url("")."chaty-pro/admin/assets/images/chaty-default.png";       // Initialize default image
            $analytics = get_option("cht_google_analytics");                        // check for google analytics enable or not
            $analytics = empty($analytics)?0:$analytics;                            // Initialize google analytics flag to 0 if not data not exists
            $text = esc_html(get_option("cht_close_button_text"));                            // close button settings
            $close_text = ($text === false)?"Hide":$text;

            $imageUrl = "";
            if($image_id != "") {
                $image_data = wp_get_attachment_image_src($image_id, "full");
                if(!empty($image_data) && is_array($image_data)) {
                    $imageUrl = $image_data[0];                                     // change close button image if exists
                }
            }
            $font_family = get_option('cht_widget_font');
	        if($font_family == "System Stack") {
		        $font_family = "-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif";
	        }
            /* add inline css for custom position */

            $animation_class = get_option("chaty_attention_effect");
            $animation_class = empty($animation_class)?"":$animation_class;

            $time_trigger = get_option("chaty_trigger_on_time");
            $time_trigger = empty($time_trigger)?"no":$time_trigger;

            $trigger_time = get_option("chaty_trigger_time");
            $trigger_time = (empty($trigger_time) || !is_numeric($trigger_time) || $trigger_time < 0)?"0":$trigger_time;

            $exit_intent = get_option("chaty_trigger_on_exit");
            $exit_intent = empty($exit_intent)?"no":$exit_intent;

            $on_page_scroll = get_option("chaty_trigger_on_scroll");
            $on_page_scroll = empty($on_page_scroll)?"no":$on_page_scroll;

            $page_scroll = get_option("chaty_trigger_on_page_scroll");
            $page_scroll = (empty($page_scroll) || !is_numeric($page_scroll) || $page_scroll < 0)?"0":$page_scroll;

            $state = get_option("chaty_default_state");
            $state = empty($state)?"click":$state;

            $has_close_button = get_option("cht_close_button");
            $has_close_button = empty($has_close_button)?"yes":$has_close_button;

            $display_days = get_option("cht_date_and_time_settings");
            $display_rules = array();

            $gmt = "";
            if(!empty($display_days)) {
                $count = 0;
                foreach ($display_days as $key=>$value) {
                    if($count == 0) {
                        $gmt = intval($value['gmt']);
                        $count++;
                    }
                    $record = array();
                    $record['days'] = $value['days']-1;
                    $record['start_time'] = $value['start_time'];
                    $record['start_hours'] = intval(date("G",strtotime(date("Y-m-d ".$value['start_time']))));
                    $record['start_min'] = intval(date("i",strtotime(date("Y-m-d ".$value['start_time']))));
                    $record['end_time'] = $value['end_time'];
                    $record['end_hours'] = intval(date("G",strtotime(date("Y-m-d ".$value['end_time']))));
                    $record['end_min'] = intval(date("i",strtotime(date("Y-m-d ".$value['end_time']))));
                    $display_rules[] = $record;
                }
            }
            $display_conditions = 0;
            if(!empty($display_rules)) {
                $display_conditions = 1;
            }

            $mode = get_option("chaty_icons_view");
            $mode = empty($mode) ? "vertical" : $mode;

            $pending_messages = get_option("cht_pending_messages");
            $pending_messages = ($pending_messages === false)?"off":$pending_messages;

            $click_setting = get_option("cht_cta_action");
            $click_setting = ($click_setting === false)?"click":$click_setting;

            $cht_number_of_messages = get_option("cht_number_of_messages");
            $cht_number_of_messages = ($cht_number_of_messages === false)?0:$cht_number_of_messages;

            $number_color = get_option("cht_number_color");
            $number_color = ($number_color === false)?"#ffffff":$number_color;

            $number_bg_color = get_option("cht_number_bg_color");
            $number_bg_color = ($number_bg_color === false)?"#dd0000":$number_bg_color;

            $cht_cta_text_color = get_option("cht_cta_text_color");
            $cht_cta_text_color = ($cht_cta_text_color === false)?"#dd0000":$cht_cta_text_color;

            $cht_cta_bg_color = get_option("cht_cta_bg_color");
            $cht_cta_bg_color = ($cht_cta_bg_color === false)?"#ffffff":$cht_cta_bg_color;

            if(empty($cht_number_of_messages)) {
                $pending_messages = "off";
            }

	        $bg_color = ($bg_color) ? $bg_color : '#A886CD';

            /* widget setting array */
            $settings = array();
            $settings['isPRO'] = 0;
            $settings['pending_messages'] = $pending_messages;
            $settings['cht_cta_bg_color'] = $cht_cta_bg_color;
            $settings['cht_cta_text_color'] = $cht_cta_text_color;
            $settings['click_setting'] = $click_setting;
            $settings['number_of_messages'] = $cht_number_of_messages;
            $settings['number_color'] = $number_color;
            $settings['number_bg_color'] = $number_bg_color;
            $settings['position'] = $position;;
            $settings['social'] = $this->get_social_icon_list();
            $settings['pos_side'] = $positionSide;
            $settings['bot'] = $cht_bottom_spacing;
            $settings['side'] = $cht_side_spacing;
            $settings['device'] = $this->device();
            $settings['color'] = $bg_color;
	        $settings['rgb_color'] = $this->getRGBColor($bg_color);
            $settings['widget_size'] = $cht_widget_size;
            $settings['widget_type'] = get_option('widget_icon');
            $settings['widget_img'] = $this->getCustomWidgetImg();
            $settings['cta'] = esc_attr($cta);
            $settings['active'] = ($cht_active && $len >= 1) ? 'true' : 'false';
            $settings['close_text'] = $close_text;
            $settings['analytics'] = $analytics;
            $settings['save_user_clicks'] = 0;
            $settings['close_img'] = "";
            $settings['is_mobile'] = (wp_is_mobile())?1:0;
            $settings['ajax_url'] = admin_url('admin-ajax.php');
            $settings['animation_class'] = $animation_class;
            $settings['time_trigger'] = $time_trigger;
            $settings['trigger_time'] = $trigger_time;
            $settings['exit_intent'] = $exit_intent;
            $settings['on_page_scroll'] = $on_page_scroll;
            $settings['page_scroll'] = $page_scroll;
            $settings['gmt'] = $gmt;
            $settings['display_conditions'] = $display_conditions;
            $settings['display_rules'] = $display_rules;
            $settings['display_state'] = $state;
            $settings['has_close_button'] = $has_close_button;
            $settings['mode'] = $mode;
            $settings['ajax_url'] = admin_url("admin-ajax.php");

            $data = array();
            $data['object_settings'] = $settings;
            $data['ajax_url'] = admin_url("admin-ajax.php");
            ob_start();
            ?>
                <?php if($position == "left") { ?>
                #wechat-qr-code{left: <?php echo esc_attr($total) ?>px; right:auto;}
                <?php } else if($position == "right") { ?>
                #wechat-qr-code{right: <?php echo esc_attr($total) ?>px; left:auto;}
                <?php } else if($position == "custom") { ?>
                <?php if($positionSide == "left") { ?>
                #wechat-qr-code{left: <?php echo esc_attr($total) ?>px; right:auto;}
                <?php } else { ?>
                #wechat-qr-code{right: <?php echo esc_attr($total) ?>px; left:auto;}
                <?php } ?>
                <?php } ?>
                .chaty-widget-is a{display: block; margin:0; padding:0;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%; }
                .chaty-widget-is svg{margin:0; padding:0;}
                .chaty-main-widget { display: none; }
                .chaty-in-desktop .chaty-main-widget.is-in-desktop { display: block; }
                .chaty-in-mobile .chaty-main-widget.is-in-mobile { display: block; }
                .chaty-widget.hide-widget { display: none !important; }
                .chaty-widget, .chaty-widget .get, .chaty-widget .get a { width: <?php echo esc_attr($cht_widget_size+8); ?>px }
                .facustom-icon { width: <?php echo esc_attr($cht_widget_size); ?>px; line-height: <?php echo esc_attr($cht_widget_size); ?>px; height: <?php echo esc_attr($cht_widget_size); ?>px; font-size: <?php echo esc_attr(intval($cht_widget_size/2)); ?>px; }
                .chaty-widget-is a { width: <?php echo esc_attr($cht_widget_size); ?>px; height: <?php echo esc_attr($cht_widget_size); ?>px; }
                <?php if(!empty($font_family)) { ?>
                .chaty-widget { font-family: <?php echo esc_attr($font_family) ?>; }
                <?php } ?>
                <?php foreach($settings['social'] as $social) {
                    if(!empty($social['bg_color']) && $social['bg_color'] != "#ffffff") {
                        ?>
                .facustom-icon.chaty-btn-<?php echo esc_attr($social['social_channel']) ?> {background-color: <?php echo esc_attr($social['bg_color']) ?>}
                .chaty-<?php echo esc_attr($social['social_channel']) ?> .color-element {fill: <?php echo esc_attr($social['bg_color']) ?>; background: <?php echo esc_attr($social['bg_color']) ?>}
                <?php }
                } ?>
                /*.chaty-widget-i-title.hide-it { display: none !important; }*/
                body div.chaty-widget.hide-widget { display: none !important; }
            <?php
            echo ".i-trigger .chaty-widget-i-title, .chaty-widget-i .chaty-widget-i-title {color:".esc_attr($cht_cta_text_color)." !important; background:".esc_attr($cht_cta_bg_color)." !important;}";
            //echo ".i-trigger .chaty-widget-i-title p, .chaty-widget-i.chaty-main-widget .chaty-widget-i-title p {color:".esc_attr($cht_cta_text_color)." !important; background:".esc_attr($cht_cta_bg_color)." !important;}";
            echo ".i-trigger .chaty-widget-i-title p, .chaty-widget-i.chaty-main-widget .chaty-widget-i-title p {color:".esc_attr($cht_cta_text_color)." !important; }";
            echo ".i-trigger .chaty-widget-i:not(.no-tooltip):before, .chaty-widget-i.chaty-main-widget:before { border-color: transparent transparent transparent ".esc_attr($cht_cta_bg_color)." !important;}";
            echo ".chaty-widget.chaty-widget-is-right .i-trigger .i-trigger-open.chaty-widget-i:before, .chaty-widget.chaty-widget-is-right .chaty-widget-i:before { border-color: transparent ".esc_attr($cht_cta_bg_color)." transparent transparent !important;}";
            echo ".chaty-widget.chaty-widget-is-right .i-trigger .chaty-widget-i:before, .chaty-widget.chaty-widget-is-right .chaty-widget-i:before {border-color: transparent ".esc_attr($cht_cta_bg_color)." transparent transparent !important; }";
            $chaty_css = ob_get_clean();

            if($len >= 1 && !empty($settings['social'])) {

                $chaty_updated_on = get_option("chaty_updated_on");
                if(empty($chaty_updated_on)) {
                    $chaty_updated_on = time();
                }

                /* add js for front end widget */
                if(!empty($font_family)) {
	                if(!in_array($font_family, array("Arial", "Tahoma", "Verdana", "Helvetica", "Times New Roman", "Trebuchet MS", "Georgia", "System Stack", "-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif"))) {
                        wp_enqueue_style('custom-google-fonts', '//fonts.googleapis.com/css?family=' . urlencode($font_family), false, false);
                    }
                }
                /* WP change this */
                wp_enqueue_style( 'chaty-front-css', CHT_PLUGIN_URL."css/chaty-front.min.css", array(), $chaty_updated_on);
                wp_add_inline_style('chaty-front-css', $chaty_css);
                wp_enqueue_script( "chaty-front-end", CHT_PLUGIN_URL."js/cht-front-script.min.js", array( 'jquery' ), $chaty_updated_on, false);
                wp_localize_script('chaty-front-end', 'chaty_settings',  $data);
            }
        endif;
    }

    public function get_chaty_settings() {
        $slug = filter_input(INPUT_POST, 'social', FILTER_SANITIZE_STRING);
        $channel = filter_input(INPUT_POST, 'channel', FILTER_SANITIZE_STRING);
        $status = 0;
        $data = array();
        if(!empty($slug)) {
            foreach ($this->socials as $social) {
                if ($social['slug'] == $slug) {
                    break;
                }
            }
            if (!empty($social)) {
                $status = 1;
                $data = $social;
                $data['help'] = "";
                $data['help_text'] = "";
                $data['help_link'] = "";
                if((isset($social['help']) && !empty($social['help'])) || isset($social['help_link'])) {
                    $data['help_title'] = isset($social['help_title'])?$social['help_title']:"Doesn't work?";
                    $data['help_text'] = isset($social['help'])?$social['help']:"";
                    if(isset($data['help_link']) && !empty($data['help_link'])) {
                        $data['help_link'] = $data['help_link'];
                    } else {
                        $data['help_title'] = $data['help_title'];
                    }
                }
            }
        }
        $response = array();
        $response['data'] = $data;
        $response['status'] = $status;
        $response['channel'] = $channel;
        echo json_encode($response);
        die;
    }

    /* function choose_social_handler start */
    public function choose_social_handler()
    {
        check_ajax_referer('cht_nonce_ajax', 'nonce_code');
        $slug = filter_input(INPUT_POST, 'social', FILTER_SANITIZE_STRING);

        if (!is_null($slug) && !empty($slug)) {
            foreach ($this->socials as $social) {
                if ($social['slug'] == $slug) {
                    break;
                }
            }
            if (!$social) {
                return;                                     // return if social media setting not found
            }

            $widget_index = filter_input(INPUT_POST, 'widget_index', FILTER_SANITIZE_STRING);

            $value = get_option('cht_social'.$widget_index.'_' . $slug);   // get setting for media if already saved

            if (empty($value)) {                                        // Initialize default values if not found
                $value = [
                    'value' => '',
                    'is_mobile' => 'checked',
                    'is_desktop' => 'checked',
                    'image_id' => '',
                    'title' => $social['title'],
                    'bg_color' => "",
                ];
            }
            if(!isset($value['bg_color']) || empty($value['bg_color'])) {
                $value['bg_color'] = $social['color'];                  // Initialize background color value if not exists. 2.1.0 change
            }
            if(!isset($value['image_id'])) {
                $value['image_id'] = '';                                // Initialize custom image id if not exists. 2.1.0 change
            }
            if(!isset($value['title'])) {
                $value['title'] = $social['title'];                     // Initialize title if not exists. 2.1.0 change
            }
            if(!isset($value['fa_icon'])) {
                $value['fa_icon'] = "";                     // Initialize title if not exists. 2.1.0 change
            }
            if(!isset($value['value'])) {
                $value['value'] = "";                     // Initialize title if not exists. 2.1.0 change
            }
            $imageId = $value['image_id'];
            $imageUrl = "";
            $status = 0;
            if(!empty($imageId)) {
                $imageUrl = wp_get_attachment_image_src($imageId, "full")[0];                       // get custom image URL if exists
                $status = 1;
            }
            if($imageUrl == "") {
                $imageUrl = plugin_dir_url("")."chaty/admin/assets/images/chaty-default.png";   // Initialize with default image if custom image is not exists
                $status = 0;
                $imageId = "";
            }
            $color = "";
            if(!empty($value['bg_color'])) {
                $color = "background-color: ".$value['bg_color'];                                   // set background color of icon it it is exists
            }
            if($social['slug'] == "Whatsapp"){
                $val = $value['value'];
                $val = str_replace("+","", $val);
                $value['value'] = $val;
            } else if($social['slug'] == "Facebook_Messenger"){
                $val = $value['value'];
                $val = str_replace("facebook.com","m.me", $val);                                    // Replace facebook.com with m.me version 2.0.1 change
                $val = str_replace("www.","", $val);                                                // Replace www. with blank version 2.0.1 change
                $value['value'] = $val;

                $val = trim($val, "/");
                $val_array = explode("/", $val);
                $total = count($val_array)-1;
                $last_value = $val_array[$total];
                $last_value = explode("-", $last_value);
                $total_text = count($last_value)-1;
                $total_text = $last_value[$total_text];

                if(is_numeric($total_text)) {
                    $val_array[$total] = $total_text;
                    $value['value'] = implode("/", $val_array);
                }
            }
            $value['value'] = esc_attr__(wp_unslash($value['value']));
            $value['title'] = esc_attr__(wp_unslash($value['title']));

            $svg_icon = $social['svg'];

            $help_title = "";
            $help_text = "";
            $help_link = "";

            if((isset($social['help']) && !empty($social['help'])) || isset($social['help_link'])) {
                $help_title = isset($social['help_title'])?$social['help_title']:"Doesn't work?";
                $help_text = isset($social['help'])?$social['help']:"";
                if(isset($social['help_link']) && !empty($social['help_link'])) {
                    $help_link = $social['help_link'];
                }
            }

            $channel_type = "";
            $placeholder = $social['example'];
            if($social['slug'] == "Link" || $social['slug'] == "Custom_Link" || $social['slug'] == "Custom_Link_3" || $social['slug'] == "Custom_Link_4" || $social['slug'] == "Custom_Link_5") {
                if (isset($value['channel_type'])) {
                    $channel_type = esc_attr__(wp_unslash($value['channel_type']));
                }

                if(!empty($channel_type)) {
                    foreach($this->socials as $icon) {
                        if($icon['slug'] == $channel_type) {
                            $svg_icon = $icon['svg'];

                            $placeholder = $icon['example'];

                            if((isset($icon['help']) && !empty($icon['help'])) || isset($icon['help_link'])) {
                                $help_title = isset($icon['help_title'])?$icon['help_title']:"Doesn't work?";
                                $help_text = isset($icon['help'])?$icon['help']:"";
                                if(isset($icon['help_link']) && !empty($icon['help_link'])) {
                                    $help_link = $icon['help_link'];
                                }
                            }
                        }
                    }
                }
            }
            if(empty($channel_type)) {
                $channel_type = $social['slug'];
            }
	        if($channel_type == "Telegram") {
		        $value['value'] = trim($value['value'], "@");
	        }
            ob_start();
            include CHT_DIR."/views/admin/channel.php";
            $html = ob_get_clean();
            echo json_encode($html);
        }
        wp_die();
    }
    /* function choose_social_handler end */

    /* get social media list for front end widget */
    public function get_social_icon_list()
    {
        $social = get_option('cht_numb_slug'.$this->widget_number); // get saved social media list
        $social = explode(",", $social);

        $arr = array();
        foreach ($social as $key_soc):
            foreach ($this->socials as $key => $social) :       // compare with Default Social media list
                if ($social['slug'] != $key_soc) {
                    continue;                                   // return if slug is not equal
                }
                $value = get_option('cht_social'.$this->widget_number.'_' . $social['slug']);   //  get saved settings for button
                if ($value) {
                    $slug = strtolower($social['slug']);
                    $channel_id = "cht-channel-0";
                    $channel_id = trim($channel_id, "_");
                    if (!empty($value['value']) || $slug == "contact_us") {
                        $slug = strtolower($social['slug']);
                        $url = "";
                        $mobile_url = "";
                        $desktop_target = "";
                        $mobile_target = "";
                        $qr_code_image = "";

                        $channel_type = $slug;

                        if(!isset($value['value'])) {
                            $value['value'] = "";
                        }

                        $svg_icon = $social['svg'];
                        if($slug == "link" || $slug == "custom_link" || $slug == "custom_link_3" || $slug == "custom_link_4" || $slug == "custom_link_5") {
                            if(isset($value['channel_type']) && !empty($value['channel_type'])) {
                                $channel_type = $value['channel_type'];

                                foreach($this->socials as $icon) {
                                    if($icon['slug'] == $channel_type) {
                                        $svg_icon = $icon['svg'];
                                    }
                                }
                            }
                        }

                        $channel_type = strtolower($channel_type);

                        $val = "";
                        if($channel_type == "viber") {
                            /* Viber change to exclude + from number for desktop */
                            $val = $value['value'];
                            if(is_numeric($val)) {
                                $fc = substr($val, 0, 1);
                                if($fc == "+") {
                                    $length = -1*(strlen($val)-1);
                                    $val = substr($val, $length);
                                }
                                if(!wp_is_mobile()) {
                                    /* Viber change to include + from number for mobile */
                                    $val = "+".$val;
                                }
                            }
                        } else if($channel_type == "whatsapp") {
                            /* Whatspp change to exclude + from phone number */
                            $val = $value['value'];
                            $val = str_replace("+","", $val);
                            $val = str_replace("-","", $val);
                            $val = str_replace(" ","", $val);
                        } else if($channel_type == "facebook_messenger") {
                            /* Facebook change to change URL from facebook.com to m.me version 2.1.0 change */
                            $val = $value['value'];
                            $val = str_replace("facebook.com","m.me", $val);                                    // Replace facebook.com with m.me version 2.0.1 change
                            $val = str_replace("www.","", $val);                                                // Replace www. with blank version 2.0.1 change
                            $value['value'] = $val;

                            $val = trim($val, "/");
                            $val_array = explode("/", $val);
                            $total = count($val_array)-1;
                            $last_value = $val_array[$total];
                            $last_value = explode("-", $last_value);
                            $total_text = count($last_value)-1;
                            $total_text = $last_value[$total_text];

                            if(is_numeric($total_text)) {
                                $val_array[$total] = $total_text;
                                $val = implode("/", $val_array);
                            }
                        } else {
                            $val = $value['value'];
                        }
                        if(!isset($value['title'])) {
                            $value['title'] = $social['title'];         // Initialize title with default title if not exists. version 2.1.0 change
                        }
                        $image_url = "";
                        $val = esc_attr($val);
                        $value['title'] = esc_attr($value['title']);

                        /* get custom image URL if uploaded. version 2.1.0 change */
                        if(isset($value['image_id']) && !empty($value['image_id'])) {
                            $image_id = $value['image_id'];
                            if(!empty($image_id)) {
                                $image_data = wp_get_attachment_image_src($image_id, "full");
                                if(!empty($image_data) && is_array($image_data)) {
                                    $image_url = $image_data[0];
                                }
                            }
                        }

                        $on_click_fn = "";
                        $popup_html = "";
                        $has_custom_popup = 0;
                        $is_default_open = 0;
                        /* get custom icon background color if exists. version 2.1.0 change */
                        if(!isset($value['bg_color']) || empty($value['bg_color'])) {
                            $value['bg_color'] = '';
                        }
                        if($channel_type == "whatsapp") {
                            /* setting for Whatsapp URL */
                            $val = str_replace("+","",$val);
	                        if(isset($value['use_whatsapp_web']) && $value['use_whatsapp_web'] == "no") {
		                        $url = "https://wa.me/".$val;
	                        } else {
		                        $url = "https://web.whatsapp.com/send?phone=" . $val;
	                        }
                            $mobile_url = "https://wa.me/".$val;
                            // https://wa.me/$number?text=$test
                            if(isset($value['pre_set_message']) && !empty($value['pre_set_message'])) {
	                            if(isset($value['use_whatsapp_web']) && $value['use_whatsapp_web'] == "no") {
		                            $url .= "?text=".rawurlencode($value['pre_set_message']);
	                            } else {
		                            $url .= "&text=".rawurlencode($value['pre_set_message']);
	                            }
                                $mobile_url .= "?text=".rawurlencode($value['pre_set_message']);
                            }
                            $url = esc_url($url);
                            if(wp_is_mobile()) {
                                $mobile_target = "";
                            } else {
                                $desktop_target = "_blank";
                            }
                            if(isset($value['embedded_window']) && $value['embedded_window'] == "yes") {
                                $embedded_message = isset($value['embedded_message'])?$value['embedded_message']:"";
                                $pre_set_message = isset($value['pre_set_message'])?$value['pre_set_message']:"";
                                $is_default_open = (isset($value['is_default_open'])&&$value['is_default_open']=="yes")?1:0;

                                $has_custom_popup = 1;
                                $mobile_url = "javascript:;";
                                $url = "javascript:;";
                                $url = "javascript:;";
                                $close_button = "<div role='button' class='close-chaty-popup is-whatsapp-btn'><div class='chaty-close-button'></div></div>";
                                $popup_html = "<div class='chaty-whatsapp-popup'>";
                                $popup_html .= "<textarea class='default-value' style='display:none'>".esc_html($pre_set_message)."</textarea>";
                                $popup_html .= "<textarea class='default-msg-value' style='display:none'>".esc_html($embedded_message)."</textarea>";
                                $popup_html .= "<textarea class='default-msg-phone' style='display:none'>".esc_html($val)."</textarea>";
                                $popup_html .= "<div class='chaty-whatsapp-body'>".$close_button."<div class='chaty-whatsapp-message'></div></div>";
                                $popup_html .= "<div class='chaty-whatsapp-footer'>";
	                            if(isset($value['use_whatsapp_web']) && $value['use_whatsapp_web'] == "no") {
		                            $popup_html .= "<form class='whatsapp-chaty-form' autocomplete='off' target='_blank' action='https://wa.me/".esc_attr($val)."' method='get'>";
	                            } else {
		                            $popup_html .= "<form class='whatsapp-chaty-form' autocomplete='off' target='_blank' action='https://web.whatsapp.com/send' method='get'>";
	                            }
                                $popup_html .= "<div class='chaty-whatsapp-field'><input autocomplete='off' class='chaty-whatsapp-msg' name='text' value='' /></div>";
                                $popup_html .= "<input type='hidden' name='phone' class='chaty-whatsapp-phone' value='' />";
                                $popup_html .= "<input type='hidden' class='is-default-open' value='".esc_attr($is_default_open)."' />";
                                $popup_html .= "<input type='hidden' class='channel-id' value='".esc_attr($channel_id)."' />";
                                $popup_html .= "<button type='submit' class='chaty-whatsapp-submit-btn'><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path fill='#ffffff' d='M1.101 21.757L23.8 12.028 1.101 2.3l.011 7.912 13.623 1.816-13.623 1.817-.011 7.912z'></path></svg></button><div style='clear:both'></div>";
                                $popup_html .= "</form>";
                                $popup_html .= "</div>";
                                $popup_html .= "</div>";
                            }
                        } else if($channel_type == "phone") {
                            /* setting for Phone */
                            $url = "tel:".$val;
                        } else if($channel_type == "sms") {
                            /* setting for SMS */
                            $url = "sms:".$val;
                        } else if($channel_type == "telegram") {
                            /* setting for Telegram */
	                        $val = ltrim($val, "@");
                            $url = "https://telegram.me/".$val;
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                        } else if($channel_type == "line" || $channel_type == "google_maps" || $channel_type == "poptin" || $channel_type == "waze" ) {
                            /* setting for Line, Google Map, Link, Poptin, Waze, Custom Link */
                            $url = esc_url($val);
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                        } else if($channel_type == "link" || $channel_type == "custom_link" || $channel_type == "custom_link_3" || $channel_type == "custom_link_4" || $channel_type == "custom_link_5") {
                            $is_exist = strpos($val, "javascript");
                            $is_viber = strpos($val, "viber");
                            if($is_viber !== false) {
                                $url = $val;
                            } else if($is_exist === false) {
                                $url = esc_url($val);
                                if($channel_type == "custom_link" || $channel_type == "link" || $channel_type == "custom_link_3" || $channel_type == "custom_link_4" || $channel_type == "custom_link_5") {
                                    $desktop_target = (isset($value['new_window']) && $value['new_window'] == 0)?"":"_blank";
                                    $mobile_target = (isset($value['new_window']) && $value['new_window'] == 0)?"":"_blank";
                                }
                            } else {
                                $url = "javascript:;";
                                $on_click_fn = str_replace('"',"'",$val);
                            }
                        }else if($channel_type == "wechat") {
                            /* setting for WeChat */
                            $url = "javascript:;";
                            if(!empty($value['title'])) {
	                            $value['title'] .= ": ".$val;
                            } else {
	                            $value['title'] = $val;
                            }
                            $qr_code = isset($value['qr_code'])?$value['qr_code']:"";
                            if(!empty($qr_code)) {
                                $image_data = wp_get_attachment_image_src($qr_code, "full");
                                if(!empty($image_data) && is_array($image_data)) {
                                    $qr_code_image = $image_data[0];
                                }
                            }
                        } else if($channel_type == "viber") {
                            /* setting for Viber */
                            $url = $val;
                        } else if($channel_type == "snapchat") {
                            /* setting for SnapChat */
                            $url = "https://www.snapchat.com/add/".$val;
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                        } else if($channel_type == "waze") {
                            /* setting for Waze */
                            $url = "javascript:;";
                            $value['title'] .= ": ".$val;
                        } else if($channel_type == "vkontakte") {
                            /* setting for vkontakte */
                            $url = "https://vk.me/".$val;
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                        } else if($channel_type == "skype") {
                            /* setting for Skype */
                            $url = "skype:".$val."?chat";
                        } else if($channel_type == "email") {
                            /* setting for Email */
                            $url = "mailto:".$val;
                            $mail_subject = (isset($value['mail_subject']) && !empty($value['mail_subject']))?$value['mail_subject']:"";
                            if($mail_subject != "") {
                                $url .= "?subject=".urlencode($mail_subject);
                            }
                            $url = esc_url($url);
                        } else if($channel_type == "facebook_messenger") {
                            /* setting for facebook URL */
                            $url = esc_url($val);
                            $url = str_replace("http:", "https:", $url);
                            if(wp_is_mobile()) {
                                $mobile_target = "";
                            } else {
                                $desktop_target = "_blank";
                            }
                            $url = esc_url($url);
                        } else if($channel_type == "twitter") {
                            /* setting for Twitter */
                            $url = "https://twitter.com/".$val;
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                            $url = esc_url($url);
                        } else if($channel_type == "instagram") {
                            /* setting for Instagram */
                            $url = "https://www.instagram.com/".$val;
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                            $url = esc_url($url);
                        } else if($channel_type == "linkedin") {
                            /* setting for Linkedin */
                            $link_type = !isset($value['link_type']) || $value['link_type'] == "company"?"company":"personal";
                            if($link_type == "personal") {
                                $url = "https://www.linkedin.com/in/".$val;
                            } else {
                                $url = "https://www.linkedin.com/company/".$val;
                            }
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                            $url = esc_url($url);
                        } else if($channel_type == "slack") {
                            /* setting for slack */
                            $url = esc_url($val);
                            $desktop_target = "_blank";
                            $mobile_target = "_blank";
                        } else if($channel_type == "contact_us") {
                            $url = "javascript:;";
                            $desktop_target = "";
                            $mobile_target = "";
                            $input_fields = "";
                            if(isset($value['name']) || isset($value['email']) || isset($value['message'])) {
                                $field_setting = $value['name'];
                                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
                                    $is_required = (isset($field_setting['is_required']) && $field_setting['is_required'] == "yes")?"is-required":"";
                                    $placeholder = isset($field_setting['placeholder'])?$field_setting['placeholder']:"Enter your name";
                                    $input_fields .= "<div class='chaty-input-area'>";
                                    $input_fields .= "<input autocomplete='off' class='chaty-input-field chaty-field-name {$is_required}' name='name' type='text' id='chaty-name' placeholder='".esc_attr($placeholder)."' />";
                                    $input_fields .= "</div>";
                                }
                                $field_setting = $value['email'];
                                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
                                    $is_required = (isset($field_setting['is_required']) && $field_setting['is_required'] == "yes")?"is-required":"";
                                    $placeholder = isset($field_setting['placeholder'])?$field_setting['placeholder']:"Enter your email address";
                                    $input_fields .= "<div class='chaty-input-area'>";
                                    $input_fields .= "<input autocomplete='off' class='chaty-input-field chaty-field-email {$is_required}' name='email' type='email' id='chaty-name' placeholder='".esc_attr($placeholder)."' />";
                                    $input_fields .= "</div>";
                                }
	                            $field_setting = $value['phone'];
	                            if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
		                            $is_required = (isset($field_setting['is_required']) && $field_setting['is_required'] == "yes")?"is-required":"";
		                            $placeholder = isset($field_setting['placeholder'])?$field_setting['placeholder']:"Enter your phone number";
		                            $input_fields .= "<div class='chaty-input-area'>";
		                            $input_fields .= "<input autocomplete='off' class='chaty-input-field chaty-field-phone {$is_required}' name='name' type='text' id='chaty-phone' placeholder='".esc_attr($placeholder)."' />";
		                            $input_fields .= "</div>";
	                            }
                                $field_setting = $value['message'];
                                if(isset($field_setting['is_active']) && $field_setting['is_active'] == "yes") {
                                    $is_required = (isset($field_setting['is_required']) && $field_setting['is_required'] == "yes")?"is-required":"";
                                    $placeholder = isset($field_setting['placeholder'])?$field_setting['placeholder']:"Enter your message";
                                    $input_fields .= "<div class='chaty-input-area'>";
                                    $input_fields .= "<textarea autocomplete='off' class='chaty-input-field chaty-field-message {$is_required}' name='name' id='chaty-name' placeholder='".esc_attr($placeholder)."' ></textarea>";
                                    $input_fields .= "</div>";
                                }
                            }
                            if(!empty($input_fields)) {
                                $has_custom_popup = 1;
                                $button_text = isset($value['button_text']) && !empty($value['button_text'])?esc_attr($value['button_text']):"Submit";
                                $button_bg_color = isset($value['button_bg_color']) && !empty($value['button_bg_color'])?esc_attr($value['button_bg_color']):"#A886CD";
                                $button_text_color = isset($value['button_text_color']) && !empty($value['button_text_color'])?esc_attr($value['button_text_color']):"#ffffff";
                                $contact_form_title = isset($value['contact_form_title'])?$value['contact_form_title']:"";
                                $popup_html = "<div class='chaty-contact-form'>";
                                $popup_html .= "<form action='#' method='post' class='chaty-contact-form-data' autocomplete='off'>";
                                $popup_html .= "<div class='chaty-contact-header'>".esc_attr($contact_form_title)." <div role='button' class='close-chaty-popup'><div class='chaty-close-button'></div></div><div style='clear:both'></div></div>";
                                $popup_html .= "<div class='chaty-contact-body'>";
                                $popup_html .= $input_fields;
                                $popup_html .= "<input type='hidden' class='chaty-field-widget' name='widget_id' value='' />";
                                $popup_html .= "<input type='hidden' class='chaty-field-channel' name='channel' value='{$social['slug']}' />";
                                $nonce = wp_create_nonce("chaty-front-form");
                                $popup_html .= "<input type='hidden' class='chaty-field-nonce' name='nonce' value='{$nonce}' />";
                                $popup_html .= "</div>";
                                $popup_html .= "<div class='chaty-contact-footer'>";
                                $popup_html .= "<button style='color: ".esc_attr($button_text_color)."; background: ".esc_attr($button_bg_color)."' type='submit' class='chaty-contact-submit-btn' data-text='".esc_attr($button_text)."'>".esc_attr($button_text)."</div>";
                                $popup_html .= "</div>";
                                $popup_html .= "</form>";
                                $popup_html .= "</div>";
                            }
                        } else if($channel_type == "tiktok") {
	                        $val = $value['value'];
	                        $firstCharacter = substr($val, 0, 1);
	                        if($firstCharacter != "@") {
		                        $val = "@".$val;
	                        }
	                        $url = esc_url("https://www.tiktok.com/".$val);
	                        $desktop_target = $mobile_target = "_blank";
                        }

                        /* Instagram checking for custom color */
                        if($channel_type == "instagram" && $value['bg_color'] == "#ffffff") {
                            $value['bg_color'] = "";
                        }

                        $svg = trim(preg_replace('/\s\s+/', '', $svg_icon));

                        $is_mobile = isset($value['is_mobile']) ? 1 : 0;
                        $is_desktop = isset($value['is_desktop']) ? 1 : 0;

                        if(empty($mobile_url)) {
                            $mobile_url = $url;
                        }

                        $svg_class = ($channel_type == "contact_us")?"color-element":"";

                        $svg = '<svg class="ico_d '.$svg_class.'" width="39" height="39" viewBox="0 0 39 39" fill="none" xmlns="http://www.w3.org/2000/svg" style="transform: rotate(0deg);">'.$svg.'</svg>';

	                    $rgb_color = $this->getRGBColor($value['bg_color']);

/*                        $url = esc_url($url);
                        $mobile_url = esc_url($mobile_url);*/
                        $data = array(
                            'val' => esc_attr__(wp_unslash($val)),
                            'default_icon' => $svg,
                            'bg_color' => $value['bg_color'],
                            'rbg_color' => $rgb_color,
                            'title' => esc_attr__(wp_unslash($value['title'])),
                            'img_url' => esc_url($image_url),
                            'social_channel' => $slug,
                            'channel_type' => $channel_type,
                            'href_url' => $url,
                            'desktop_target' => $desktop_target,
                            'mobile_target' => $mobile_target,
                            'qr_code_image' => esc_url($qr_code_image),
                            'channel' => $social['slug'],
                            'is_mobile' => $is_mobile,
                            'is_desktop' => $is_desktop,
                            'mobile_url' => $mobile_url,
                            'on_click' => $on_click_fn,
                            "has_font" => 0,
                            "popup_html" => $popup_html,
                            "has_custom_popup" => $has_custom_popup,
                            "is_default_open" => $is_default_open
                        );
                        $arr[] = $data;
                    }
                }
            endforeach;
        endforeach;
        return $arr;
    }

    public function insert_widget()
    {

    }

	public function getRGBColor($color) {
		if(!empty($color)) {
			if (strpos($color, '#') !== false) {
				$color = $this->hex2rgba($color);
			}
			if (strpos($color, 'rgba(') !== false || strpos($color, 'rgb(') !== false) {
				$color = explode(",", $color);
				$color = str_replace(array("rgba(", "rgb(", ")"), array("","",""), $color);
				$string = "";
				$string .= ((isset($color[0]))?trim($color[0]):"0").",";
				$string .= ((isset($color[1]))?trim($color[1]):"0").",";
				$string .= ((isset($color[2]))?trim($color[2]):"0");
				return $string;
			}
		}
		return "0,0,0";
	}

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

		$default = 'rgb(0,0,0)';

		//Return default if no color provided
		if(empty($color))
			return $default;

		//Sanitize $color if "#" is provided
		if ($color[0] == '#' ) {
			$color = substr( $color, 1 );
		}

		//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;
		}

		//Convert hexadec to rgb
		$rgb =  array_map('hexdec', $hex);

		//Check if opacity is set(rgba or rgb)
		if($opacity){
			if(abs($opacity) > 1)
				$opacity = 1.0;
			$output = 'rgba('.implode(",",$rgb).','.$opacity.')';
		} else {
			$output = 'rgb('.implode(",",$rgb).')';
		}

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

    private function canInsertWidget()
    {
        return get_option('cht_active') && $this->checkChannels();
    }

    private function checkChannels()
    {
        $social = explode(",", get_option('cht_numb_slug'));
        $res = false;
        foreach ($social as $name) {
            $value = get_option('cht_social_' . strtolower($name));
            $res = $res || !empty($value['value']) || ($name == "Contact_Us");
        }
        return $res;
    }

    function get_user_ipaddress() {
        if(!empty($_SERVER['HTTP_CLIENT_IP'])){
            $ip = sanitize_text_field( wp_unslash($_SERVER['HTTP_CLIENT_IP']));
        }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
            //ip pass from proxy
            $ip = sanitize_text_field( wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
        }else{
            $ip = sanitize_text_field( wp_unslash($_SERVER['REMOTE_ADDR']));
        }
        return $ip;
    }
}

return new CHT_Frontend();
