<?php
if (!defined( 'CANVAS_DIR' )) {
	die();
}
require_once(dirname(__FILE__) . '/canvas_views.class.php' );
require_once(CANVAS_DIR . 'core/push/canvas-notifications.class.php' );

class CanvasAdmin {

	public static $admin_pages = array(
		'options' => 'Theme Options',
		'editor' => 'CSS Editor',
		'push' => 'Push Notifications',
		'login' => 'Login & Subscriptions'
	);
	public static $admin_notifications = array(
		'notifications' => 'Notifications'
	);
	public static $welcome_steps = array( 'details', 'success',  'scheduled' );
	private static $admin_screens = array();
	private static $push_screen = '';
	private static $welcome_screen = '';

	public static  function init() {
		add_action( 'admin_menu', array( 'CanvasAdmin', 'on_admin_menu' ) );
		add_action( 'current_screen', array( 'CanvasAdmin', 'current_screen' ) );
		add_action( 'admin_init', array( 'CanvasAdmin', 'on_admin_init' ), 1 );
		add_action( 'admin_head', array( 'CanvasViews', 'on_admin_head' ), 1 );
		add_action( 'wp_ajax_canvas_welcome', array( 'CanvasAdmin', 'ajax_welcome' ) );
		add_action( 'wp_ajax_canvas_save_theme', array( 'CanvasAdmin', 'save_theme' ) );
		add_action( 'wp_ajax_canvas_schedule_dismiss', array( 'CanvasAdmin', 'schedule_dismiss' ) );

		if (Canvas::push_keys_set()) {
			add_action( 'wp_ajax_canvas_attachment_content', array( 'CanvasNotifications', 'attachment_content' ) );
			add_action( 'wp_ajax_canvas_notification_check_duplicate', array( 'CanvasNotifications', 'notification_check_duplicate' ) );
			add_action( 'wp_ajax_canvas_notification_manual_send', array( 'CanvasNotifications', 'notification_manual_send' ) );
			add_action( 'wp_ajax_canvas_notification_history', array( 'CanvasNotifications', 'notification_history' ) );
		}
	}

	public static function on_admin_init() {
		// Redirect to plugin's page on plugin activation
		if ( get_transient( '__canvas_activation_redirect' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
			delete_transient( '__canvas_activation_redirect' );
			if ( isset( $_GET[ 'activate-multi' ] ) ) {
				return;
			}

			wp_safe_redirect( add_query_arg( array( 'page' => Canvas::$slug ), get_admin_url( NULL, 'admin.php' ) ) );
		}
		//
		if (is_admin() && current_user_can( 'administrator' )) {
			if (!Canvas::get_option( 'schedule_dismiss' )) {
				add_action( 'admin_notices', array( 'CanvasViews', 'add_schedule_demo' ));
			}
		}
	}

	public static function on_admin_menu() {
		// show basic settings
		$image = "data:image/svg+xml;base64, ";

		if (Canvas::is_not_welcome_screen()) {
			self::$admin_screens[] = add_submenu_page( Canvas::$slug, 'Configuration', 'Configuration', "activate_plugins", Canvas::$slug, array( 'CanvasAdmin', 'main_menu' ) );
			self::$admin_screens[] = add_menu_page( 'Canvas', 'Canvas', 'activate_plugins', Canvas::$slug, array( 'CanvasAdmin', 'main_menu'), $image, '25.31415926' );

			// Show manual notifications only if app id and key set
			if (Canvas::push_keys_set()) {
				self::$push_screen = add_submenu_page( Canvas::$slug, 'Push Notification', 'Push Notifications', "publish_posts", Canvas::$slug . '_push', array( 'CanvasAdmin', 'push_menu' ) );
				self::$admin_screens[] = self::$push_screen;
			}
			do_action( 'canvas_on_menu', Canvas::$slug);
		} else {
			self::$welcome_screen = add_menu_page( 'Canvas', 'Canvas', 'activate_plugins', Canvas::$slug, array( 'CanvasAdmin', 'welcome_menu'), $image, '25.31415926' );
			self::$admin_screens[] = self::$welcome_screen;
		}
	}

	public static function current_screen() {
		if (is_admin()) {
			$screen = get_current_screen();
			if ($screen instanceof WP_Screen && in_array($screen->id, self::$admin_screens)) {
				self::add_scripts(self::$push_screen == $screen->id, self::$welcome_screen == $screen->id);
			}
		}
	}

	public static function main_menu() {
		// for old Wordpress versions
		if (!function_exists( 'set_current_screen' )) {
			self::add_scripts();
		}

		do_action( 'canvas_main_menu', Canvas::$slug);
		$active_tab = (isset($_GET[ 'tab' ]) && isset(CanvasAdmin::$admin_pages[$_GET[ 'tab' ]])) ? $_GET[ 'tab' ] :  'options';
		// save settings
		$updated = false;
		if ( count( $_POST ) && check_admin_referer( 'form-settings-' . $active_tab ) && !isset($_POST[ 'configured' ])) {
			switch ($active_tab) {
				case 'options':
					Canvas::set_theme(!empty( $_POST[ 'different_theme_for_app' ] ), $_POST[ 'theme' ] );
					break;

				case 'editor':
					update_option( 'canvas_editor_css', (isset($_POST[ 'canvas_editor_css' ]) ? $_POST[ 'canvas_editor_css' ] : '' ));
					break;

				case 'push':
					Canvas::set_option( 'push_app_id', sanitize_text_field( $_POST[ 'canvas_push_app_id' ] ) );
					Canvas::set_option( 'push_key', sanitize_text_field( $_POST[ 'canvas_push_key' ] ) );
					Canvas::set_option( 'push_auto_enabled', !empty( $_POST[ 'canvas_push_auto_enabled' ] ) );

					Canvas::set_option( 'bp_private_messages', !empty( $_POST[ 'canvas_bp_private_messages' ] ) );
					Canvas::set_option( 'bp_other_notitications', !empty( $_POST[ 'canvas_bp_other_notitications' ] ) );
					Canvas::set_option( 'bp_global_messages', !empty( $_POST[ 'canvas_bp_global_messages' ] ) );
					Canvas::set_option( 'bp_friends', !empty( $_POST[ 'canvas_bp_friends' ] ) );

					// Categories and taxonomies
					CanvasAdmin::push_notification_taxonomies_clear();
					CanvasAdmin::push_notification_taxonomies_clear( 'taxonomy' );
					if ( isset( $_POST[ 'canvas_push_categories' ] ) ) {
						if ( is_array( $_POST[ 'canvas_push_categories' ] ) ) {
							$cat_list = array();
							$tax_list = array();
							foreach ( $_POST[ 'canvas_push_categories' ] as $categoryID ) {
								if (0 === strpos($categoryID, 'tax:' )) {
									$tax_list[] = absint(str_replace( 'tax:', '', $categoryID));
								} else {
									$cat_list[] = $categoryID;
								}
							}
							CanvasAdmin::push_notification_taxonomies_set($cat_list);
							CanvasAdmin::push_notification_taxonomies_set($tax_list, 'taxonomy' );
						}
					}

					// Post types
					$include_post_types = '';
					if ( isset( $_POST['canvas_push_post_types'] ) && count( $_POST[ 'canvas_push_post_types' ] ) ) {
						$include_post_types = implode( ",", $_POST[ 'canvas_push_post_types' ] );
					}
					Canvas::set_option( 'push_post_types', sanitize_text_field( $include_post_types ) );
					Canvas::set_option( 'push_auto_use_cat', isset( $_POST[ 'canvas_push_auto_use_cat' ] ) );

					$push_auto_tags = array();
					if (!empty($_POST[ 'canvas_push_auto_tags' ])) {
						$push_auto_tags = explode( ',', $_POST[ 'canvas_push_auto_tags' ] );
						foreach ($push_auto_tags as $key => $value) {
							$push_auto_tags[$key] = strtolower(trim($value));
						}
					}
					Canvas::set_option( 'push_auto_tags', $push_auto_tags);
					Canvas::set_option( 'push_include_image', isset( $_POST[ 'canvas_push_include_image' ] ) ? '1' : '0' );

					Canvas::set_option( 'push_log_enable', isset( $_POST[ 'canvas_push_log_enable' ] ) );
					break;

				case 'login':
					Canvas::set_option( 'login_enabled', !empty($_POST[ 'canvas_login_enabled' ]) ? 1 : 0);
					Canvas::set_option( 'login_hide_back', !empty($_POST[ 'canvas_login_hide_back' ]) ? 1 : 0);
					Canvas::set_option( 'login_hide_register', !empty($_POST[ 'canvas_login_hide_register' ]) ? 1 : 0);
					Canvas::set_option( 'login_hide_remind', !empty($_POST[ 'canvas_login_hide_remind' ]) ? 1 : 0);
					Canvas::set_option( 'editor_login_css', (isset($_POST[ 'canvas_editor_login_css' ]) ? $_POST[ 'canvas_editor_login_css' ] : '' ));
					break;
			}
			$updated = true;
		}
		// show settings form
		CanvasViews::view( 'settings-' . $active_tab, array(
			'active_tab' => $active_tab,
			'updated' => $updated,
			'show_sidebar' => true,
			'tabs' => CanvasAdmin::$admin_pages,
			'tab_path' => 'admin.php?page=canvas&tab=',
			'show_form' => true,
		) );
		self::track_user_event( 'view_settings-' . $active_tab);
	}

	public static function push_menu() {
		// for old Wordpress versions
		if (!function_exists( 'set_current_screen' )) {
			self::add_scripts(true);
		}
		do_action( 'canvas_push_menu', Canvas::$slug);

		// show settings form
		$active_tab = 'notifications';
		CanvasViews::view( 'push-notifications', array(
			'active_tab' => $active_tab,
			'tabs' => CanvasAdmin::$admin_notifications,
			'tab_path' => 'admin.php?page=canvas_push&tab=',
			'show_sidebar' => false
		) );
		self::track_user_event( 'view_push-' . $active_tab);
	}

	public static function welcome_menu() {
		// for old Wordpress versions
		if (!function_exists( 'set_current_screen' )) {
			self::add_scripts(false, true);
		}

		// current tab
		$active_step = Canvas::get_option( 'welcome_step', CanvasAdmin::$welcome_steps[0] );
		if (isset($_GET[ 'step' ]) && in_array($_GET[ 'step' ], CanvasAdmin::$welcome_steps)) {
			$active_step = $_GET[ 'step' ];
		}
		if (!in_array($active_step, CanvasAdmin::$welcome_steps)) {
			$active_step = CanvasAdmin::$welcome_steps[0];
		}
		// proceed form
		switch ($active_step) {
			case CanvasAdmin::$welcome_steps[0]: break;
			case CanvasAdmin::$welcome_steps[1]:
				if (isset($_GET[ 'open' ])) {
					self::track_user_event( 'welcome_request', array( 'intercom' ));
				}
				break;
			case CanvasAdmin::$welcome_steps[2]:
				if (!empty($_GET[ 'id' ])&& !empty($_GET[ 'time' ])&& !empty($_GET[ 'timezone' ])) {
					// save data from Appointlet
					Canvas::set_option( 'welcome-time', array( 'id' => sanitize_text_field($_GET[ 'id' ]), 'time' =>  urldecode($_GET[ 'time' ]), 'timezone' => urldecode($_GET[ 'timezone' ])));
				}
				break;

		}
		Canvas::set_option( 'welcome_step', $active_step);
		// show welcome form
		CanvasViews::view( $active_step, array(
			'step' => $active_step,
			'show_sidebar' => false,
			'base_path' => 'admin.php?page=canvas&tab=',
			'show_form' => false,
			'welcome' => true,
		) );
		self::track_user_event( 'view_welcome-' . $active_step);
	}

	public static function add_scripts($add_google = false, $add_welcome = false) {
		wp_enqueue_media();

		wp_register_script( 'areyousure', CANVAS_URL . 'assets/libs/jquery.are-you-sure.js', 'jquery', CANVAS_PLUGIN_VERSION, true );
		wp_register_script( 'jquerychosen', CANVAS_URL . 'assets/libs/chosen/chosen.jquery.min.js', 'jquery', CANVAS_PLUGIN_VERSION, true );
		wp_register_script( 'notify-js', CANVAS_URL . 'assets/libs/notify/notify.min.js', array( 'jquery' ), false, CANVAS_PLUGIN_VERSION );
		wp_register_script( 'canvas-admin-js', CANVAS_URL . 'assets/js/admin.js', array( 'jquery', 'jquerychosen' ,'areyousure', 'notify-js' ), CANVAS_PLUGIN_VERSION, true );
		if ($add_google) {
			wp_register_script( 'google_chart', 'https://www.google.com/jsapi' );
			wp_enqueue_script( 'google_chart' );
		}
		if ($add_welcome) {
			wp_register_script( 'jquery-validate', CANVAS_URL . 'assets/libs/jquery.validate.min.js', array( 'jquery' ), false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_script( 'jquery-validate' );
			wp_register_script( 'ladda-spin-js', CANVAS_URL . 'assets/libs/ladda/spin.min.js', false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_script( 'ladda-spin-js' );
			wp_register_script( 'ladda-js', CANVAS_URL . 'assets/libs/ladda/ladda.min.js', false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_script( 'ladda-js' );
			wp_register_script( 'sweetalert-js', CANVAS_URL . 'assets/libs/sweetalert/sweetalert.min.js', array( 'jquery' ), false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_script( 'sweetalert-js' );
			wp_register_script( 'canvas-welcome', CANVAS_URL . 'assets/js/welcome.js', false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_script( 'canvas-welcome' );

			wp_register_style( 'canvas-welcome-css', CANVAS_URL . "assets/css/welcome.css", false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_style( 'canvas-welcome-css' );
			wp_register_style( 'ladda-css', CANVAS_URL . "assets/libs/ladda/ladda-themeless.min.css", false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_style( 'ladda-css' );
			wp_register_style( 'sweetalert-css', CANVAS_URL . "assets/libs/sweetalert/sweetalert.css", false, CANVAS_PLUGIN_VERSION );
			wp_enqueue_style( "sweetalert-css" );
		}
		wp_enqueue_script( 'areyousure' );
		wp_enqueue_script( 'jquerychosen' );
		wp_enqueue_script( 'notify-js' );
		wp_enqueue_script( 'canvas-admin-js' );

		wp_register_style( 'canvas-css', CANVAS_URL . 'assets/css/admin.css', false, CANVAS_PLUGIN_VERSION );
		wp_register_style( 'jquerychosen-css', CANVAS_URL . 'assets/libs/chosen/chosen.css', false, CANVAS_PLUGIN_VERSION );
		wp_enqueue_style( 'jquerychosen-css' );
		wp_enqueue_style( 'canvas-css' );
	}

	/**
	* Save options from welcome screen
	*
	*/
	public static function ajax_welcome() {
		$email = $_POST['ml_email'];
		$name = !empty($_POST['ml_name']) ? $_POST['ml_name'] : '';
		$site = !empty($_POST['ml_site']) ? $_POST['ml_site'] : '';
		$company = !empty($_POST['ml_company']) ? $_POST['ml_company'] : '';
		$phone = !empty($_POST['ml_app_type']) ? $_POST['ml_phone'] : '';
		$phone = !empty($_POST['ml_phone']) ? $_POST['ml_phone'] : '';
		$message = !empty($_POST['ml_message']) ? $_POST['ml_message'] : '';
		$pricing = empty($_POST['ml_pricing']) ? 0 : 1;
		$newsletter = empty($_POST['ml_newsletter']) ? 0 : 1;
		$intercom = empty($_POST['ml_intercom']) ? 0 : 1;
		$type = !empty($_POST['ml_apptype']) ? $_POST['ml_apptype'] : '';
		$ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

		Canvas::set_option( 'init_name', sanitize_text_field( $name ) );
		Canvas::set_option( 'init_email', sanitize_text_field( $email ) );
		Canvas::set_option( 'init_site', sanitize_text_field( $site ) );
		Canvas::set_option( 'init_company', sanitize_text_field( $company ) );
		Canvas::set_option( 'init_apptype', sanitize_text_field( $type ) );
		Canvas::set_option( 'init_phone', sanitize_text_field( $phone ) );
		Canvas::set_option( 'init_message', sanitize_textarea_field( $message ) );
		Canvas::set_option( 'init_newsletter', $newsletter );
		Canvas::set_option( 'welcome', '1' );

		$url = 'https://www.mobiloud.com/demo_plugin/';
		$params = array(
			'email' => $email,
			'name' => $name,
			'type' => $type,
			'site' => $site,
			'company_name' => $company,
			'phone' => $phone,
			'questions' => $message,
			'pricing' => $pricing,
			'newsletter' => $newsletter,
			'ip' => $ip,
			'utm_source' => 'canvas-plugin'
		);

		$result = wp_remote_post( $url, array( 'body' => $params, 'timeout' => 15, 'sslverify' => false)); // call endpoint
		// success?
		if (!is_wp_error($result) && is_array($result) && !empty($result[ 'body' ])) {
			$answer = json_decode($result[ 'body' ], true);
			if (is_array($answer) && !empty($answer[ 'success' ]) && is_array($answer[ 'data' ])) {
				$timezone_check = true;
				if (isset($answer[ 'data' ][ 'timezone' ]) && !$answer[ 'data' ][ 'timezone' ]) {
					$timezone_check = false;
				}
				Canvas::set_option( 'welcome_timezone', $timezone_check );
				$next_step = admin_url( 'admin.php?page=canvas&step=' . CanvasAdmin::$welcome_steps[1] . '&open=true' );

				wp_send_json_success( array(
					'url' => $next_step,
					'timezone_check' => $timezone_check,
				) );
				die();
			}
		}

		wp_send_json_error();
		die();
	}

	/**
	* Save options from Theme Options tab
	*
	*/
	public static function save_theme() {
		Canvas::set_theme(!empty( $_POST[ 'use' ] ), $_POST[ 'theme' ] );
		die('Ok');
	}

	/**
	* Return name of log file
	*
	*/
	public static function get_push_log_name( $web_path = false ) {
		$filename = Canvas::get_option( 'push_log_name' );
		if (empty($filename)) {
			$site = str_replace(array( 'https://', 'http://', '/', ':' ), array( '', '', '_', '' ), get_site_url());
			$filename = $site . '-canvaspush' .  rand(10000000, 99999999) . '.txt';
			Canvas::set_option( 'push_log_name', $filename);
		}
		$paths = wp_upload_dir();
		if ($web_path) {
			return $paths[ 'baseurl' ] . '/' . $filename;
		} else {
			return $paths[ 'basedir' ] . '/' . $filename;
		}
	}

	public static function run_db_install() {
		global $wpdb;
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

		$table_name = $wpdb->prefix . "canvas_notifications";
		if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
			$sql = "CREATE TABLE " . $table_name . " (
			id bigint(11) NOT NULL AUTO_INCREMENT,
			time bigint(11) DEFAULT '0' NOT NULL,
			post_id bigint(11),
			url VARCHAR(255) NULL DEFAULT NULL,
			msg blob,
			android varchar(1) NOT NULL,
			ios varchar(1) NOT NULL,
			tags blob,
			UNIQUE KEY id (id),
			KEY post_id (post_id)
			);";

			dbDelta( $sql );
		}
	}

	/**
	* Get list of categories or taxonomies allowed for notifications
	*
	* @param string $taxonomy
	*/
	static public function push_notification_taxonomies_get($taxonomy = 'category' ) {
		return Canvas::get_option( 'push_list_' . $taxonomy, array());
	}

	/**
	* Clear list of categories or taxonomies allowed for notifications
	*
	* @param string $taxonomy
	*/
	static private function push_notification_taxonomies_clear($taxonomy = 'category' ) {
		Canvas::set_option( 'push_list_' . $taxonomy, array());
	}

	/**
	* Save list of categories or taxonomies allowed for notifications
	*
	* @param array $taxonomies_list
	* @param string $taxonomy
	*/
	static private function push_notification_taxonomies_set( $taxonomies_list, $taxonomy = 'category'  ) {
		Canvas::set_option( 'push_list_' . $taxonomy, $taxonomies_list);
	}
	/**
	* Check if currently on plugin page
	*
	*/
	static public function using_canvas() {
		return isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'canvas', 'canvas_push' ) ) !== false;
	}

	public static function track_user_event( $event ) {
		CanvasViews::track_intercom($event);
	}

	public static function schedule_dismiss() {
		Canvas::set_option( 'schedule_dismiss', time());
		echo 'OK';
		die();
	}
}