# spoki/2.0.9/spoki.php

Spoki – Chat Buttons and WooCommerce Notifications, version 2.0.9. 790 lines.

- Page: https://pluginprobe.com/plugins/spoki/2.0.9/code/spoki.php
- Raw: https://pluginprobe.com/plugins/spoki/2.0.9/raw/spoki.php
- Modified: 2021-05-13T14:04:08+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/spoki/2.0.9/code/spoki.php#L10-L20`.

```php
<?php
/* @wordpress-plugin
 * Plugin Name:       Spoki - Chat Buttons and WooCommerce notifications
 * Description:       Add WhatsApp chat button on your website and send WooCommerce status order notifications using WhatsApp!
 * Version:           2.0.9
 * Author:            Reddoak Srl
 * Author URI:        https://reddoak.com
 * Text Domain:       spoki
 * Domain Path:       /languages
 * License:           GPLv2
 */

define('SPOKI_DIR', plugin_dir_path(__FILE__));
include_once SPOKI_DIR . 'includes/constants.php';
include_once SPOKI_DIR . 'includes/spoki-functions.php';

add_filter( 'cron_schedules', 'add_cron_interval' );
function add_cron_interval( $schedules ) {
	$schedules['every_day'] = array(
		'interval' => 86400,
		'display'  => esc_html__( 'Every day' ), );
	return $schedules;
}

$spoki = Spoki();

function Spoki()
{
	return WpSpoki::instance();
}

final class WpSpoki
{
	protected static $_instance = null;
	private $version = '';
	private $langs = '';
	public $shop = [];

	private $api_plan = SPOKI_BASE_API . "plan/";
	private $api_status = SPOKI_BASE_API . "status/";
	private $api_enable_flex = SPOKI_BASE_API . "enable/";
	private $api_account = SPOKI_BASE_API . "account/";

	public static function instance()
	{
		if (is_null(self::$_instance)) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	private function __construct()
	{
		$data = get_file_data(__FILE__, array('ver' => 'Version', 'langs' => 'Domain Path'));
		$this->version = $data['ver'];
		$this->langs = $data['langs'];
		$this->options = get_option(SPOKI_OPTIONS);
		$this->shop = [
			"name" => isset($this->options['shop_name']) ? $this->options['shop_name'] : get_bloginfo('name'),
			"url" => get_bloginfo('url'),
			"email" => isset($this->options['email']) ? $this->options['email'] : get_bloginfo('admin_email'),
			"language" => isset($this->options['language']) ? $this->options['language'] : get_bloginfo('language'),
			"telephone" => isset($this->options['telephone']) ? $this->options['telephone'] : '',
			"contact_link" => isset($this->options['account_info']['contact_link']) ? $this->options['account_info']['contact_link'] : null,
		];

		add_action('init', 'spoki_update_po_file');
		add_action('admin_menu', array($this, 'add_option_menu'));
		add_filter("plugin_action_links_" . plugin_basename(__FILE__), array($this, 'plugin_settings_link'));
		add_action('wp_enqueue_scripts', array($this, 'add_styles'));
		add_action('admin_enqueue_scripts', array($this, 'add_admin_styles'));
		add_action('updated_option', array($this, 'on_option_added'), 10, 3);
		add_action('spoki_cron_hook', array($this, 'check_secret_status'));

		if ( !wp_next_scheduled( 'spoki_cron_hook' ) ) {
			$this->check_secret_status();
			wp_schedule_event( time(), 'every_day', 'spoki_cron_hook' );
		}

		$this->includes();
		$this->handle_woocommerce();
		$this->render_buttons();
	}

	/**
	 * Include all Spoki required files
	 */
	private function includes()
	{
		require_once SPOKI_DIR . 'includes/spoki-functions.php';
	}

	/**
	 * Get the setting link of the plugin
	 *
	 * @param $links
	 * @return mixed
	 */
	public function plugin_settings_link($links)
	{
		$settings_link = '<a href="options-general.php?page=' . SPOKI_PLUGIN_NAME . '">' . __('Settings', SPOKI_PLUGIN_NAME) . '</a>';
		array_unshift($links, $settings_link);
		return $links;
	}

	/**
	 * Add the Spoki option to the menu
	 */
	public function add_option_menu()
	{
		add_menu_page(
			'Spoki Options',
			'Spoki',
			'manage_options',
			'spoki',
			array($this, 'render_setup_page'),
			plugins_url() . '/' . SPOKI_PLUGIN_NAME . '/assets/images/logo.svg',
			98
		);
		add_action('admin_init', array($this, 'register_option_var'));
	}

	/**
	 * Register the Spoki option
	 */
	public function register_option_var()
	{
		register_setting('wp-spoki-option', SPOKI_OPTIONS);
	}

	/**
	 * Add website spoki styles
	 */
	public function add_styles()
	{
		$styles = ['buttons'];
		foreach ($styles as $style) {
			echo "<style id='spoki-style-$style'>";
			include SPOKI_DIR . "assets/css/$style.css";
			echo "</style>";
		}
	}

	/**
	 * Add admin spoki styles
	 */
	public function add_admin_styles()
	{
		$styles = ['admin.css', 'onboarding.css', 'account-overview.css', 'spoki-overview.css'];

		foreach ($styles as $style) {
			echo "<style>";
			include_once SPOKI_DIR . 'assets/css/' . $style;
			echo "</style>";
		}
	}

	/**
	 * Handle option submit
	 *
	 * @param $option
	 * @param $old_value
	 * @param $value
	 */
	public function on_option_added($option, $old_value, $value)
	{
		if ($option == SPOKI_OPTIONS) {

			/** New Telephone from settings */
			if (isset($value['telephone'])) {
				$this->update_options($value, ["telephone" => spoki_get_formatted_telephone($value['telephone'])]);
			}

			/** Onboarding Without WooCommerce */
			if (isset($value['onboarding']['without_wc'])) {
				$this->update_options($value, [
					"telephone" => spoki_get_formatted_telephone($value['onboarding']['telephone']),
					"onboarding" => null,
				]);
				$url = admin_url('/admin.php?page=' . SPOKI_PLUGIN_NAME . '&tab=' . urlencode('Floating Button'));
				header("Location: {$url}");
				exit;
			}

			/** Onboarding With WooCommerce */
			if (isset($value['onboarding']['with_wc'])) {
				$response = $this->create_spoki_account($value['onboarding']['telephone'], $value['onboarding']['email'], $value['onboarding']['shop_name']);
				if (isset($response['secret']) && isset($response['delivery_url'])) {
					$this->update_options($value, [
						"telephone" => spoki_get_formatted_telephone($value['onboarding']['telephone']),
						"email" => $value['onboarding']['email'],
						"shop_name" => $value['onboarding']['shop_name'],
						"secret" => $response['secret'],
						"delivery_url" => $response['delivery_url'],
						"onboarding" => null,
						"woocommerce" => [
							"order_created" => 1,
							"order_updated" => 1,
							"order_deleted" => 1,
							"order_note_added" => 1,
						],
					]);
					$url = admin_url('/admin.php?page=' . SPOKI_PLUGIN_NAME . '&tab=' . urlencode('WooCommerce'));
					header("Location: {$url}");
					exit;
				}
			}

			/** Settings updated for registered account */
			if (isset($value['is_settings'])) {
				$keys_changed = ($value['secret'] != $old_value['secret']) || ($value['delivery_url'] != $old_value['delivery_url']);

				$shop_name_changed = $value['shop_name'] != $old_value['shop_name'];
				$email_changed = $value['email'] != $old_value['email'];
				$telephone_changed = $value['telephone'] != $old_value['telephone'];
				$contact_link_changed = $value['contact_link'] != $old_value['contact_link'];
				$billing_data_changed = $value['billing_data'] != $old_value['billing_data'];

				if ($shop_name_changed || $email_changed || $telephone_changed || $contact_link_changed || $billing_data_changed) {
					$this->update_spoki_account($value['telephone'], $value['email'], $value['shop_name'], $value['contact_link'], $value['billing_data']);
				}

				if ($keys_changed) {
					$url = admin_url('/admin.php?page=' . SPOKI_PLUGIN_NAME . '&tab=' . urlencode('Welcome'));
					header("Location: {$url}");
					exit;
				}
			}
		}
	}

	/**
	 * Handle WooCommerce features
	 */
	public function handle_woocommerce()
	{
		if (isset($this->options['secret'])) {
			include_once(ABSPATH . 'wp-admin/includes/plugin.php');
			if (is_plugin_active('woocommerce/woocommerce.php')) {
				if (isset($this->options['woocommerce']['order_updated']) && $this->options['woocommerce']['order_updated'] == 1) {
					add_action('woocommerce_order_status_changed', array($this, 'send_woocommerce_order_updated_alert'), 10, 3);
				}
				if (isset($this->options['woocommerce']['order_created']) && $this->options['woocommerce']['order_created'] == 1) {
					add_action('woocommerce_checkout_order_created', array($this, 'send_woocommerce_order_created_alert'), 10, 3);
				}
				if (isset($this->options['woocommerce']['order_deleted']) && $this->options['woocommerce']['order_deleted'] == 1) {
					add_action('woocommerce_cancelled_order', array($this, 'send_woocommerce_order_deleted_alert'), 10, 3);
					add_action('woocommerce_trash_order', array($this, 'send_woocommerce_order_deleted_alert'), 10, 3);
				}
				// TODO
				// if (isset($this->options['woocommerce']['cart_abandoned']) && $this->options['woocommerce']['cart_abandoned'] == 1) {
				// add_action('woocommerce_ajax_added_to_cart', array($this, 'send_woocommerce_order_alert'), 10, 3);
				// }
				if (isset($this->options['woocommerce']['order_note_added']) && $this->options['woocommerce']['order_note_added'] == 1) {
					add_action('woocommerce_order_note_added', array($this, 'send_woocommerce_note_alert'), 10, 2);
				}

				if (isset($this->options['woocommerce']['cart_button_hide_checkout_button_check']) && $this->options['woocommerce']['cart_button_hide_checkout_button_check'] == 1) {
					add_action('woocommerce_proceed_to_checkout', array($this, 'disable_checkout_button'), 1);
				}
			}
		}
		$this->fetch_secret_status();
	}

	/**
	 * Send the Spoki notification for order status updated
	 *
	 * @param $order_get_id
	 */
	public function send_woocommerce_order_updated_alert($order_get_id)
	{
		$this->send_woocommerce_order_alert($order_get_id, 'order.updated');
	}

	/**
	 * Send the Spoki notification for order created
	 *
	 * @param $order_get_id
	 */
	public function send_woocommerce_order_created_alert($order_get_id)
	{
		$this->send_woocommerce_order_alert($order_get_id, 'order.created');
	}

	/**
	 * Send the Spoki notification for order deleted
	 *
	 * @param $order_get_id
	 */
	public function send_woocommerce_order_deleted_alert($order_get_id)
	{
		$this->send_woocommerce_order_alert($order_get_id, 'order.updated');
	}

	/**
	 * Send the Spoki notification for order status
	 *
	 * @param $order_get_id
	 */
	public function send_woocommerce_order_alert($order_get_id, $target)
	{
		$order = wc_get_order($order_get_id);
		$shop = ["shop" => $this->shop];
		$order_data = (isset($order) && false != $order ? $order->get_data() : ["id" => $order_get_id]);
		$this->spoki_send(array_merge($order_data, $shop), $target);
	}

	/**
	 * Send the Spoki notification for tracking number
	 *
	 * @param $id
	 * @param $order
	 */
	public function send_woocommerce_note_alert($id, $order)
	{
		$comment = get_comment($id);

		if (isset($comment->comment_content)) {
			$is_gls_tracking = substr(strtolower($comment->comment_content), 0, 4) == '[gls';
			$is_user_tracking = substr(strtolower($comment->comment_content), 0, 10) == '[tracking]';

			/** Send the message only if it is a tracking order note */
			if ($comment->comment_type == 'order_note' && ($is_gls_tracking || $is_user_tracking)) {
				$order_data = $order->get_data();
				$shop = ["shop" => $this->shop];
				$note = ["note" => $comment];
				$this->spoki_send(array_merge($order_data, $shop, $note), 'order.tracking');
			}
		}
	}

	/**
	 * Send the Spoki notification
	 *
	 * @param $data
	 * @return bool
	 */
	private function spoki_send($data, $topic): bool
	{
		$request_params = array(
			"headers" => array(
				"Authorization" => $this->options['secret'],
				"language" => $this->shop['language'],
				"X-Wc-Webhook-Topic" => $topic,
			),
			"body" => wp_json_encode($data)
		);
		$response = wp_remote_post($this->options['delivery_url'], $request_params);
		$code = wp_remote_retrieve_response_code($response);
		return $code == 200;
	}

	/**
	 * Create a new Spoki Free account
	 *
	 * @param $telephone
	 * @param $email
	 * @param $shop_name
	 * @return array
	 */
	private function create_spoki_account($telephone, $email, $shop_name): array
	{
		$request_params = array(
			"headers" => array("Authorization" => $this->options['secret'], "language" => $this->shop['language']),
			"body" => [
				"phone" => $telephone,
				"email" => $email,
				"name" => $shop_name,
			],
		);

		$response = wp_remote_post($this->api_enable_flex, $request_params);
		$code = wp_remote_retrieve_response_code($response);

		if ($code >= 200 && $code < 300) {
			$data = json_decode(wp_remote_retrieve_body($response), true);
			return [
				"secret" => isset($data['secret']) ? $data['secret'] : null,
				"delivery_url" => isset($data['delivery_url']) ? $data['delivery_url'] : null,
			];
		}
		return [];
	}


	/**
	 * Update a Spoki account
	 *
	 * @param $telephone
	 * @param $email
	 * @param $shop_name
	 * @param $contact_link
	 * @param $billing_data
	 */
	private function update_spoki_account($telephone, $email, $shop_name, $contact_link, $billing_data = [])
	{
		$request_params = array(
			"headers" => array("Authorization" => $this->options['secret'], "language" => $this->shop['language']),
			"body" => [
				"phone" => $telephone ?: '',
				"email" => $email ?: '',
				"name" => $shop_name ?: '',
				"contact_link" => $contact_link ?: '',
				"zip_code" => $billing_data['zip_code'] ?: '',
				"province" => $billing_data['province'] ?: '',
				"country" => $billing_data['country'] ?: '',
				"route" => $billing_data['route'] ?: '',
				"city" => $billing_data['city'] ?: '',
				"vat_number" => $billing_data['vat_number'] ?: '',
				"vat_name" => $billing_data['vat_name'] ?: '',
				"c_f" => $billing_data['c_f'] ?: '',
				"pec" => $billing_data['pec'] ?: '',
				"sid" => $billing_data['sid'] ?: '',
			],
		);
		wp_remote_post($this->api_account, $request_params);
	}

	/**
	 * Fetch and update the account_info
	 */
	public function fetch_account_info()
	{
		$request_params = array("headers" => array("Authorization" => $this->options['secret'], "language" => $this->shop['language']));
		$response = wp_remote_get($this->api_plan, $request_params);
		$this->update_options(get_option(SPOKI_OPTIONS), ["account_info" => json_decode(wp_remote_retrieve_body($response), true)]);
	}

	/**
	 * Check the status of the spoki keys
	 *
	 * @return array|WP_Error
	 */
	public function check_spoki_status()
	{
		$secret = isset($this->options['secret']) ? $this->options['secret'] : null;
		$request_params = array("headers" => array("Authorization" => $secret, "language" => $this->shop['language']));
		$response = wp_remote_get($this->api_status, $request_params);
		return $response;
	}

	/**
	 * Render the admin setup page
	 */
	public function render_setup_page()
	{
		require_once SPOKI_DIR . 'includes/page-setup.php';
	}

	/**
	 * Render the WhatsApp buttons in the website
	 */
	public function render_buttons()
	{
		$has_fixed_support_button = isset($this->options['buttons']['fixed_support_button_check']) && $this->options['buttons']['fixed_support_button_check'] == 1;
		$has_product_item_listing_button = isset($this->options['woocommerce']['product_item_listing_button_check']) && $this->options['woocommerce']['product_item_listing_button_check'] == 1;
		$has_cart_button = isset($this->options['woocommerce']['cart_button_check']) && $this->options['woocommerce']['cart_button_check'] == 1;
		$has_single_product_button = isset($this->options['woocommerce']['single_product_button_check']) && $this->options['woocommerce']['single_product_button_check'] == 1;

		// Floating Button
		if ($has_fixed_support_button) {
			add_action('wp_footer', array($this, 'render_floating_button'), 1);
		}

		// Product Item Listing Button
		if ($has_product_item_listing_button) {
			add_action('woocommerce_after_shop_loop_item', array($this, 'render_product_item_listing_button'), 20);
		}

		// Cart Page Button
		if ($has_cart_button) {
			add_action('woocommerce_after_cart_totals', array($this, 'render_cart_button'), 20);
		}

		// Single Product Page Button
		if ($has_single_product_button) {
			$position = isset($this->options['woocommerce']['single_product_button_position']) ? $this->options['woocommerce']['single_product_button_position'] : 'after_atc';
			switch ($position) {
				case 'under_atc':
					add_action('woocommerce_after_add_to_cart_form', array($this, 'render_single_product_button'), 5);
					break;
				case 'after_shortdesc':
					add_action('woocommerce_before_add_to_cart_form', array($this, 'render_single_product_button'), 5);
					break;
				case 'after_atc':
				default:
					add_action('woocommerce_after_add_to_cart_button', array($this, 'render_single_product_button'), 5);
					break;
			}
		}

		if ($has_fixed_support_button || $has_product_item_listing_button || $has_cart_button || $has_single_product_button) {
			add_action('wp_footer', array($this, 'render_shadowed_buttons'));
		}
	}

	public function disable_checkout_button() {
		remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
	}

	/**
	 *
	 */
	public function render_shadowed_buttons()
	{
		echo "<script>(() => Array.from(document.getElementsByClassName('spoki-shadowed-button')).forEach(el => {
    		const content = document.importNode(el, true);
    		const shadowRoot = el.attachShadow({mode: 'closed'});
    		el.innerHTML = '';
    		const style = document.createElement('style');
    		style.innerHTML = document.getElementById('spoki-style-buttons').innerHTML.replace(/(\\r\\n|\\n|\\r)/gm, '');
    		shadowRoot.appendChild(style);
    		shadowRoot.appendChild(content.firstChild);
		}))();</script>";
	}

	/**
	 * Render the WhatsApp FAB on the website in every page
	 */
	public function render_floating_button()
	{
		if (isset($this->options['telephone']) && $this->options['telephone'] != '') {
			$phone = $this->options['telephone'];
			$text = $this->options['buttons']['fixed_support_button_text'];
			$position = $this->options['buttons']['fixed_support_button_position'] == 'Left' ? 'left' : 'right';
			$border_type = isset($this->options['buttons']['fixed_support_button_border']) ? $this->options['buttons']['fixed_support_button_border'] : 'circle';
			$border_radius = '50%';
			if ($border_type == 'squared') {
				$border_radius = '0';
			} elseif ($border_type == 'rounded') {
				$border_radius = '8px';
			}
			$color = isset($this->options['buttons']['fixed_support_button_color']) ? $this->options['buttons']['fixed_support_button_color'] : '#23D366';
			$bottom_space = isset($this->options['buttons']['fixed_support_button_bottom_space']) ? $this->options['buttons']['fixed_support_button_bottom_space'] : '12';
			$side_space = isset($this->options['buttons']['fixed_support_button_side_space']) ? $this->options['buttons']['fixed_support_button_side_space'] : '12';
			$wa_link = "https://api.whatsapp.com/send/?phone=$phone&text=" . urlencode($text);
			echo "<div id='spoki-shadowed-fixed-button' class='spoki-shadowed-button'><div id='spoki-fixed-btn' style='$position:{$side_space}px;bottom:{$bottom_space}px;'><a id='spoki-chat-link' style='background-color:{$color};border-radius:$border_radius;' href='$wa_link' target='_blank'><img alt='WhatsApp logo' src='https://app.spoki.it/static/png/whatsapp-logo-squared.png'/></a></div></div>";
		}
	}

	/**
	 * Render the product button for every product in shop page
	 */
	public function render_product_item_listing_button()
	{
		global $product;
		$phone = $this->options['telephone'];
		$cta = __("Request support on WhatsApp", "spoki");
		if (isset($this->options['woocommerce']['product_item_listing_button_cta']) && !empty($this->options['woocommerce']['product_item_listing_button_cta'])) {
			$cta = $this->options['woocommerce']['product_item_listing_button_cta'];
		}
		$message = __("Hi, I want to buy:", "spoki");
		if (isset($this->options['woocommerce']['product_item_listing_button_text']) && !empty($this->options['woocommerce']['product_item_listing_button_text'])) {
			$message = $this->options['woocommerce']['product_item_listing_button_text'];
		}
		$color = isset($this->options['woocommerce']['product_item_listing_button_color']) ? $this->options['woocommerce']['product_item_listing_button_color'] : '#23D366';
		$margin_top = isset($this->options['woocommerce']['product_item_listing_button_margin_top']) ? $this->options['woocommerce']['product_item_listing_button_margin_top'] : '4';
		$margin_bottom = isset($this->options['woocommerce']['product_item_listing_button_margin_bottom']) ? $this->options['woocommerce']['product_item_listing_button_margin_bottom'] : '4';
		$border_type = isset($this->options['woocommerce']['product_item_listing_button_border']) ? $this->options['woocommerce']['product_item_listing_button_border'] : 'rounded';

		$this->render_product_button($product, $phone, $cta, $message, $color, $border_type, $margin_top, $margin_bottom);
	}

	/**
	 * Render the button in the cart page
	 */
	public function render_cart_button()
	{
		global $product;
		$phone = $this->options['telephone'];
		$cta = __("Order via WhatsApp", "spoki");
		if (isset($this->options['woocommerce']['cart_button_cta']) && !empty($this->options['woocommerce']['cart_button_cta'])) {
			$cta = $this->options['woocommerce']['cart_button_cta'];
		}
		$message = __("Hi, I want to buy:", "spoki");
		if (isset($this->options['woocommerce']['cart_button_text']) && !empty($this->options['woocommerce']['cart_button_text'])) {
			$message = $this->options['woocommerce']['cart_button_text'];
		}
		$color = isset($this->options['woocommerce']['cart_button_color']) ? $this->options['woocommerce']['cart_button_color'] : '#23D366';
		$margin_top = isset($this->options['woocommerce']['cart_button_margin_top']) ? $this->options['woocommerce']['cart_button_margin_top'] : '4';
		$margin_bottom = isset($this->options['woocommerce']['cart_button_margin_bottom']) ? $this->options['woocommerce']['cart_button_margin_bottom'] : '4';

		$final_message = urlencode($message);

		$products = WC()->cart->get_cart();

		foreach ($products as $item) {
			$product_id = $item['product_id'];
			$qty = $item['quantity'];
			$product = wc_get_product($product_id);
			$product_url = $product->get_permalink();
			$product_title = $product->get_name();
			$price = wp_strip_all_tags(wc_price(wc_get_price_including_tax($product)));
			$encoded_title = urlencode($product_title);
			$encoded_product_url = urlencode($product_url);
			$final_message .= "%0D%0A%0D%0A(ID:%20$product_id)%20*$encoded_title*%20$price%20x$qty%0D%0A$encoded_product_url";
		}

		$href = "https://api.whatsapp.com/send?phone=$phone&text=$final_message";
		$title = "$cta";
		$class = 'button spoki-button size-4';
		$border_type = isset($this->options['woocommerce']['cart_button_border']) ? $this->options['woocommerce']['cart_button_border'] : 'rounded';

		$border_radius = '16px';
		if ($border_type == 'squared') {
			$border_radius = '0';
		}

		echo "<div class='spoki-shadowed-button'><div class='spoki-button-relative' style='margin-top:{$margin_top}px;margin-bottom:{$margin_bottom}px'><a href='$href' target='_blank' title='$title' class='$class' style='background-color:$color;border-radius:$border_radius'><img class='spoki-wa-icon' alt='WhatsApp logo' src='https://app.spoki.it/static/png/whatsapp-logo-squared.png'/><span>$cta</span></a></div></div>";
	}

	/**
	 * Render the button in the product page
	 */
	public function render_single_product_button()
	{
		global $product;
		$phone = $this->options['telephone'];
		$cta = __("Request support on WhatsApp", "spoki");
		if (isset($this->options['woocommerce']['single_product_button_cta']) && !empty($this->options['woocommerce']['single_product_button_cta'])) {
			$cta = $this->options['woocommerce']['single_product_button_cta'];
		}
		$message = __("Hi, I want to buy:", "spoki");
		if (isset($this->options['woocommerce']['single_product_button_text']) && !empty($this->options['woocommerce']['single_product_button_text'])) {
			$message = $this->options['woocommerce']['single_product_button_text'];
		}
		$position = isset($this->options['woocommerce']['single_product_button_position']) ? $this->options['woocommerce']['single_product_button_position'] : 'after_atc';
		$color = isset($this->options['woocommerce']['single_product_button_color']) ? $this->options['woocommerce']['single_product_button_color'] : '#23D366';
		$margin_top = isset($this->options['woocommerce']['single_product_button_margin_top']) ? $this->options['woocommerce']['single_product_button_margin_top'] : '4';
		$margin_bottom = isset($this->options['woocommerce']['single_product_button_margin_bottom']) ? $this->options['woocommerce']['single_product_button_margin_bottom'] : '4';
		$border_type = isset($this->options['woocommerce']['single_product_button_border']) ? $this->options['woocommerce']['single_product_button_border'] : 'rounded';

		$this->render_product_button($product, $phone, $cta, $message, $color, $border_type, $margin_top, $margin_bottom, $position);
	}

	/**
	 * Render the button of a product
	 *
	 * @param $product
	 * @param $phone
	 * @param $cta
	 * @param $message
	 * @param null $position
	 */
	public function render_product_button($product, $phone, $cta, $message, $color = '#23D366', $border_type = 'rounded', $margin_top = '4', $margin_bottom = '4', $position = null)
	{
		$product_url = $product->get_permalink();
		$product_title = $product->get_name();
		$product_id = $product->get_id();

		$class = sprintf('button spoki-button product_type_%s', $product->get_type());
		if (isset($position)) {
			$class .= " size-2 $position";
		} else {
			$class .= " size-4";
		}
		$price = wp_strip_all_tags(wc_price(wc_get_price_including_tax($product)));

		$border_radius = '16px';
		if ($border_type == 'squared') {
			$border_radius = '0';
		}

		$encoded_message = urlencode($message);
		$encoded_title = urlencode($product_title);
		$encoded_product_url = urlencode($product_url);

		$final_message = "$encoded_message%0D%0A%0D%0A(ID:%20$product_id)%20*$encoded_title*%20$price%0D%0A$encoded_product_url";
		$href = "https://api.whatsapp.com/send?phone=$phone&text=$final_message";
		$title = "$cta $product_title";

		echo "<div class='spoki-shadowed-button'><div class='spoki-button-relative' style='margin-top:{$margin_top}px;margin-bottom:{$margin_bottom}px;'><a href='$href' target='_blank' title='$title' class='$class' style='background-color:$color;border-radius:$border_radius'><img class='spoki-wa-icon' alt='WhatsApp logo' src='https://app.spoki.it/static/png/whatsapp-logo-squared.png'/><span>$cta</span></a></div></div>";
	}

	/**
	 * Get the link to change plan
	 *
	 * @param $is_upgrade
	 * @return string
	 */
	public function get_plan_link($is_upgrade): string
	{
		$url = $this->shop['language'] == 'it-IT' ? 'https://spoki.it/spoki-flex-acquista-pacchetti-flex/?' : 'https://spoki.it/spoki-flex-acquista-pacchetti-flex/spoki-flex-packages/?';

		if (isset($this->options['account_info']['upgrade_url']) ? $this->options['account_info']['upgrade_url'] : '') {
			$url = $this->options['account_info']['upgrade_url'];
		}
		if ($is_upgrade) {
			$url .= '&is_upgrade=true';
		}
		return $url;
	}

	/**
	 * Update Spoki options
	 *
	 * @param $current_options
	 * @param $new_options
	 */
	private function update_options($current_options, $new_options)
	{
		$c_options = is_string($current_options) ? [] : $current_options;
		if (isset($new_options["woocommerce"])) {
			$woocommerce = array_merge($c_options["woocommerce"], $new_options["woocommerce"]);
			$new_options["woocommerce"] = $woocommerce;
		}
		update_option(SPOKI_OPTIONS, array_merge($c_options, $new_options));
		$this->options = get_option(SPOKI_OPTIONS);
	}

	/**
	 * Check the secret status periodically
	 */
	public function check_secret_status()
	{
		$this->fetch_secret_status(true);
	}

	/**
	 * Fetch the status of the Spoki keys
	 */
	public function fetch_secret_status($force_checking = false)
	{
		$response = null;
		if ($force_checking) {
			$response = $this->check_spoki_status();
		}

		if (!isset($this->options['secret']) || $this->options['secret'] == '' || !isset($this->options['delivery_url']) || $this->options['delivery_url'] == '') {
			$this->update_options(get_option(SPOKI_OPTIONS), ["secret_status" => [
				'secret' => isset($this->options['secret']) ? $this->options['secret'] : '',
				'delivery_url' => isset($this->options['delivery_url']) ? $this->options['delivery_url'] : '',
				'code' => 0,
				'message' => ''
			]]);
		} else if (!isset($this->options['secret_status']) || $this->options['secret_status']['code'] != 200 || $this->options['secret'] != $this->options['secret_status']['secret'] || $this->options['delivery_url'] != $this->options['secret_status']['delivery_url']) {
			if (!$force_checking) {
				$response = $this->check_spoki_status();
			}
			$this->update_options(get_option(SPOKI_OPTIONS), ["secret_status" => [
				'secret' => isset($this->options['secret']) ? $this->options['secret'] : '',
				'delivery_url' => isset($this->options['delivery_url']) ? $this->options['delivery_url'] : '',
				'code' => wp_remote_retrieve_response_code($response),
				'message' => wp_remote_retrieve_response_message($response)
			]]);
		}
	}
}

/**
 * Executed on activation of the plugin
 */
function spoki_activation() {
	// Don't do redirects when multiple plugins are bulk activated
	if (
		( isset( $_REQUEST['action'] ) && 'activate-selected' === $_REQUEST['action'] ) &&
		( isset( $_POST['checked'] ) && count( $_POST['checked'] ) > 1 ) ) {
		return;
	}
	add_option( 'spoki_activation_redirect', wp_get_current_user()->ID );
}

/**
 * Redirects the user after plugin activation.
 */
function spoki_activation_redirect() {
	// Make sure it's the correct user
	if ( intval( get_option( 'spoki_activation_redirect', false ) ) === wp_get_current_user()->ID ) {
		// Make sure we don't redirect again after this one
		delete_option( 'spoki_activation_redirect' );
		wp_safe_redirect( admin_url( '/options-general.php?page=' . SPOKI_PLUGIN_NAME ) );
		exit;
	}
}

/**
 * Executed on deactivation of the plugin
 */
function spoki_deactivation()
{
	//	delete_option(SPOKI_OPTIONS);
	$timestamp = wp_next_scheduled( 'spoki_cron_hook' );
	wp_unschedule_event( $timestamp, 'spoki_cron_hook' );
}

register_deactivation_hook( __FILE__, 'spoki_deactivation' );
// register_activation_hook( __FILE__, 'spoki_activation' );
// add_action( 'admin_init', 'spoki_activation_redirect' );

```
