<?php
defined('ABSPATH') or die('No script kiddies please!');

/**
    Plugin Name:  WP WhatsApp Button (Sliding Animation)
    Plugin URI:   https://accesspressthemes.com/wordpress-plugins/wp-whatsapp-button
    Description:  WP WhatsApp Button allows you to easily create WhatsApp button in WordPress.
    Version:      2.0.3
    Author:       AccessPress Themes
    Author URI:   https://accesspressthemes.com
    License:      GPL2
    License URI:  https://www.gnu.org/licenses/gpl-2.0.html
    Text Domain:  wp-whatsapp-button
    Domain Path:  /languages
*/

define('wpwab_PLUGIN_PATH', plugin_dir_path(__FILE__));
include(wpwab_PLUGIN_PATH . 'inc/frontend/wpwab-mobile-detect.php');
include(wpwab_PLUGIN_PATH . 'inc/backend/wpwab-widget.php');
require_once('inc/backend/pagination/wpwab-pagination.php');

if (!class_exists('wpwab_Class')) {
    class wpwab_Class {
        function __construct() {

            $this->define_constants();
            add_action('plugins_loaded', array($this, 'wpwab_load_textdomain'));
            add_action('admin_menu', array($this, 'wpwab_menu'));
            add_action('admin_enqueue_scripts', array($this, 'wpwab_register_assets'));
            add_action('admin_post_wpwab_settings_save', array($this, 'save_form_settings'));
            add_shortcode('wp_whatsapp_button', array($this, 'wpwab_shortcode'));
            add_action('wp_enqueue_scripts', array($this, 'wpwab_register_frontend_assets'));
            add_action('widgets_init', array($this, 'wpwab_register_widget'));
            add_filter('wp_nav_menu_items', array($this, 'wpwab_menu_overwrite'), 10, 2);
            add_action('wp_footer', array($this, 'testing_footer'));
            add_action('wp_footer', array($this, 'multi_contact'));
            add_action('wp_ajax_wpwab_floating_button', array($this, 'wpwab_floating_button'));
            add_action('wp_ajax_wpwab_reset_button', array($this, 'wpwab_reset_button'));
            add_action('wp_ajax_wpwab_floating_button_pages', array($this, 'wpwab_floating_button_pages'));

            add_action('wp_ajax_wpwab_multi_settings_pages', array($this, 'wpwab_multi_settings_pages'));
            add_action('wp_ajax_wpwab_multi_settings_posts', array($this, 'wpwab_multi_settings_posts'));



            /* For Appending Div */
            add_action('wp_ajax_wpwab_append_elements', array($this, 'wpwab_append_custom_elements')); // Ajax hook
            add_action('wp_ajax_nopriv_wpwab_append_elements', array($this, 'wpwab_append_custom_elements'));

        }

        function wpwab_multi_settings_pages (){
            include('inc/backend/pagination/multi/wpwab-page-list.php' );
            die();
        }

        function wpwab_multi_settings_posts (){

            include('inc/backend/pagination/multi/wpwab-post-list.php' );
            die();
        }

        function wpwab_append_custom_elements() {
            if (isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'wpwab-admin-ajax-nonce')) {
                ob_start();
                include(wpwab_PLUGIN_PATH . 'inc/backend/multiple/multi-contact.php');
                $content = ob_get_contents();
                ob_get_clean();
                echo json_encode($content);
                die;
            }
        }

        function wpwab_reset_button(){

            if (isset($_POST['_wpajaxnonce']) && wp_verify_nonce($_POST['_wpajaxnonce'], 'wpwab-admin-ajax-nonce')) {

                $default_settings = array(

                    'contact_number' => '',
                    'whatsapp_format' => 'web',
                    'button_text' => '',
                    'button_text_position' => 'right',
                    'enable_sticky' => 'show',
                    'tooltip_text' => 'WhatsApp Me!',
                    'button_template' => 'template-1',
                    'button_color' =>'',
                    'text_color' =>'',
                    'icon_background_color' =>'',
                    'icon_color' =>'',
                    'button_animation' => 'animation-6',
                    'animation_type'=>'on_hover',
                    'button_location' => 'bottom_right',
                    'pages' => 'all',
                    'page_details' => 'page',
                    'posts' => 'all',
                    'post_details' => 'post',
                    'category' => 'all',
                    'specific_pages_list' => '',
                    'specific_posts_list' =>'',
                    'showbutton' => 'show',
                    'first' => 'last',
                    'showbuttontext' => 'show',
                    'whatsapp_button_text_menu' => 'WhatsApp Us!',
                    'wpwab_button_template_menu' => 'template-1',
                    'button_color_menu' => '',
                    'text_color_menu' => '',
                    'icon_background_color_menu' => '',
                    'icon_color_menu' => '',
                    'menu_list' => Array(),
                    'generate_shortcode' => '',
                    'button_name' => 'WhatsApp',
                    'button_location_shortcode' => 'top_left',
                    'enable_desktop' => 'hide',
                    'specific_page' => Array(),
                    'multi' => Array(
                        'enable_sticky' => 'show',
                        'greeting_text' => 'Start A Conversation',
                        'greeting_sub_text' => 'Connect with any one of our support members',
                        'button_location' => 'bottom_right',
                        'pages' => 'page',
                        'page_details' => 'page',
                        'posts' => 'post',
                        'post_details' => 'post',
                        'category' => 'specific',
                        'specific_pages_list' => '',
                        'specific_posts_list' => '',
                        'specific_page' => Array()
                    ),
                'multiple' => Array ()
                );

                $array = update_option('wpwab_settings', $default_settings);
                echo admin_url('admin.php?page=wp-whatsapp-button&message=3');
                die();
            }else{
                echo admin_url('admin.php?page=wp-whatsapp-button&message=2');
                die();
            }

        }

        function redirect($redirect){
            if (headers_sent()){ // Use JavaScript to redirect if content has been previously sent (not recommended, but safe)
                echo '<script language="JavaScript" type="text/javascript">window.location=\'';
                echo $redirect;
                echo '\';</script>';
            }else{  // Default Header Redirect
                header('Location: ' . $redirect);
            }
            exit;
        }

        function testing_footer() {
            $wpwab_settings = get_option('wpwab_settings');
            
            $omit_keys = array('generate_shortcode', 'pages', 'posts', 'showbutton', 'wpwab_button_template', 'wpwab_button_animation', 'showbutton', 'first', 'showbuttontext', 'whatsapp_button_text_menu', 'wpwab_button_template_menu', 'button_color_menu', 'text_color_menu', 'icon_background_color_menu', 'icon_color_menu', 'menu_list', 'category', 'fb_user_name_menu', 'button_text_show', 'button_name');
            $shortcode_atts = array();
            if(!empty($wpwab_settings)){
                foreach ($wpwab_settings as $key => $val) {
                    if (!(is_array($val) || in_array($key, $omit_keys))) {
                        $shortcode_atts[] = $key . "='" . $val . "'";
                    }
                } 
            }
            
            $shortcode_atts = implode(' ', $shortcode_atts);

            $shortcode = '[wp_whatsapp_button ' . $shortcode_atts . ' ]';

            $specific_page_flag = true;
            global $post;
            if (isset($wpwab_settings['pages']) && $wpwab_settings['pages'] == 'page' && is_page()) {
                $specific_pages = (!empty($wpwab_settings['specific_page'])) ? $wpwab_settings['specific_page'] : array();
                if (!in_array($post->ID, $specific_pages)) {
                    $specific_page_flag = false;
                }
            }
            $specific_post_flag = true;
            if (is_singular('post') && isset($wpwab_settings['posts']) && $wpwab_settings['posts'] == 'post') {
                $specific_post = (!empty($wpwab_settings['specific_post'])) ? $wpwab_settings['specific_post'] : array();
                if (!in_array($post->ID, $specific_post)) {
                    $specific_post_flag = false;
                }
            }
            $specific_category_flag = true;
            if (is_singular('post') && isset($wpwab_settings['category']) && $wpwab_settings['category'] == 'specific') {
                $specific_category = (!empty($wpwab_settings['specific_category'])) ? $wpwab_settings['specific_category'] : array();
                $categories = get_the_category($post->ID);
                $term_ids = wp_list_pluck($categories, 'term_id');

                if (!array_intersect($specific_category, $term_ids)) {
                    $specific_category_flag = false;
                } //when found
            }
             if ($specific_page_flag && $specific_post_flag && $specific_category_flag) {

                echo do_shortcode("$shortcode");
             }
        }
        
        function multi_contact() {
            $wpwab_settings = get_option('wpwab_settings');
                    
            if (isset($wpwab_settings['enable_multi']) && $wpwab_settings['enable_multi']  == 'enable'){
            
                $specific_page_flag = true;
                global $post;


                if (isset($wpwab_settings['multi']['pages']) && $wpwab_settings['multi']['pages'] == 'page' && is_page()) {

                    $selected_pages = (isset($wpwab_settings['multi']['specific_pages_list']) && $wpwab_settings['multi']['specific_pages_list'] !='') ? ($wpwab_settings['multi']['specific_pages_list']) : '';
                    $selected_pages= explode(',', $selected_pages);
                    if (!in_array($post->ID, $selected_pages)) {
                        $specific_page_flag = false;
                    }
                }

                $specific_post_flag = true;
                if (is_singular('post') && isset($wpwab_settings['multi']['posts']) && $wpwab_settings['multi']['posts'] == 'post') {
                    $selected_posts = (isset($wpwab_settings['multi']['specific_posts_list']) && $wpwab_settings['multi']['specific_posts_list'] != '') ? ( $wpwab_settings['multi']['specific_posts_list']) : '';
                    $selected_posts= explode(',', $selected_posts);

                    if (!in_array($post->ID, $selected_posts)) {
                        $specific_post_flag = false;
                    }
                }

                $specific_category_flag = true;
                if (is_singular('post') && isset($wpwab_settings['multi']['category']) && $wpwab_settings['multi']['category'] == 'specific') {
                    $specific_category = (!empty($wpwab_settings['multi']['specific_category'])) ? $wpwab_settings['multi']['specific_category'] : array();
                    $categories = get_the_category($post->ID);
                    $term_ids = wp_list_pluck($categories, 'term_id');

                    if (!array_intersect($specific_category, $term_ids)) {
                        $specific_category_flag = false;
                    } //when found
                }

                if ($specific_page_flag && $specific_post_flag && $specific_category_flag) {
                    include(wpwab_PLUGIN_PATH . 'inc/frontend/multi-contact.php');
                }
            }

        }


        /* Menu overwrite */
        function wpwab_menu_overwrite($items, $args) {
            $wpwab_settings = get_option('wpwab_settings');
            $wpwab_settings = empty($wpwab_settings) ? array() : $wpwab_settings;
            $showbutton = isset($wpwab_settings['showbutton']) ? sanitize_text_field($wpwab_settings['showbutton']) : 'hide';
            $menuposition = isset($wpwab_settings['first']) ? sanitize_text_field($wpwab_settings['first']) : 'hide';
            $showbuttontext = isset($wpwab_settings['showbuttontext']) ? sanitize_text_field($wpwab_settings['showbuttontext']) : 'hide';
            $button_text = isset($wpwab_settings['whatsapp_button_text_menu']) ? sanitize_text_field($wpwab_settings['whatsapp_button_text_menu']) : '';
            // $user_name = isset($wpwab_settings['user_name']) ? sanitize_text_field($wpwab_settings['user_name']) : '';
            $contact_number = isset($wpwab_settings['contact_number']) ? sanitize_text_field($wpwab_settings['contact_number']) : '';

            $button_template = isset($wpwab_settings['wpwab_button_template_menu']) ? sanitize_text_field($wpwab_settings['wpwab_button_template_menu']) : '';
            $menu_list = isset($wpwab_settings['menu_list']) ? $wpwab_settings['menu_list'] : array();
            $whatsapp_format = isset($wpwab_settings['whatsapp_format'])?sanitize_text_field($wpwab_settings['whatsapp_format']): 'web';

            $wpwab_screen_detector = new wpwab_Mobile_Detect();
            if($wpwab_screen_detector->isMobile()){
              $href_link = "whatsapp://send?phone=$contact_number&text=";
            }else{
                if($whatsapp_format == "web"){
                    $href_link = "https://web.whatsapp.com/send?l=en&phone=$contact_number";
                }else{
                    $href_link = "https://api.whatsapp.com/send?phone=$contact_number&text=";
                }
            }

            if ($menuposition == 'first') {
                if ($showbutton == "show") {
                    if ($showbuttontext == "show") {
                        if (in_array($args->theme_location, $menu_list)) {
                            $items = '<li id="wpwab-button-menu-template" class="menu-item wpwab-menu-login wpwab-menu-button-wrap wpwab-button-' . $button_template . '">' . '<div class="wpwab-button-position-left wpwab-text-inner-wrapper wpwab-button-with-text">'
                                    . '<a href="'.$href_link.'"><i class="socicon-whatsapp"></i> ' . $button_text . '</a>'
                                    . '</li>' . $items;
                        }
                    } else {
                        if (in_array($args->theme_location, $menu_list)) {
                            $items = '<li id="wpwab-button-menu-template" class="menu-item wpwab-menu-login wpwab-menu-button-wrap  wpwab-button-' . $button_template . '">' . '<div class="wpwab-button-position-left wpwab-text-inner-wrapper wpwab-button-without-text">'
                                    . '<a href="'.$href_link.'"><i class="socicon-whatsapp"></i></a>'
                                    . '</li>' . $items;
                        }
                    }
                }
            }else
            if ($showbutton == "show") {
                if ($showbuttontext == "show") {
                    if (in_array($args->theme_location, $menu_list)) {
                        $items .= '<li id="wpwab-button-menu-template" class="menu-item wpwab-menu-login wpwab-menu-button-wrap wpwab-button-' . $button_template . '">' . '<div class="wpwab-button-position-left wpwab-text-inner-wrapper wpwab-button-with-text">'
                                . '<a href="'.$href_link.'"><i class="socicon-whatsapp"></i> ' . $button_text . '</a>'
                                . '</li>';
                    }
                } else {
                    if (in_array($args->theme_location, $menu_list)) {
                        $items .= '<li id="wpwab-button-menu-template" class="menu-item wpwab-menu-login
              wpwab-menu-button-wrap wpwab-button-' . $button_template . '">' . '<div class="wpwab-button-position-left wpwab-text-inner-wrapper wpwab-button-without-text">'
                                . '<a href="'.$href_link.'"><i class="socicon-whatsapp"></i></a>'
                                . '</li>';
                    }
                }
            }
            return $items;
        }
        function define_constants() {
            defined('wpwab_PLUGIN_URL') or define('wpwab_PLUGIN_URL', plugin_dir_url(__FILE__));
            defined('wpwab_PLUGIN_PATH') or define('wpwab_PLUGIN_PATH', plugin_dir_path(__FILE__));
            define('wpwab_IMG_DIR', plugin_dir_url(__FILE__) . 'images'); //
            define('wpwab_CSS_DIR', plugin_dir_url(__FILE__) . 'css');
            define('wpwab_JS_DIR', plugin_dir_url(__FILE__) . 'js/');
            defined('wpwab_URL') or define('wpwab_URL', plugin_dir_url(__FILE__));
            defined('wpwab_PLUGIN_VERSION') or define('wpwab_PLUGIN_VERSION', '2.0.3');
            defined('wpwab_TD') or define('wpwab_TD', 'wp-whatsapp-button'); //plugin's text domain
        }

        function wpwab_load_textdomain() {
            load_plugin_textdomain(wpwab_TD, false, basename(dirname(__FILE__)) . '/languages');
        }

        function wpwab_menu() {
            add_menu_page(__('WP WhatsApp Button ', wpwab_TD), __('WP WhatsApp Button', wpwab_TD), 'manage_options', wpwab_TD, array($this, 'whatsapp_setting'), wpwab_IMG_DIR.'/whatsapp.png');
        }

        function whatsapp_setting() {
            include(wpwab_PLUGIN_PATH . 'inc/backend/wpwab-setting.php');
        }

        function wpwab_register_assets() {
            if(isset($_GET['page']) && $_GET['page'] ==='wp-whatsapp-button'){
                wp_enqueue_style('wp-color-picker');
                wp_enqueue_style('wpwab-backend-style', wpwab_CSS_DIR . '/backend/wpwab-backend.css', array(), wpwab_PLUGIN_VERSION);
                wp_enqueue_media();
                wp_enqueue_style('wpwab-fontawesome-style', wpwab_CSS_DIR . '/backend/font-awesome/font-awesome.min.css', false, wpwab_PLUGIN_VERSION);
                wp_enqueue_style('wpwab-inttelinput-style', wpwab_CSS_DIR . '/backend/intlTelInput.css', false, wpwab_PLUGIN_VERSION );
                wp_enqueue_script('wpwab-inttelinput', wpwab_JS_DIR.'/intlTelInput.js', array('jquery'), wpwab_PLUGIN_VERSION );
                wp_enqueue_script('wpwab-backend-script', wpwab_JS_DIR . '/wpwab-backend.js', array('jquery', 'jquery-ui-sortable', 'wpwab-inttelinput', 'wp-color-picker'), wpwab_PLUGIN_VERSION);

                $admin_ajax_nonce = wp_create_nonce('wpwab-admin-ajax-nonce');
                $admin_ajax_object = array('ajax_url' => admin_url('admin-ajax.php'), 
                    'ajax_nonce' => $admin_ajax_nonce,
                    'delete_message'=> __('Confirm Delete?',wpwab_TD));
                wp_localize_script('wpwab-backend-script', 'wpwab_backend_js_params', $admin_ajax_object);
                wp_enqueue_style('wpwab-socicon', wpwab_CSS_DIR . '/backend/socicon/style.css', false, wpwab_PLUGIN_VERSION);
            }
        }

        function wpwab_register_frontend_assets() {
            wp_enqueue_style('wpwab-socicon', wpwab_CSS_DIR . '/frontend/socicon/style.css', false, wpwab_PLUGIN_VERSION);
            wp_enqueue_style('wpwab-frontend', wpwab_CSS_DIR . '/frontend/frontend.css', false, wpwab_PLUGIN_VERSION);
            wp_enqueue_script('wpwab-frontend-script', wpwab_JS_DIR . '/wpwab-frontend.js', array('jquery', 'jquery-ui-sortable'), wpwab_PLUGIN_VERSION);
            
            wp_enqueue_style('wpwab-fontawesome-style', wpwab_CSS_DIR . '/backend/font-awesome/font-awesome.min.css', false, wpwab_PLUGIN_VERSION);
            wp_enqueue_style('google-fonts', '//fonts.googleapis.com/css?family=Raleway|ABeeZee|Aguafina+Script|Open+Sans|Roboto|Roboto+Slab|Lato|Titillium+Web|Source+Sans+Pro|Playfair+Display|Montserrat|Khand|Oswald|Ek+Mukta|Rubik|PT+Sans+Narrow|Poppins|Oxygen:300,400,600,700', array(), wpwab_PLUGIN_VERSION);
        }

        function save_form_settings() {
            if (isset($_POST['wpwab_form_nonce_field']) && wp_verify_nonce($_POST['wpwab_form_nonce_field'], 'wpwab_form_nonce')) {
                $wpwab_settings = $_POST['wpwab_settings'];
                $wpwab_settings['enable_desktop'] = isset($_POST['wpwab_settings']['enable_desktop']) ? 'show' : 'hide';

                if (!empty($_POST['wpwab_settings']['specific_pages_list'])) {
                    $specific_pages = explode( ',', $_POST['wpwab_settings']['specific_pages_list'] );
                }

                if (!empty($_POST['wpwab_settings']['specific_posts_list'])) {
                    $specific_posts = explode(',', $_POST['wpwab_settings']['specific_posts_list']);
                }

                if (!empty($_POST['wpwab_settings']['specific_category'])) {
                    $specific_category = array_map('sanitize_text_field', $_POST['wpwab_settings']['specific_category']);
                }

                // $wpwab_settings = array_map('sanitize_text_field', $wpwab_settings);
                if (isset($specific_pages)) {
                    $wpwab_settings['specific_page'] = $specific_pages;
                }

                if (isset($specific_posts)) {
                    $wpwab_settings['specific_post'] = $specific_posts;
                }

                if (isset($specific_category)) {
                    $wpwab_settings['specific_category'] = $specific_category;
                }

                $wpwab_settings['menu_list'] = isset($_POST['wpwab_settings']['menu_list']) ? $_POST['wpwab_settings']['menu_list'] : array();
                $wpwab_settings = $this->sanitize_array($wpwab_settings);
                update_option('wpwab_settings', $wpwab_settings);
            }

            wp_redirect(admin_url('admin.php?page=wp-whatsapp-button&message=1'));
            exit;
        }
        static function sanitize_array( $array = array(), $sanitize_rule = array() ){
            if ( ! is_array( $array ) || count( $array ) == 0 ) {
                return array();
            }

            foreach ( $array as $k => $v ) {
                if ( ! is_array( $v ) ) {
                    $default_sanitize_rule = (is_numeric( $k )) ? 'text' : 'html';
                    $sanitize_type = isset( $sanitize_rule[ $k ] ) ? $sanitize_rule[ $k ] : $default_sanitize_rule;
                    $array[ $k ] = self:: sanitize_value( $v, $sanitize_type );
                }

                if ( is_array( $v ) ) {
                    $array[ $k ] = self:: sanitize_array( $v, $sanitize_rule );
                }
            }

            return $array;
        }

        static function sanitize_value( $value = '', $sanitize_type = 'text' ){
            switch ( $sanitize_type ) {
             case 'html':
                 $allowed_html = wp_kses_allowed_html( 'post' );
                 return wp_kses( $value, $allowed_html );
                 break;
             default:
                 return sanitize_text_field( $value );
                 break;
            }
        }

        function print_array($array) {
            echo "<pre>";
            print_r($array);
            echo "</pre>";
        }

        function wpwab_shortcode($atts) {
            ob_start();
            include('inc/frontend/wpwab_shortcode.php' );
            $html = ob_get_contents();
            ob_get_clean();
            return $html;
        }

        /** Register Testimonial Widget */
        function wpwab_register_widget() {
            register_widget('wpwab_Widget');
        }

        function wpwab_floating_button() {
            include('inc/backend/pagination/wpwab-post-list.php' );
            die();
        }

        function wpwab_floating_button_pages() {
            include('inc/backend/pagination/wpwab-page-list.php' );
            die();
        }
    }
    new wpwab_Class();
}