<?php
class UptimeRobot_DB {
	
	private $uptime_robot_monitors_db_version = '1.8';	
	private static $instance = null;
	private $table_prefix;
	
	static function get_instance() {
		if ( null === UptimeRobot_DB::$instance ) {
			UptimeRobot_DB::$instance = new UptimeRobot_DB();
		}
		return UptimeRobot_DB::$instance;
	}
	
	//Constructor
	function __construct() {
		global $wpdb;
		$this->wpdb         = &$wpdb;
		$this->table_prefix = $wpdb->prefix;		
	}

	function table_name( $suffix ) {
		return $this->table_prefix . $suffix;
	}
	
	//Installs new DB
	function install() {
		global $wpdb;		
		$currentVersion = get_option( 'uptime_robot_monitors_db_version' );		
		
		$rslt = UptimeRobot_DB::get_instance()->query( "SHOW TABLES LIKE '" . $this->table_name( 'aum_monitors' ) . "'" );
		if ( @UptimeRobot_DB::num_rows( $rslt ) == 0 ) {
			$currentVersion = false;
		}
		
		if ( $currentVersion == $this->uptime_robot_monitors_db_version ) { return; }		
		
		$charset_collate = $wpdb->get_charset_collate();
		$sql = array();

		$tbl = 'CREATE TABLE `' . $this->table_name( 'aum_monitors' ) . '` (
`monitor_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`monitor_name` varchar(100) NOT NULL,
`monitor_type` int(5) NOT NULL,
`monitor_api_key` varchar(100) NOT NULL,
`monitor_not_email` varchar(100) NOT NULL,
`monitor_main` tinyint(1) NOT NULL DEFAULT 1,
`monitor_reg_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP';
		if ( '' == $currentVersion ) {
					$tbl .= ',
PRIMARY KEY  (`monitor_id`)  '; }
		$tbl .= ') ' . $charset_collate;
		
		$sql[] = $tbl;
				
		$tbl = 'CREATE TABLE `' . $this->table_name( 'aum_urls' ) . '` (
`url_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `monitor_id` int(11) NOT NULL,
  `url_uptime_monitor_id` varchar(100) NOT NULL,
  `url_api_key` varchar(100) NOT NULL,
  `url_friendly_name` varchar(100) NOT NULL,
  `url_address` varchar(100) NOT NULL,
  `url_not_email` varchar(100) NOT NULL,
  `url_monitor_type` tinyint(4) NOT NULL,
  `url_monitor_subtype` tinyint(4) NOT NULL,
  `url_monitor_keywordtype` tinyint(4) NOT NULL,
  `url_monitor_keywordvalue` text NOT NULL,
  `dashboard` tinyint(1) NOT NULL DEFAULT 0,  
  `status` tinyint(1) NOT NULL DEFAULT 2, 
  `alltimeuptimeratio` DECIMAL( 12, 2 ) NOT NULL DEFAULT  0,     
  `customuptimeratio`varchar(256) NOT NULL, 
  `monitor_interval` tinyint(4) NOT NULL DEFAULT 5,
  `http_username` varchar(256) NOT NULL,
  `http_password` varchar(256) NOT NULL,
  `url_reg_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP';		
		if ( '' == $currentVersion ) {
					$tbl .= ',
PRIMARY KEY  (`url_id`)  '; }
		$tbl .= ') ' . $charset_collate;
		
		$sql[] = $tbl;
		
		$tbl = 'CREATE TABLE `' . $this->table_name( 'aum_stats' ) . '` (
`event_id` int(11) NOT NULL AUTO_INCREMENT,
`monitor_id` int(11) NOT NULL,
`type` tinyint(3) NOT NULL DEFAULT 0,
`duration` int(11) NOT NULL,
`code` int(5) NOT NULL,
`detail` varchar(256) NOT NULL,
`monitor_type` tinyint(4) NOT NULL DEFAULT -1,
`event_datetime_gmt` datetime NOT NULL';		
		if ( '' == $currentVersion ) {
					$tbl .= ',
PRIMARY KEY  (`event_id`)  '; }
		$tbl .= ') ' . $charset_collate;
		
		$sql[] = $tbl;
		
		error_reporting( 0 ); // make sure to disable any error output
		require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
		foreach ( $sql as $query ) {
			dbDelta( $query );
		}
        
        $this->check_update($currentVersion);
		update_option( 'uptime_robot_monitors_db_version', $this->uptime_robot_monitors_db_version );
	}
	
    function check_update($version) {
        if (!empty($version)) {
            global $wpdb;
            if (version_compare($version, '1.7', '<=')) {      
                $wpdb->update( $this->table_name( 'aum_stats' ), array('duration' => '113'), array( 'duration' => '-1' ) );
            }
        }
    }
    
    function delete_stats($by, $value) {
        global $wpdb;
        if ($by == 'monitor_id' && $value != '') {            
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'aum_stats 
                            WHERE monitor_id = "' . $value . '"');
            return true;
        }
        return false;
    }
    
    public function update_event( $event_id, $fields ) {
        global $wpdb;
		if ( count( $fields ) > 0 ) {
			return $wpdb->update( $this->table_name( 'aum_stats' ), $fields, array( 'event_id' => $event_id ) );
		}
		return false;
	}
        
    function get_overal_uptime_monitor() {
        global $wpdb;
        $return = array();
        
        // get monitors status
        $result = $wpdb->get_results('SELECT status, customuptimeratio FROM ' . $wpdb->prefix . 'aum_urls WHERE 1');
        
        $overal_ratios = array();
        
        $overal_status = array(
             'paused' => 0,
             'not_checked' => 0,
             'up' => 0,             
             'seems_down' => 0,
             'down' => 0,             
         );
        
        $count = 0;
		if ($result) {
            foreach($result as $val) {
                $ratios = explode('-', $val->customuptimeratio);
                if (is_array($ratios) && count($ratios) == 6) {
                    $count++;
                    for($i=0; $i < 6; $i++) {
                        $overal_ratios[$i] += $ratios[$i]; 
                    }                    
                }                
                //monitor status: 0 - paused, 1 - not checked yet, 2 - up, 8 - seems down, 9 - down
                if ($val->status == 0) {
                    $overal_status['paused']++;
                } else if ($val->status == 1) {
                    $overal_status['not_checked']++;
                } else if ($val->status == 2) {
                    $overal_status['up']++;
                } else if ($val->status == 8) {
                    $overal_status['seems_down']++;
                } else if ($val->status == 9) {
                    $overal_status['down']++;
                }
            }
        }
        if ($count) {
            for($i=0; $i < 6; $i++) {
                $overal_ratios[$i] = number_format($overal_ratios[$i] / $count, 2); 
            }
            $return['overal_ratios'] = $overal_ratios;
        }        
        $return['overal_status'] = $overal_status;
        return $return;
    }
    
    public static function get_monitor_statuses() {        
        //monitor status: 0 - paused, 1 - not checked yet, 2 - up, 8 - seems down, 9 - down
        return $monitor_statuses = array(
            0 => 'paused',
            1 => 'not_checked',
            2 => 'up',
            8 => 'seems_down',
            9 => 'down'
        );
    }
    
    public static function get_event_statuses() {        
        // 1 - down, 2 - up, 99 - paused, 98 - started
        return $event_statuses = array(
            1 => 'down',
            2 => 'up',
            99 => 'paused',
            98 => 'started'            
        );        
    }
  
    
	//Support old & new versions of wordpress (3.9+)
	public static function use_mysqli() {
		/** @var $this ->wpdb wpdb */
		if ( ! function_exists( 'mysqli_connect' ) ) {
			return false;
		}

		return ( self::$instance->wpdb->dbh instanceof mysqli );
	}
	
	
	public function query( $sql ) {
		if ( $sql == null ) {
			return false;
		}

		$result = @self::_query( $sql, $this->wpdb->dbh );

		if ( ! $result || ( @UptimeRobot_DB::num_rows( $result ) == 0 ) ) {
			return false;
		}

		return $result;
	}
	
	public static function _query( $query, $link ) {
		if ( self::use_mysqli() ) {
			return mysqli_query( $link, $query );
		} else {
			return mysql_query( $query, $link );
		}
	}
	
	public static function num_rows( $result ) {
		if ( $result === false ) {
			return 0;
		}

		if ( self::use_mysqli() ) {
			return mysqli_num_rows( $result );
		} else {
			return mysql_num_rows( $result );
		}
	}
	
}
?>
