<?php
/*
  Plugin Name: Advanced Uptime Monitor Extension
  Plugin URI: https://mainwp.com
  Description: MainWP Extension for real-time uptime monitoring.
  Version: 5.0.1
  Author: MainWP
  Author URI: https://mainwp.com
  Documentation URI: https://mainwp.com/help/category/mainwp-extensions/advanced-uptime-monitor/
*/

if ( ! defined( 'MAINWP_AUM_PLUGIN_FILE' ) ) {
	define( 'MAINWP_AUM_PLUGIN_FILE', __FILE__ );
}

if ( ! defined( 'MVC_AUM_PLUGIN_PATH' ) ) {
	define( 'MVC_AUM_PLUGIN_PATH', dirname( __FILE__ ) . '/' );
}

if ( ! defined( 'MAINWP_AUM_API_LIMIT_PER_PAGE' ) ) {
	define( 'MAINWP_AUM_API_LIMIT_PER_PAGE', 50 );
}

class Advanced_Uptime_Monitor_Extension {

	/**
	 * @var instance
	 */
	private static $instance = null;

	/**
	 * @var plugin_name
	 */
	public $plugin_name = 'Advanced Uptime Monitor Extension';

	/**
	 * @var plugin_handle
	 */
	public $plugin_handle = 'advanced-uptime-monitor-extension';

	/**
	 * @var plugin_dir
	 */
	public $plugin_dir;

	/**
	 * @var plugin_url
	 */
	protected $plugin_url;

	/**
	 * @var plugin_admin
	 */
	protected $plugin_admin = '';

	/**
	 * @var option
	 */
	protected $option;

	/**
	 * @var option_handle
	 */
	protected $option_handle = 'advanced_uptime_monitor_extension';

	/**
	 * @var api_url
	 */

	/**
	 * @var message_info
	 */
	public $message_info = array();

	/**
	 * @var plugin_slug
	 */
	private $plugin_slug;

	public $monitor_types = array();

	public $uptime_data_sites = null;

	static function get_install() {
		if ( null === self::$instance ) {
			self::$instance = new Advanced_Uptime_Monitor_Extension();
		}
		return self::$instance;
	}

	public function __construct() {
		global $wpdb;
		$this->monitor_types = array( '1' => 'HTTP(s)', '2' => 'Keyword', '3' => 'Ping', '4' => 'TCP Ports' );
		error_reporting( E_ALL ^ E_NOTICE );
		$this->plugin_dir = plugin_dir_path( __FILE__ );
		$this->plugin_url = plugin_dir_url( __FILE__ );
		$this->plugin_slug = plugin_basename( __FILE__ );

		if ( is_admin() ) {
			// Load admin functionality
			require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
			$loader = new MvcAdminLoader();
			add_filter( 'plugin_row_meta', array( &$this, 'plugin_row_meta' ), 10, 2 );
			add_action( 'admin_menu', array( $loader, 'add_menu_pages' ) );
			add_action( 'admin_menu', array( $loader, 'add_settings_pages' ) );
			add_action( 'plugins_loaded', array( $loader, 'add_admin_ajax_routes' ) );
			add_action( 'init', array( $loader, 'init' ) );
			add_action( 'widgets_init', array( $loader, 'register_widgets' ) );
			add_filter( 'post_type_link', array( $loader, 'filter_post_link' ), 10, 2 );
			add_filter( 'mainwp-sitestable-getcolumns', array( $this, 'sitestable_getcolumns' ), 10 );
			add_filter( 'mainwp-sitestable-item', array( $this, 'sitestable_item' ), 10 );
		}

		add_filter( 'mainwp_aum_get_data', array( &$this, 'aum_get_data' ), 10, 3 ); // ok
		// Load global functionality
		add_action( 'admin_init', array( &$this, 'admin_init' ) );
		add_action( 'init', array( &$this, 'localization' ) );
		require_once MVC_AUM_PLUGIN_PATH . 'app/classes/uptimerobot-db.php';
		UptimeRobot_DB::get_instance()->install();
		require_once MVC_AUM_PLUGIN_PATH . 'app/classes/uptimerobot.php';

		add_action( 'admin_enqueue_scripts', array( $this, 'uptime_robot_monitors_enqueue_style' ) );
		add_action( 'admin_head', array( $this, 'uptime_robot_monitors_add_head' ) );

		$this->option = get_option( $this->option_handle );
	}

	function uptime_robot_monitors_enqueue_style() {
		wp_register_style( 'mainwp-aum', plugins_url( 'css/mainwp-aum.css', __FILE__ ) , array(), '4.0' );
		wp_enqueue_style( 'mainwp-aum' );
		wp_register_script( 'mainwp-aum', plugins_url( 'js/mainwp-aum.js', __FILE__ ), array(), '4.0' );
		wp_enqueue_script( 'mainwp-aum' );

		$urm_plugin_url = plugins_url( '', __FILE__ );

		wp_localize_script( 'mainwp-aum', 'urm_plugin_url', $urm_plugin_url );
    if ( isset( $_GET['page'] ) && $_GET['page'] == 'Extensions-Advanced-Uptime-Monitor-Extension' ) {
      wp_enqueue_script('mainwp-aum-chart', plugins_url( 'js/loader.js', __FILE__ ));
    }
	}

	function uptime_robot_monitors_add_head() {
		echo "<script>var siteurl = '" . esc_html( home_url() ) . "';\n</script>";
	}

	public function admin_init() {

		if ( isset( $_POST['aum_monitors_per_page'] ) ) {
			$per_page = intval($_POST['aum_monitors_per_page']);
			if ( !in_array($per_page, array( 10, 20, 30, 40, 50 )) )
				$per_page = 10;
			update_option('mainwp_aum_setting_monitors_per_page', $per_page);
		}

	}

	public function localization() {
		load_plugin_textdomain( 'advanced-uptime-monitor-extension', false,  dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
	}

	public function sitestable_getcolumns( $columns ) {
		$columns['aum_status'] = __( 'Uptime Status', 'advanced-uptime-monitor-extension' );
		return $columns;
	}

	public function sitestable_item( $item ) {
		$site_url = $item['url'];
		if( $this->uptime_data_sites === null ) {
			$this->uptime_data_sites = $this->get_uptime_data();
		}
        $site_url = str_replace(array('https://www.', 'http://www.', 'https://', 'http://', 'www', '/'), array('', '', '', '', '', ''), $site_url);
		if (isset($this->uptime_data_sites[$site_url])) {
			$uptime = $this->uptime_data_sites[$site_url];
			$item['aum_status'] = $this->render_status_bar( $uptime['status'], $uptime['alltimeuptimeratio'] );
            //$item['aum_status'] = $this->render_ratio_bar( $uptime['status'], $uptime['alltimeuptimeratio'] );
		}
		return $item;
	}

	public function get_uptime_data() {
		$api_key = $this->option['api_key'];
		if ( empty( $api_key ) ) {
			return array();
		}

		require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
		new MvcAdminLoader();
		// to fix bug Fatal error: Class 'UptimeMonitor' not found
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_monitor.php';
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_url.php';

		$utime_mo = new UptimeMonitor();
		$monitor = $utime_mo->find_one(array(
			'selects' => array( 'monitor_id' ),
			'conditions' => array(
			'monitor_api_key' => $api_key,
			),
		));

		if ( ! $monitor ) {
			return array();
		}

		$utime_url = new UptimeUrl();
		$urls = $utime_url->find( array(
      	'conditions' => array(
				'monitor_id' => $monitor->monitor_id
			),
		) );

		if ( ! $urls ) {
			return array();
		}

		$uptime_data = array();

		foreach($urls as $url) {
			$url_address = $url->url_address;
      $url_address = str_replace( array( 'https://www.', 'http://www.', 'https://', 'http://', 'www', '/'), array( '', '', '', '', '', '' ), $url_address );
			$uptime_data[$url_address] = array('status' => $url->status, 'alltimeuptimeratio' => $url->alltimeuptimeratio);
		}

		return $uptime_data;

	}

	public function plugin_row_meta( $plugin_meta, $plugin_file ) {
		if ( $this->plugin_slug != $plugin_file ) {
			return $plugin_meta;
		}

		$slug = basename($plugin_file, ".php");
		$api_data = get_option( $slug. '_APIManAdder');
		if (!is_array($api_data) || !isset($api_data['activated_key']) || $api_data['activated_key'] != 'Activated' || !isset($api_data['api_key']) || empty($api_data['api_key']) ) {
			return $plugin_meta;
		}

		$plugin_meta[] = '<a href="?do=checkUpgrade" title="Check for updates.">' . __( 'Check for updates now' , 'advanced-uptime-monitor-extension' ) . '</a>';
		return $plugin_meta;
	}

	public function option_page() {
		$saved = false;
		if ( isset( $_POST['aum_submit'] ) &&  isset( $_POST['nonce'] ) && wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'aum_nonce_option' ) ) {
			$saved = $this->save_option();
		}

		$current_tab = '';

		if ( isset( $_GET['tab'] ) ) {
			if ( $_GET['tab'] == 'monitors' ) {
				$current_tab = 'monitors';
			} else if ( $_GET['tab'] == 'settings' ) {
				$current_tab = 'settings';
			} else if ( $_GET['tab'] == 'recent-events' ) {
				$current_tab = 'recent-events';
			}
		} else {
			$current_tab = 'monitors';
		}

		?>
		<div class="ui labeled icon inverted menu mainwp-sub-submenu" id="mainwp-advanced-uptime-monitor-menu">
	    <a href="admin.php?page=Extensions-Advanced-Uptime-Monitor-Extension&tab=monitors" class="item <?php echo ( $current_tab == 'monitors' ? 'active' : '' ); ?>"><i class="eye icon"></i> <?php _e( 'Monitoring', 'mainwp-spinner' ); ?></a>
			<a href="admin.php?page=Extensions-Advanced-Uptime-Monitor-Extension&tab=recent-events" class="item <?php echo ( $current_tab == 'recent-events' ? 'active' : '' ); ?>"><i class="history icon"></i> <?php _e( 'Recent Events', 'mainwp-spinner' ); ?></a>
	    <a href="admin.php?page=Extensions-Advanced-Uptime-Monitor-Extension&tab=settings" class="item <?php echo ( $current_tab == 'settings' ? 'active' : '' ); ?>" data-tab="mainwp-advanced-uptime-monitor-settings"><i class="cog icon"></i> <?php _e( 'Settings', 'mainwp-spinner' ); ?></a>
	  </div>

		<!-- Monitors -->
    <?php if ( $current_tab == 'monitors' || $current_tab == '' ) : ?>
    <div id="mainwp-advanced-uptime-monitor-monitors-tab">
      <?php self::renderMonitors(); ?>
    </div>
    <?php endif; ?>

		<!-- Recent Events -->
    <?php if ( $current_tab == 'recent-events' ) : ?>
    <div class="ui segment" id="mainwp-advanced-uptime-monitor-recent-events">
      <?php self::renderLastEvents(); ?>
    </div>
    <?php endif; ?>

		<!-- Settings -->
    <?php if ( $current_tab == 'settings' ) : ?>
    <div class="ui alt segment" id="mainwp-advanced-uptime-monitor-settings">
			<div class="mainwp-main-content">
				<?php
				if ( ! empty( $this->option['uptime_robot_message'] ) ) {
					?>
					<div class="ui red message"><i class="close icon"></i><?php echo esc_html( $this->option['uptime_robot_message'] ); ?></div>
					<?php
				}

				if ( $saved ) {
					if ( isset( $_POST['submit_btn'] ) ) {
						?>
						<div class="ui green message"><i class="close icon"></i><?php echo __( 'Settings saved successfully.', 'advanced-uptime-monitor-extension' ); ?></div>
						<?php
					} else {
						?>
						<div class="ui green message"><i class="close icon"></i><?php echo __( 'Data reloaded successfully.', 'advanced-uptime-monitor-extension' ); ?></div>
						<?php
					}
				}
				?>
	      <?php self::renderUptimeMonitorSettings(); ?>
			</div>
			<div class="mainwp-side-content">
				<p><?php _e( 'MainWP Advanced Uptime Monitor is an extension that works with the Uptime Robot service that checks your websites sites every 5 minutes, 24 hours a day, 7 days a week. In the case your site is not loading, it makes few more checks in next 3 minutes to make sure that site is down. If the site is still down, it will notify you immediately.', 'advanced-uptime-monitor-extension' ); ?></p>
				<p><?php _e( 'Not sure how to get the Uptime Robot API key?', 'advanced-uptime-monitor-extension' ); ?> <a href="https://mainwp.com/help/docs/advanced-uptime-monitor/connect-your-uptime-robot-account/create-uptime-robot-api-key/" target="_blank"><?php _e( 'Click here to find out!', 'advanced-uptime-monitor-extension' ); ?></a></p>
				<a href="https://mainwp.com/help/docs/advanced-uptime-monitor/" class="ui big green fluid button" target="_blank"><?php _e( 'Extension Documentation', 'advanced-uptime-monitor-extension' ); ?></a>
			</div>
			<div class="ui clearing hidden divider"></div>
    </div>
    <?php endif; ?>

		<div class="ui modal" id="mainwp-create-edit-monitor-modal">
			<div class="header"></div>
			<div class="scrolling content"></div>
			<div class="actions">
				<div class="ui cancel button"><?php _e( 'Close', 'advanced-uptime-monitor-extension' ); ?></div>
			</div>
		</div>
		<?php
	}

	public static function renderUptimeMonitorSettings() {
		$option = self::get_install()->option;
		$api_key_aum = $option['api_key'];
		?>
		<form method="POST" action="admin.php?page=Extensions-Advanced-Uptime-Monitor-Extension&tab=settings" class="ui form">
			<h3 class="ui dividing header"><?php _e( 'Uptime Robot Settings', 'advanced-uptime-monitor-extension' ); ?></h3>
			<div class="ui grid field">
				<label class="six wide column middle aligned"><?php _e( 'Uptime Robot API Key', 'advanced-uptime-monitor-extension' ); ?></label>
				<div class="ten wide column">
					<input type="text" name="api_key" id="api_key" value="<?php echo esc_attr( $api_key_aum ); ?>" />
				</div>
			</div>
			<div class="ui grid field">
				<label class="six wide column middle aligned"><?php _e( 'Default alert contact', 'advanced-uptime-monitor-extension' ); ?></label>
				<div class="ten wide column">
					<?php
					if ( is_array( $option['list_notification_contact'] ) && count( $option['list_notification_contact'] ) > 0 ) {
					?>
						<select name="select_default_noti_contact" class="ui dropdown">
							<?php
							foreach ( $option['list_notification_contact'] as $key => $val ) {
								if ( $option['uptime_default_notification_contact_id'] == $key ) {
									echo '<option value="' . esc_attr( $key ) . '" selected="selected">' . esc_html( $val ) . '</option>';
								} else {
									echo '<option value="' . esc_attr( $key ) . '" >' . esc_html( $val ) . '</option>';
								}
							}
							?>
						</select>
					<?php
					} else {
						echo __( 'No items found! Make sure to submit your Uptime Robot API key first.','advanced-uptime-monitor-extension' );
					}
					?>
				</div>
			</div>
			<div class="ui grid field">
				<label class="six wide column middle aligned"><?php _e( 'Timezone', 'advanced-uptime-monitor-extension' ); ?></label>
				<div class="ten wide column">
					<?php
					if ( isset( $option['api_timezone'] ) && !empty( $option['api_timezone'] ) ) {
						Advanced_Uptime_Monitor_Extension::get_install()->display_timezone( $option['api_timezone'] );
					}
					?>
				</div>
			</div>
			<div class="ui divider"></div>
			<input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'aum_nonce_option' ) ?>" />
			<input type="hidden" name="aum_submit" value="1"/>
			<input type="submit" name="submit_btn" class="ui big green right floated button" value="<?php esc_attr_e( 'Save Settings', 'advanced-uptime-monitor-extension' ); ?>" />
			<input type="button" name="aum_monitor_reload" id="aum_monitor_reload" class="ui green basic big button <?php echo empty( $api_key_aum ) ? 'disabled' : ''; ?>" value="<?php esc_attr_e( 'Reload Uptime Robot Data', 'advanced-uptime-monitor-extension' ); ?>" />
		</form>
	<?php
	}

	public static function renderMonitors() {
		$option = self::get_install()->option;
		$api_key_aum = $option['api_key'];
		$monitor_id = 0;
		if ( ! empty( $api_key_aum ) ) {
			require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_monitor.php';
			$UM = new UptimeMonitor();
			$mo = $UM->get_user_main_monitor();
			if ( ! empty( $mo ) ) {
				$monitor_id = $mo->monitor_id;
			}
		}

		$overal_uptime = UptimeRobot_DB::get_instance()->get_overal_uptime_monitor();
		$overal_status = isset( $overal_uptime['overal_status'] ) ? $overal_uptime['overal_status'] : array();

		if ( empty( $api_key_aum ) ) {
		?>
		<div class="ui padded segment">
			<div class="ui hidden divider"></div>
			<h2 class="ui icon header">
			  <i class="info circle icon"></i>
			  <div class="content">
			    <?php echo __( 'No Uptime Robot Account Connected', 'advanced-uptime-monitor-extension' ); ?>
			    <div class="sub header"><?php _e( 'To add new monitors or load existing ones, please enter your Uptime Robot API key in the Uptime Robot Settings.', 'advanced-uptime-monitor-extension' ); ?></div>
					<div class="ui hidden divider"></div>
					<a class="ui big green button" href="admin.php?page=Extensions-Advanced-Uptime-Monitor-Extension&tab=settings"><?php echo __( 'Uptime Robot Settings', 'advanced-uptime-monitor-extension' ); ?></a>
			  </div>
			</h2>
			<div class="ui hidden divider"></div>
		</div>
		<?php } else { ?>
			<div class="mainwp-actions-bar">
				<div class="ui grid">
					<div class="ui two column row">
						<div class="column">
							<input type="hidden" id="mainwp_aum_extension_display_dashboard_nonce" value="<?php echo wp_create_nonce( 'aum_nonce_display_dashboard' ); ?>"/>
					    <div id="aum_monitor_action" class="actions ui mini form">
							<select name="monitor_action" class="ui mini dropdown">
							<option value="-1" selected="selected"><?php _e( 'Bulk Actions', 'advanced-uptime-monitor-extension' ); ?></option>
							<option value="start" ><?php _e( 'Start', 'advanced-uptime-monitor-extension' ); ?></option>
							<option value="pause" ><?php _e( 'Pause', 'advanced-uptime-monitor-extension' ); ?></option>
							<option value="delete"><?php _e( 'Delete', 'advanced-uptime-monitor-extension' ); ?></option>
							</select>
				        <input type="button" href="javascript:void(0)" onclick="urm_apply_check(this, event)" name="doaction" id="doaction" class="ui mini button" value="<?php _e( 'Apply', 'advanced-uptime-monitor-extension' ); ?>">
					    </div>
		        </div>
						<div class="right aligned column">
							<a onclick="urm_add_new_monitor_button( this, event, <?php echo intval( $monitor_id ); ?>, '<?php echo wp_create_nonce( 'aum_nonce_url_form' ); ?>')" class="ui green button" ><?php _e( 'Create New Monitor', 'advanced-uptime-monitor-extension' ); ?></a>
							<button id="aum_auto_add_sites_monitor" disabled="disabled" class="ui basic green button"><?php _e( 'Create Monitors for All Sites', 'advanced-uptime-monitor-extension' ); ?></button>
		        </div>
	        </div>
				</div>
			</div>

			<div class="ui green inverted center aligned padded segment" style="margin-bottom: 0;">
				<div class="ui five column grid">
					<div class="row">
						<div class="column">
							<div class="ui inverted horizontal statistic">
						    <div class="value"><?php echo $overal_status['up']; ?></div>
						    <div class="label">UP</div>
						  </div>
						</div>
						<div class="column">
							<div class="ui inverted horizontal statistic">
						    <div class="value"><?php echo $overal_status['down']; ?></div>
						    <div class="label">DOWN</div>
						  </div>
						</div>
						<div class="column">
							<div class="ui inverted horizontal statistic">
						    <div class="value"><?php echo $overal_status['not_checked']; ?></div>
						    <div class="label">PENDING</div>
						  </div>
						</div>
						<div class="column">
							<div class="ui inverted horizontal statistic">
						    <div class="value"><?php echo $overal_status['seems_down']; ?></div>
						    <div class="label">SEEMS DOWN</div>
						  </div>
						</div>
						<div class="column">
							<div class="ui inverted horizontal statistic">
						    <div class="value"><?php echo $overal_status['paused']; ?></div>
						    <div class="label">PAUSED</div>
						  </div>
						</div>
					</div>
				</div>
			</div>
			<div class="ui green segment">
				<div class="ui active inverted dimmer" id="aum_mainwp_uptime_monitor_loading">
			    <div class="ui text loader"><?php _e( 'Loading', 'advanced-uptime-monitor-extension' ); ?></div>
			  </div>
				<div id="mainwp-advanced-uptime-monitor-monitors"></div>
			</div>
		<?php } ?>

		<?php

		$get_page = isset( $_GET['get_page'] ) && $_GET['get_page'] > 0 ? $_GET['get_page'] : 1;

		if ( ! empty( $option['api_key'] ) ) {
		?>
		<script type="text/javascript">
		// Load monitors
		jQuery( document ).ready( function () {

			mainwp_aum_option_page_get_monitors = function( pPage ) {
				jQuery.ajax( {
					url: ajaxurl,
					type: "POST",
					data: {
						action: 'admin_uptime_monitors_option_page',
						get_page: pPage,
						wp_nonce: '<?php echo wp_create_nonce( 'aum_nonce_option_page' ); ?>'
					},
					error: function () {
						jQuery( '#aum_mainwp_uptime_monitor_loading' ).hide();
						jQuery( '#mainwp-advanced-uptime-monitor-monitors' ).html( '<div class="ui yellow message">' + __( 'Request timed out. Please, try again later.' ) + '</div>' ).show();
					},
					success: function (response) {
						jQuery( '#aum_mainwp_uptime_monitor_loading' ).hide();
						jQuery( '#mainwp-advanced-uptime-monitor-monitors' ).html( response ).show();
						jQuery('#aum_auto_add_sites_monitor').removeAttr('disabled');

						jQuery('#mainwp_aum_monitor_select_page').dropdown();
						jQuery('#mainwp_aum_monitor_select_page').dropdown('setting', 'onChange', function( val ){
							mainwp_aum_option_page_get_monitors(val);
						});

						if (typeof mainwp_table_check_columns_init === 'function')
							mainwp_table_check_columns_init(); // to fix select all checkboxs for ajax table

					},
					timeout: 20000
				});
			};

			mainwp_aum_option_page_get_monitors( <?php echo intval($get_page ); ?> );

		});
		// Auto create monitors
	  jQuery( '#aum_auto_add_sites_monitor' ).click( function ( event ) {
	    if ( jQuery( this ).prop( 'disabled' ) ) {
	      return false;
	    }

	    if ( !confirm( 'Are you sure?' ) )
	      return false;

	    jQuery( this ).attr( 'disabled', 'disabled' );

		aum_popup_box( 'auto_add_sites', false, '<?php echo wp_create_nonce( 'aum_nonce_auto_add_sites' ); ?>', 'Creating monitors...', null, true );

//	    jQuery.ajax( {
//				url: ajaxurl,
//				type: "POST",
//				data: {
//					action: 'admin_uptime_monitors_auto_add_sites',
//					wp_nonce: '<?php echo wp_create_nonce( 'aum_nonce_auto_add_sites' ); ?>'
//				},
//				error: function () {
//					jQuery( '#aum_mainwp_uptime_monitor_loading' ).hide();
//					jQuery( '#mainwp-advanced-uptime-monitor-monitors' ).html( '<div class="ui yellow message">' + __( 'Request timed out. Please, try again later.' ) + '</div>' ).show();
//				},
//				success: function ( response ) {
//					jQuery( '#aum_mainwp_uptime_monitor_loading' ).hide();
//					jQuery( '#mainwp-advanced-uptime-monitor-monitors' ).html( response ).show();
//				},
//				timeout: 20000
//			});
	  });
		</script>
		<?php
		}
	}

  public function renderLastEvents() {
  	$option = self::get_install()->option;
    $api_key = $option['api_key'];
		if ( empty( $api_key ) ) {
			?>
			<h2 class="ui icon header">
			  <i class="info circle icon"></i>
			  <div class="content">
			    <?php echo __( 'No Monitors Created', 'advanced-uptime-monitor-extension' ); ?>
			    <div class="sub header"><?php _e( 'To add new monitors or load existing ones, please enter your Uptime Robot API key in the Uptime Robot Settings.', 'advanced-uptime-monitor-extension' ); ?></div>
					<div class="ui hidden divider"></div>
					<a class="ui big green button" href="admin.php?page=Extensions-Advanced-Uptime-Monitor-Extension&tab=settings"><?php echo __( 'Uptime Robot Settings', 'advanced-uptime-monitor-extension' ); ?></a>
			  </div>
			</h2>
			<?php
		}

		require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
		new MvcAdminLoader();

		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_monitor.php';
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_url.php';

    $utime_url = new UptimeUrl();
		$urls = $utime_url->find();
    $urls_info = array();
    if ( $urls ) {
      foreach( $urls as $url ) {
        $urls_info[$url->url_uptime_monitor_id] = array(
          'url' => $url->url_address,
          'friendly_name' => $url->url_friendly_name
        );
      }
    }

    if ( empty( $urls_info ) ) {
			return;
		}

    $event_statuses = UptimeRobot_DB::get_event_statuses();

    $UMS = new UptimeStats();
    $order_by = "event_datetime_gmt DESC";
    $limit = "LIMIT 100";
    $stats = $UMS->get_events( '', $order_by, $limit );

    if ( $stats ) {
      $option = self::get_install()->option;
      $offset_time = 0;
      if ( isset( $option[ 'api_timezone' ] ) && is_array( $option[ 'api_timezone' ] ) ) {
        $offset_time = $option[ 'api_timezone' ][ 'offset_time' ];
        $offset_time = $offset_time * 60 * 60;
      }
    ?>
		<table id="mainwp-aum-recent-events-table" class="ui single line table">
			<thead>
				<tr>
					<th class="collapsing"><?php _e( 'Event', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Monitor', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Date / Time', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Details', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Duration', 'advanced-uptime-monitor-extension' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $stats as $event ) : ?>
					<?php
					$status = '';
					if ( $event->monitor_type == '-1' ) {
						$type = $event->type;
						$status = ucfirst( $event_statuses[ $type ] );
					} else {
						$type = $event->monitor_type;
						switch ( $type ) {
							case '0':
								$status = __( 'Paused', 'advanced-uptime-monitor-extension' );
								break;
							case '1':
								$status = __( 'Started', 'advanced-uptime-monitor-extension' );
						}
					}
					if ( ! empty( $urls_info[$event->monitor_id]['friendly_name'] ) ) {
						?>
						<tr>
							<td>
								<?php
								switch ( $status ) {
									case 'Started':
										echo  '<span class="ui center aligned mini fluid yellow label">Started</span>';
										break;
									case 'Up':
										echo '<span class="ui center aligned mini fluid green label">Up</span>';
										break;
									case 'Paused':
										echo '<span class="ui center aligned mini fluid grey label">Paused</span>';
										break;
									case 'Down':
										echo '<span class="ui center aligned mini fluid red label">Down</span>';
										break;
								}
								?>
							</td>
							<td><?php echo isset($urls_info[$event->monitor_id]) ? esc_html($urls_info[$event->monitor_id]['friendly_name']) : ''; ?></td>
							<td>
							<?php
								$datetime = strtotime( $event->event_datetime_gmt ) + $offset_time;
								$datetime = Advanced_Uptime_Monitor_Extension::get_install()->format_timestamp($datetime);
								echo $datetime;
							?>
							</td>
							<td>
									<?php
									switch ( $status ) {
											case 'Started':
													echo '<span class="play bold">' . __( 'Started', 'advanced-uptime-monitor-extension' ) . '</span>';
													break;
											case 'Up':
													echo '<span class="positive bold">' . __( 'Ok', 'advanced-uptime-monitor-extension' ). ' (' . $event->code . ')</span>';
													break;
											case 'Paused':
													echo '<span class="pause bold">' . __( 'Paused', 'advanced-uptime-monitor-extension' ). '</span>';
													break;
											case 'Down':
													echo '<span class="negative bold">' . $event->detail. '</span>';
													break;
									}
									?>
							</td>
							<td>
								<?php
								$duration = $event->duration;
								$hrs = floor($duration / 3600);
								$mins =  floor(($duration - $hrs * 3600) / 60);
								echo $hrs . ' hrs, ' . $mins . ' mins' ;
								?>
							</td>
						</tr>
						<?php
					}
					?>
				<?php endforeach; ?>
			</tbody>
			<tfoot>
				<tr>
					<th><?php _e( 'Event', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Monitor', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Date / Time', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Details', 'advanced-uptime-monitor-extension' ); ?></th>
					<th><?php _e( 'Duration', 'advanced-uptime-monitor-extension' ); ?></th>
				</tr>
			</tfoot>
		</table>
		<script type="text/javascript">
		jQuery( '#mainwp-aum-recent-events-table' ).DataTable( {
			"columnDefs": [ { "orderable": false, "targets": "no-sort" } ],
			"order": [ [ 1, "asc" ] ],
			"stateSave":  true,
			"language": { "emptyTable": "No events recorded yet." }
		} );
		</script>
		<?php
    }
  }

	public function display_timezone($timezone) {
		if ( ! is_array( $timezone ) )
			return;
		$offset_time = $timezone['offset_time'];
		$out = $timezone['text'] ." (GMT";

		if ( $offset_time >= 0 )
			$out .= "+";
		else {
			$out .= "-";
			$offset_time *= -1;
		}

		$hour = floor( $offset_time );
		$min = ( $offset_time - $hour ) * 60;
		$format = '%1$02d:%2$02d:00)';
		$out .= sprintf( $format, $hour, $min );
		echo $out;
	}


  function get_ratio_value( $value ){
    $value = (float)$value;
    $value = sprintf( "%.2f", $value );
    $exp = explode( ".", $value );

    if ( is_array( $exp ) && count( $exp ) == 2 ) {
      if ( 0 == intval( $exp[1] ) )
        return $exp[0];
    }

    return $value;
  }

	function aum_get_data( $websiteid = null, $start_date = null, $end_date = null ) {
		$api_key = $this->option['api_key'];
		if ( empty( $api_key ) ) {
			return false;
		}

		require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
		$loader = new MvcAdminLoader();
		// to fix bug Fatal error: Class 'UptimeMonitor' not found
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_monitor.php';
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_url.php';
    require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_stats.php';

		$utime_mo = new UptimeMonitor();
		$monitor = $utime_mo->find_one( array(
			'selects' => array( 'monitor_id' ),
			'conditions' => array(
        'monitor_api_key' => $api_key,
			),
		));

		if ( ! $monitor ) {
			return false;
		}

		global $mainwpAdvancedUptimeMonitorExtensionActivator;
		$website = apply_filters( 'mainwp-getsites', $mainwpAdvancedUptimeMonitorExtensionActivator->get_child_file(), $mainwpAdvancedUptimeMonitorExtensionActivator->get_child_key(), $websiteid );
		$url_site = '';
		if ( $website && is_array( $website ) ) {
			$website = current( $website );
			$url_site = $website['url'];
		}

		if ( empty( $url_site ) ) {
			return false;
		}

		$utime_url = new UptimeUrl();
		$url_upmo = $utime_url->find_one( array(
			'conditions' => array(
			'monitor_id' => $monitor->monitor_id,
			'url_address' => $url_site, // pass string value only
			),
		));

    if ( ! $url_upmo ) {
        return false;
    }

		$url_upmo_ids = array( $url_upmo->url_uptime_monitor_id );

		$UR = new UptimeRobot( '' );
		$UR->set_format( 'json' );
		$UR->set_api_key( $api_key );
		$result = $UR->get_monitors( $url_upmo_ids, 0, 0, 1, '7-15-30-45-60' );
		// Place this one first
		while ( strpos( $result, ',,' ) !== false ) {
			$result = str_replace( array( ',,' ), ',', $result ); // fix json
		}
		$result = str_replace( ',]', ']', $result ); // fix json
		$result = str_replace( '[,', '[', $result ); // fix json

		$result = json_decode( $result );

		if ( empty( $result ) || $result->stat == 'fail' ) {
			return false;
		}
		$return = array();

		if ( isset( $result->monitors ) && is_array( $result->monitors ) && count( $result->monitors ) > 0 ) {
			$monitor = $result->monitors[0];
			$return['aum.alltimeuptimeratio'] = $monitor->all_time_uptime_ratio;
			list( $up7, $up15, $up30, $up45, $up60 ) = explode( '-', $monitor->custom_uptime_ratio );

      $return['aum.uptime7']  = $this->get_ratio_value( $up7 );
			$return['aum.uptime15'] = $this->get_ratio_value( $up15 );
			$return['aum.uptime30'] = $this->get_ratio_value( $up30 );
			$return['aum.uptime45'] = $this->get_ratio_value( $up45 );
			$return['aum.uptime60'] = $this->get_ratio_value( $up60 );
		}

        $event_statuses = UptimeRobot_DB::get_event_statuses();

        $UMS = new UptimeStats();
        $order_by = "event_datetime_gmt DESC";
        $stats = $UMS->get_events( 'event_datetime_gmt >= STR_TO_DATE("' . date( 'Y-m-d H:i:s', $start_date ) . '", "%Y-%m-%d %H:%i:%s") AND event_datetime_gmt <= STR_TO_DATE("' . date( 'Y-m-d H:i:s', $end_date ) . '", "%Y-%m-%d %H:%i:%s") AND monitor_id = ' . $url_upmo->url_uptime_monitor_id, $order_by );

        $last_existing_event = $UMS->get_last_event( array( 'monitor_id' => $url_upmo->url_uptime_monitor_id ) );
        $unixtime_last_event = 0;
        if ( ! empty( $last_existing_event ) ) {
            $unixtime_last_event = strtotime( $last_existing_event->event_datetime_gmt );
        }

        if ($stats) {

            $option = self::get_install()->option;
            $offset_time = 0;
            if ( isset( $option['api_timezone'] ) && is_array( $option['api_timezone'] ) ) {
                $offset_time = $option['api_timezone']['offset_time'];
                $offset_time = $offset_time * 60 * 60;
            }

            ob_start();
            ?>
            <table>
                <tbody>
	                <tr>
                       <th style="text-align: left;"><?php _e( 'Monitor Name:', 'advanced-uptime-monitor-extension' ); ?></th>
	                   <td><?php echo $url_upmo->url_friendly_name ?></td>
	               </tr>
	               <tr>
	                   <th style="text-align: left;"><?php _e( 'Monitor URL:', 'advanced-uptime-monitor-extension' ); ?></th>
	                   <td><?php echo $url_upmo->url_address; ?></td>
	               </tr>
	               <tr>
	                   <th style="text-align: left;"><?php _e( 'Monitor Type:', 'advanced-uptime-monitor-extension' ); ?></th>
	                   <td><?php echo Advanced_Uptime_Monitor_Extension::get_install()->monitor_types[ $url_upmo->url_monitor_type ] ?></td>
	               </tr>
	               <tr>
	                    <th style="text-align: left;"><?php _e( 'Current Status:', 'advanced-uptime-monitor-extension' ); ?></th>
	                    <td>
	                    <?php
							$last_status = $stats[0];
							if ( $last_status->monitor_type == '-1' ) {
							   $type = $last_status->type;
							   echo ucfirst( $event_statuses[ $type ] );
							} else {
							   $type = $last_status->monitor_type;
							   switch ( $type ) {
							       case '0':
							           echo __( 'Paused', 'advanced-uptime-monitor-extension' );
							           break;
							       case '1':
							           echo __( 'Started', 'advanced-uptime-monitor-extension' );
							           break;
							   }
							}
	                    ?>
	                    </td>
	               </tr>
                </tbody>
            </table>
	        <table style="border-spacing: 0;">
	                <thead>
	                    <tr>
	                        <th width="100px" style="text-align: left;">
	                            <?php _e( 'Status', 'advanced-uptime-monitor-extension' ); ?>
	                        </th>
	                        <th width="220px" style="text-align: left;">
	                            <?php _e( 'Details', 'advanced-uptime-monitor-extension' ); ?>
	                        </th>
	                        <th   width="160px" style="text-align: left;" >
	                            <?php _e( 'Date / Time', 'advanced-uptime-monitor-extension' ); ?>
	                        </th>
                            <th style="text-align: left;">
                                <?php _e( 'Duration', 'advanced-uptime-monitor-extension' ); ?>
                            </th>
	                    </tr>
	                </thead>
	                <tbody>
	                    <?php
	                    foreach ( $stats as $event ) {
	                        $status = '';
	                        if ( $event->monitor_type == '-1' ) {
	                            $type = $event->type;
	                            $status = ucfirst( $event_statuses[ $type ] );
	                        } else {
	                            $type = $event->monitor_type;
	                            switch ( $type ) {
	                                case '0':
	                                    $status = __( 'Paused', 'advanced-uptime-monitor-extension' );
	                                    break;
	                                case '1':
	                                    $status = __( 'Started', 'advanced-uptime-monitor-extension' );
	                            }
	                        }
	                        ?>
	                        <tr>
	                        <td>
	                                <?php
	                                switch ( $status ) {
	                                    case 'Started':
	                                        echo  __( 'Started', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                    case 'Up':
	                                        echo __( 'Up', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                    case 'Paused':
	                                        echo __( 'Paused', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                    case 'Down':
	                                        echo __( 'Down', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                }
	                                ?>
	                            </td>
	                            <td>
	                                <?php
	                                switch ( $status ) {
	                                    case 'Started':
		                                echo __( 'The monitor started manually', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                    case 'Up':
	                                        echo __( 'Successful response received.', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                    case 'Paused':
	                                        echo __( 'The monitor is paused manually', 'advanced-uptime-monitor-extension' );
	                                        break;
	                                    case 'Down':
	                                        if ( $url_upmo->url_monitor_type == '2' ) {
	                                            echo __( 'The keyword exists.', 'advanced-uptime-monitor-extension' );
	                                        } else {
		                                    echo __( 'No response from the website.', 'advanced-uptime-monitor-extension' );
	                                        }
	                                        break;
	                                }
	                                ?>
	                            </td>
	                            <td>
                                <?php
                                    $datetime = strtotime( $event->event_datetime_gmt ) + $offset_time;
                                    $datetime = Advanced_Uptime_Monitor_Extension::get_install()->format_timestamp($datetime);
                                    echo $datetime;
                                ?>
	                            </td>
                                <td>
                                    <?php
                                    $duration = $event->duration;
                                    $unixtime_event_datetime = strtotime( $event->event_datetime_gmt );
                                    if ( $unixtime_event_datetime >= $unixtime_last_event ) { // actually equal
                                       $duration = time() - strtotime( $event->event_datetime_gmt ); // up-to-date duration
                                    }
                                    $hrs = floor($duration / 3600);
                                    $mins =  floor(($duration - $hrs * 3600) / 60);
                                    echo $hrs . ' hrs, ' . $mins . ' mins' ;
                                    ?>
                                </td>
	                        </tr>
	                        <?php
	                    }
	                    ?>
	                </tbody>
	            </table>
            <?php
            $stats_html = ob_get_clean();
            $stats_html = preg_replace( "/\r|\n/", "", $stats_html );  // to fix nl2br() issue
            $return['aum.stats'] = $stats_html;
            }

		return $return;
	}

	public function get_notification_contacts( $api_key ) {

		$UR = new UptimeRobot( '' );
		$UR->set_format( 'json' );
		$UR->set_api_key( $api_key );
		try {
			$result = $UR->get_contacts();
			$result = json_decode( $result );
			if ( $result->stat == 'fail' ) {
				return array();
			}
		} catch (Exception $ex) {

			$this->flash( 'error', $ex->getMessage() );
			return array();
		}

    $contact_types = array(
	    2 => 'E-mail',
	    8 => 'Pro SMS',
	    3 => 'Twitter',
	    5 => 'Web-Hook',
	    1 => 'Email-to-SMS',
	    4 => 'Boxcar 2 (Push for iOS)',
	    6 => 'Pushbullet (Push for Android, iOS &amp; Browsers)',
	    9 => 'Pushover (Push for Android, iOS, Browsers &amp; Desktop)',
	    10 => 'HipChat',
	    11 => 'Slack'
    );

		$number_contacts = count( $result->alert_contacts );
		$list_contact = array();
		for ( $i = 0; $i < $number_contacts; $i++ ) {
			//if ( $result->alert_contacts[ $i ]->status == 2 ) { // active alert

                $value = '';
                $type = $result->alert_contacts[ $i ]->type;
                if (isset($contact_types[$type])) {
                    $value = $result->alert_contacts[ $i ]->friendly_name. " (" .  $contact_types[$type]  . ")";
                } else {
                    $value = $result->alert_contacts[ $i ]->value;
                }
                $list_contact[ $result->alert_contacts[ $i ]->id ] = $value;
			//}
		}
		return $list_contact;
	}

	public function save_option() {
		global $wpdb;

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'aum_nonce_option' ) ) {
			return false;
		}

		// to fix bug Fatal error: Class 'UptimeMonitor' not found
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_monitor.php';
		require_once MVC_AUM_PLUGIN_PATH . 'app/models/uptime_url.php';

		if ( get_option( 'mainwp_aum_requires_reload_monitors' ) == 'yes' ) {
			update_option( 'mainwp_aum_requires_reload_monitors', '' );
		}

		$this->option['api_timezone'] = '';
		$api_key = isset( $_POST['api_key'] ) ? trim( $_POST['api_key'] ) : '';
		// All is OK now
		if ( ! empty( $api_key ) ) {
			$UM = new UptimeMonitor();
			$UUR = new UptimeUrl();
            $current_UMs = $UM->find();
			// to fix bug
			if (empty($current_UMs)) {
				$UM->save_user_main_api_key( $api_key );
			}

			$count = 0;
			$results = $this->get_all_uptime_monitors( $api_key ); // saving options
			// error_log("result=" . print_r($results, true));
			if ( is_array( $results ) && (count( $results ) > 0) ) {
				$monitor_id = 0;
                $current_UMs = $UM->find();
				if ( count( $current_UMs ) > 0 ) {
					foreach ( $current_UMs as $current_UM ) {
						// delete others, each user have only one monitor
						if ( $current_UM->monitor_api_key == $api_key && empty( $monitor_id ) ) {
							$monitor_id = $current_UM->monitor_id;
						} else {
							$UM->delete_all(array(
								'conditions' => array(
									'monitor_id' => $current_UM->monitor_id,
								),
							));
							// delete monitor urls
							$UUR->delete_all(array(
								'conditions' => array(
									'monitor_id' => $current_UM->monitor_id,
								),
							));
						}
					}
				}

				$current_uptime_monitor_ids = array();

				if ( $monitor_id ) {
					$current_UUR = $UUR->find(array(
						'conditions' => array(
							'monitor_id' => $monitor_id,
						),
					));
					if ( is_array( $current_UUR ) && (count( $current_UUR ) > 0) ) {
						foreach ( $current_UUR as $mo ) {
							if ( ! empty( $mo->url_address ) ) {
								$current_uptime_monitor_ids[] = $mo->url_uptime_monitor_id;
							}
						}
					}
				} else {
					$monitor_id = $UM->save_user_main_api_key( $api_key );
				}

				$results_uptime_monitor_ids = array();
				if ( $monitor_id ) {
					foreach ( $results as $result ) {
						if ( is_object( $result ) ) {
							$UUR->save_uptime_monitors( $monitor_id, $result->monitors ); // saving options
							foreach ( $result->monitors as $mo ) {
								$results_uptime_monitor_ids[] = $mo->id;
							}
						}
					}
				}

				$diff_ids = array_diff( $current_uptime_monitor_ids, $results_uptime_monitor_ids );

				if ( is_array( $diff_ids ) && count( $diff_ids ) > 0 ) {
					foreach ( $diff_ids as $mo_id ) {
                        $UUR->delete_all( array( 'conditions' => array( 'url_uptime_monitor_id' => $mo_id ) ) );
					}
				}

			}

			$list_contact = $this->get_notification_contacts( $api_key );
			//error_log(print_r($list_contact, true));
			$this->option['uptime_default_notification_contact_id'] = isset( $_POST['select_default_noti_contact'] ) ? wp_unslash( $_POST['select_default_noti_contact'] ) : 0;
			$this->option['list_notification_contact'] = $list_contact;
			$this->option['api_key'] = $api_key;

			$UR = new UptimeRobot( $api_key );
			$off = $UR->get_ur_gmt_offset_time();
			if ( is_array($off)) {
				$this->option['api_timezone'] = $off;
			}

		} else {
			$UM = new UptimeMonitor();
            $UM->delete_all();
			// delete monitor urls
			$UUR = new UptimeUrl();
            $UUR->delete_all();   // do not delete statistics event data
			$this->option['list_notification_contact'] = '';
			$this->option['api_key'] = '';
		}
		// echo $count;
		// All is OK now
		$this->option['saved_time'] = current_time( 'timestamp' );
		update_option( $this->option_handle, $this->option );
		return true;
	}

	public function get_option( $key ) {
		if ( isset( $this->option[ $key ] ) ) {
			return $this->option[ $key ];
		}
		return '';
	}

	public function set_option( $key, $value ) {
		$this->option[ $key ] = $value;
		return update_option( $this->option_handle, $this->option );
	}

	function get_all_uptime_monitors( $api_key ) {
		if ( empty( $api_key ) ) {
			$this->set_option( 'uptime_robot_message', __( 'Please enter your Uptime monitor API key.', 'advanced-uptime-monitor-extension' ) );
			return false;
		}
		$valid = false;
		$UR = new UptimeRobot( '' );
		$UR->set_format( 'json' );
		$UR->set_api_key( $api_key );
		$results = $UR->get_all_monitors(); // saving options
		$this->set_option( 'uptime_robot_message', '' );

		if ( empty( $results ) ) {
			$this->set_option( 'uptime_robot_message', __( 'Uptime Robot undefined error.', 'advanced-uptime-monitor-extension' ) );
		}

		if ( is_array( $results ) && count( $results ) > 0 ) {
			$result = current( $results ); // check first one only
			// $result = json_decode($result);
			if ( $result->stat == 'fail' ) {
				$this->set_option( 'uptime_robot_message', $result->message );
			} else {
				$valid = true;
			}

			if ( isset( $result->id ) && ($result->id == 212) ) { // api have no monitors
				$this->set_option( 'uptime_robot_message', '' );
				$this->set_option( 'api_key_status', 'valid' );
				return array();
			}
		}
		if ( $valid ) {
			$this->set_option( 'api_key_status', 'valid' );
			if ( ! isset( $result->id ) || ($result->id != 212) ) {
				$this->set_option( 'uptime_robot_message', '' );
			}
		} else {
			$this->set_option( 'api_key_status', 'invalid' );
			return false;
		}

		return $results;
	}

	function get_uptime_monitors( $api_key, $monitor_ids = array(), $logs = 0, $alertContacts = 0, $allUptimeRatio = 0, $customRatio = '' ) {
		if ( empty( $api_key ) ) {
			$this->set_option( 'uptime_robot_message', __( 'Please enter your Uptime monitor API key.', 'advanced-uptime-monitor-extension' ) );
			return false;
		}

		$valid = false;
		$UR = new UptimeRobot( '' );
		$UR->set_format( 'json' );
		$UR->set_api_key( $api_key );
		$result = $UR->get_monitors( $monitor_ids, $logs, $alertContacts, $allUptimeRatio, $customRatio );

		// place this one first
		while ( strpos( $result, ',,' ) !== false ) {
			$result = str_replace( array( ',,' ), ',', $result ); // fix json
		}
		$result = str_replace( ',]', ']', $result ); // fix json
		$result = str_replace( '[,', '[', $result ); // fix json
        $result = json_decode( $result );

		$this->set_option( 'uptime_robot_message', '' );
		if ( empty( $result ) ) {
			$this->set_option( 'uptime_robot_message', __( 'Uptime Robot undefined error', 'advanced-uptime-monitor-extension' ) );
		} else if ( $result->stat == 'fail' ) {
			$this->set_option( 'uptime_robot_message', $result->message );
		} else {
			$valid = true;
		}

		if ( isset( $result->id ) && ($result->id == 212) ) { // api have no monitors
			$this->set_option( 'uptime_robot_message', '' );
			$this->set_option( 'api_key_status', 'valid' );
			return array();
		}

		if ( $valid ) {
			$this->set_option( 'api_key_status', 'valid' );
			if ( ! isset( $result->id ) || ($result->id != 212) ) {
				$this->set_option( 'uptime_robot_message', '' );
			}
		} else {
			$this->set_option( 'api_key_status', 'invalid' );
			return false;
		}

		return $result;
	}

	public function aum_metabox() {

		// to fix bug call function from hook may be not load MVC
		require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
		$site_id = isset( $_GET['dashboard'] ) ? wp_unslash( $_GET['dashboard'] ) : 0;
		?>
        <div id="aum_mainwp_widget_uptime_monitor_content" class="inside">
            <div id="aum_mainwp_uptime_monitor_loading">
                <i class="fa fa-spinner fa-pulse"></i> <?php _e( 'Loading monitors...', 'advanced-uptime-monitor-extension' ); ?>
            </div>
            <div id="aum_mainwp_widget_uptime_monitor_content_inner" class="monitors"></div>
        </div>
        <script type="text/javascript">
            jQuery(document).ready(function () {

				mainwp_aum_metabox_get_monitors = function( pPage ) {
					jQuery.ajax({
						url: ajaxurl,
						type: "POST",
						data: {
							action: 'admin_uptime_monitors_meta_box',
							site_id: '<?php echo esc_attr( $site_id ); ?>',
							get_page: pPage,
							wp_nonce: '<?php echo esc_attr( wp_create_nonce( 'aum_nonce_meta_box' ) ); ?>'
						},
						error: function () {
							jQuery('#aum_mainwp_uptime_monitor_loading').hide();
							jQuery('#aum_mainwp_widget_uptime_monitor_content_inner').html('Request timed out. Please, try again later.').fadeIn(2000);
						},
						success: function (response) {
							jQuery('#aum_mainwp_uptime_monitor_loading').hide();
							jQuery('#aum_mainwp_widget_uptime_monitor_content_inner').html(response).fadeIn(2000);
							jQuery('#aum_mainwp_widget_uptime_monitor_content .ui.dropdown').dropdown();


							jQuery('#mainwp_aum_monitor_select_page').dropdown();
							jQuery('#mainwp_aum_monitor_select_page').dropdown('setting', 'onChange', function( val ){
								mainwp_aum_metabox_get_monitors(val);
							});
						},
						timeout: 20000
					});
				};
				mainwp_aum_metabox_get_monitors( 1 );
            });
        </script>
        <?php
	}

	public function render_status_bar( $status, $ratio ) {
        $ratio = number_format( $ratio, 2 );
		switch ( $status ) {
			case 0:
				$sta = '<div class="aum_upm_status paused"><span title="' . __('Uptime ratio: ') . $ratio . '%">' . '<i class="fa fa-pause" aria-hidden="true"></i> Paused' . '</span></div>';
				break;
			case 1:
				$sta = '<div class="aum_upm_status not_checked"><span title="' . __('Uptime ratio: ') . $ratio . '%">' . '<i class="fa fa-clock-o" aria-hidden="true"></i> Pending' . '</span></div>';
				break;
			case 2:
				$sta = '<div class="aum_upm_status up"><span title="' . __('Uptime ratio: ') . $ratio . '%">' . '<i class="fa fa-arrow-up" aria-hidden="true"></i> Up' . '</span></div>';
				break;
			case 8:
				$sta = '<div class="aum_upm_status seems_down"><span title="' . __('Uptime ratio: ') . $ratio . '%">' . '<i class="fa fa-question" aria-hidden="true"></i> Seems down' . '</span></div>';
				break;
			case 9:
				$sta = '<div class="aum_upm_status down"><span title="' . __('Uptime ratio: ') . $ratio . '%">' . '<i class="fa fa-arrow-down" aria-hidden="true"></i> Down' . '</span></div>';
				break;
		}
		return $sta;
	}

    public function render_ratio_bar( $status, $ratio ) {
        $ratio = number_format( $ratio, 2 );
		return $ratio . '%';
	}

    public static function format_timestamp( $timestamp ) {
		return date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $timestamp );
	}

}

function mainwp_uptime_robot_monitors_activate() {
	require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
	$loader = new MvcAdminLoader();
	// to fix bug
	$plugin_loader = new MvcPluginLoader();
	$plugin_loader->activate_app( __FILE__ );

	update_option( 'mainwp_uptime_robot_monitors_activated', 'yes' );
	$extensionActivator = new AdvancedUptimeMonitorExtensionActivator();
	$extensionActivator->activate();
}

function mainwp_uptime_robot_monitors_deactivate() {
	require_once MVC_AUM_PLUGIN_PATH . 'core/loaders/mvc_admin_loader.php';
	$loader = new MvcAdminLoader();
	// to fix bug
	$plugin_loader = new MvcPluginLoader();
	$plugin_loader->deactivate_app( __FILE__ );

	$extensionActivator = new AdvancedUptimeMonitorExtensionActivator();
	$extensionActivator->deactivate();
}

register_activation_hook( __FILE__, 'mainwp_uptime_robot_monitors_activate' );
register_deactivation_hook( __FILE__, 'mainwp_uptime_robot_monitors_deactivate' );

class AdvancedUptimeMonitorExtensionActivator {

	protected $mainwpMainActivated = false;
	protected $childEnabled = false;
	protected $childKey = false;
	protected $childFile;
	protected $plugin_handle = 'advanced-uptime-monitor-extension';
	protected $product_id = 'Advanced Uptime Monitor Extension';
	protected $software_version = '5.0.1';

	public function __construct() {
		$this->childFile = __FILE__;
		add_filter( 'mainwp-getextensions', array( &$this, 'get_this_extension' ) );
		$this->mainwpMainActivated = apply_filters( 'mainwp-activated-check', false );
		if ( $this->mainwpMainActivated !== false ) {
			$this->activate_this();
		} else {
			add_action( 'mainwp-activated', array( &$this, 'activate_this' ) );
		}
		add_action( 'admin_init', array( &$this, 'admin_init' ) );
		add_action( 'admin_notices', array( &$this, 'mainwp_error_notice' ) );
	}

	public function get_child_key() {

		return $this->childKey;
	}

	public function get_child_file() {

		return $this->childFile;
	}

	function admin_init() {
		if ( get_option( 'mainwp_uptime_robot_monitors_activated' ) == 'yes' ) {
			delete_option( 'mainwp_uptime_robot_monitors_activated' );
			wp_redirect( admin_url( 'admin.php?page=Extensions' ) );
			return;
		}
	}

	function get_this_extension( $pArray ) {
		$pArray[] = array(
			'plugin' => __FILE__,
			'api' => $this->plugin_handle,
			'mainwp' => true,
			'callback' => array( &$this, 'settings' ),
			'apiManager' => true
		);
		return $pArray;
	}

	function settings() {
		do_action( 'mainwp-pageheader-extensions', __FILE__ );
		Advanced_Uptime_Monitor_Extension::get_install()->option_page();
		do_action( 'mainwp-pagefooter-extensions', __FILE__ );
	}

	function get_metaboxes( $metaboxes ) {
		if ( ! $this->childEnabled ) {
			return $metaboxes;
		}

		if ( ! is_array( $metaboxes ) ) {
			$metaboxes = array();
		}
		$metaboxes[] = array( 'id' => 'aum-widget', 'plugin' => $this->childFile, 'key' => $this->childKey, 'metabox_title' => '<i class="fa fa-eye"></i> ' . __( 'Advanced Uptime Monitor', 'advanced-uptime-monitor-extension' ), 'callback' => array( &$this, 'render_metabox' ) );
		return $metaboxes;
	}

	function render_metabox() {
	?>
		<div class="ui grid">
			<div class="twelve wide column">
				<h3 class="ui header handle-drag">
				<?php esc_html_e( 'Monitors', 'advanced-uptime-monitor-extension' ); ?>
					<div class="sub header"><?php esc_html_e( 'Monitor your child sites', 'advanced-uptime-monitor-extension' ); ?></div>
				</h3>
			</div>
			<div class="four wide column right aligned"></div>
		</div>
		<?php
		Advanced_Uptime_Monitor_Extension::get_install()->aum_metabox();
	}

	function activate_this() {
		$this->mainwpMainActivated = apply_filters( 'mainwp-activated-check', $this->mainwpMainActivated );
		if ( function_exists( 'mainwp_current_user_can' ) && ! mainwp_current_user_can( 'extension', 'advanced-uptime-monitor-extension' ) ) {
			return;
		}
		// fix bug uptime monitor for no get ajax to create DB
		Advanced_Uptime_Monitor_Extension::get_install();
		add_filter( 'mainwp-getmetaboxes', array( &$this, 'get_metaboxes' ) );
		add_filter( 'mainwp-widgets-screen-options', array( &$this, 'widgets_screen_options' ), 10 , 1 );

		$this->childEnabled = apply_filters( 'mainwp-extension-enabled-check', __FILE__ );
		$this->childKey = $this->childEnabled['key'];
	}

	function widgets_screen_options( $input ) {
		$input['advanced-aum-widget'] = __( 'Monitors', 'advanced-uptime-monitor-extension' );
		return $input;
	}

	function mainwp_error_notice() {
		global $current_screen;
		if ( $current_screen->parent_base == 'plugins' && $this->mainwpMainActivated == false ) {
			echo '<div class="error"><p>Advanced Uptime Monitor Extension ' . __('requires <a href="http://mainwp.com/" target="_blank">MainWP Dashboard Plugin</a> to be activated in order to work. Please install and activate <a href="http://mainwp.com/" target="_blank">MainWP Dashboard Plugin</a> first.') . '</p></div>';
		}
	}

	public function activate() {
		$options = array(
			'product_id' => $this->product_id,
			'activated_key' => 'Deactivated',
			'instance_id' => apply_filters( 'mainwp-extensions-apigeneratepassword', 12, false ),
			'software_version' => $this->software_version,
		);
		update_option( $this->plugin_handle . '_APIManAdder', $options );
	}

	public function deactivate() {
		update_option( $this->plugin_handle . '_APIManAdder', '' );
	}
}

global $mainwpAdvancedUptimeMonitorExtensionActivator;
$mainwpAdvancedUptimeMonitorExtensionActivator = new AdvancedUptimeMonitorExtensionActivator();
