<?php


class Els_Ajax {

    public $users = null;

    public function run_action(){

        global $wpdb;

        if ( $_POST["action"] == "load_session" ) {

            $this->check_session();

            //Add a new row in the live_visitors_page_views table with the current page data
            $wpdb->query(
                $wpdb->prepare("INSERT INTO {$wpdb->prefix}live_visitor_page_view (
                    live_visitor_page_view_random_user,
                    live_visitor_page_view_page,
                    live_visitor_page_view_page_url)
                    VALUES ('%s', '%s', '%s')
                ", $_SESSION["live_visitor"], $_POST["title"], $_POST["url"])
            );

            if ( !$this->is_user_new() ){


                $ip = $this->get_user_ip();
                $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));

                $username = null;
                if ( is_user_logged_in() ) {

                    global $current_user;
                    get_currentuserinfo();

                    $username = $current_user->user_login;
                }


                $wpdb->query(
                    $wpdb->prepare("INSERT INTO {$wpdb->prefix}live_visitor_user
                        (
                        live_visitor_page_view_random_user,
                        live_visitor_user_wp_name,
                        live_visitor_user_ip,
                        live_visitor_user_os,
                        live_visitor_user_browser,
                        live_visitor_user_city,
                        live_visitor_user_region,
                        live_visitor_user_country,
                        live_visitor_last_page_load
                        )

                        VALUES ('%s','%s', '%s', '%s','%s','%s','%s','%s', '%s')
                    ", $_SESSION["live_visitor"], $username, $ip, $this->get_user_os(), $this->get_user_browser(), $details->city, $details->region, $details->country, time())
                );


            }

        } else if ( $_POST["action"] == "update_page" ){

            $this->update_current_page();
            $this->check_for_username();

        } else if ( $_POST["action"] == "live-visitors" ){

            $this->delete_entries();
            $this->users = $this->get_distinct_users();

            $this->get_user_data();

            echo json_encode($this->users);

        }else if ( $_POST["action"] == "today-live-visitors" ){

            $this->delete_entries();
            $this->users = $this->get_past_users();
            $this->get_user_data( true );

            echo json_encode($this->users);
        }

        die();
    }

    protected function update_current_page(){

        global $wpdb;

        $id = $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_id FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' AND live_visitor_page_view_end_time IS NULL ORDER BY live_visitor_page_view_end_time DESC LIMIT 0,1", $_SESSION["live_visitor"])
        );

        $wpdb->query("UPDATE {$wpdb->prefix}live_visitor_page_view SET live_visitor_page_view_end_time = NOW() WHERE live_visitor_page_view_id = '" . $id . "'");
    }

    protected function check_session() {

        if ( !$this->is_session_set() )
                $this->set_session();
        else {

            //Check it hasn't been more than 30 mins
            //since the last page refresh/load
            global $wpdb;

            $last = $wpdb->get_var(
                $wpdb->prepare("SELECT live_visitor_last_page_load FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $_SESSION["live_visitor"])
            );


            $elapsed = time() - $last;

            if ( $elapsed > 1800 ){
                $this->set_session();
            }else {
                $wpdb->query(
                    $wpdb->prepare("UPDATE {$wpdb->prefix}live_visitor_user SET live_visitor_last_page_load = '%s' WHERE live_visitor_page_view_random_user = '%s'", time(), $_SESSION["live_visitor"])
                );
            }

        }

    }

    protected function check_for_username(){


        global $wpdb;

        $username = null;
        if ( is_user_logged_in() ) {

            global $current_user;
            get_currentuserinfo();

            $username = $current_user->user_login;
            $wpdb->query(
                $wpdb->prepare("UPDATE {$wpdb->prefix}live_visitor_user SET live_visitor_user_wp_name = '%s' WHERE live_visitor_page_view_random_user = '%s' ", $username, $_SESSION["live_visitor"])
            );
        }

    }

    protected function is_session_set() {

        if ( isset( $_SESSION["live_visitor"] ) )
            return true;
        else
            return false;
    }

    protected function set_session(){

        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = '';
        for ($i = 0; $i < 32; $i++)
            $rand .= $characters[rand(0, strlen($characters) - 1)];

        $_SESSION["live_visitor"] = time() . "-" . $rand;
    }

    protected function is_user_new(){

        global $wpdb;

        $user = $wpdb->get_var("SELECT count(*) AS count FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '" . $_SESSION["live_visitor"] . "'");
        return $user;
    }

    protected function get_user_ip(){

        if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
            if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
                $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
                return trim($addr[0]);
            } else {
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
        }
        else {
            return $_SERVER['REMOTE_ADDR'];
        }
    }

    protected function get_user_os(){

        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        $os_platform = "Unknown OS Platform";

        $os_array = array(
            '/windows nt 6.3/i'     =>  'Windows 8.1',
            '/windows nt 6.2/i'     =>  'Windows 8',
            '/windows nt 6.1/i'     =>  'Windows 7',
            '/windows nt 6.0/i'     =>  'Windows Vista',
            '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
            '/windows nt 5.1/i'     =>  'Windows XP',
            '/windows xp/i'         =>  'Windows XP',
            '/windows nt 5.0/i'     =>  'Windows 2000',
            '/windows me/i'         =>  'Windows ME',
            '/win98/i'              =>  'Windows 98',
            '/win95/i'              =>  'Windows 95',
            '/win16/i'              =>  'Windows 3.11',
            '/macintosh|mac os x/i' =>  'Mac OS X',
            '/mac_powerpc/i'        =>  'Mac OS 9',
            '/linux/i'              =>  'Linux',
            '/ubuntu/i'             =>  'Ubuntu',
            '/iphone/i'             =>  'iPhone',
            '/ipod/i'               =>  'iPod',
            '/ipad/i'               =>  'iPad',
            '/android/i'            =>  'Android',
            '/blackberry/i'         =>  'BlackBerry',
            '/webos/i'              =>  'Mobile'
        );

        foreach ($os_array as $regex => $value) {

            if (preg_match($regex, $user_agent)) {
                $os_platform    =   $value;
            }

        }

        return $os_platform;
    }

    protected function get_user_browser(){

        include_once (plugin_dir_path( __FILE__ ) . "/els-detect-browser.php");

        $browser = new Browser();
        return $browser->getBrowser() . " " . $browser->getVersion();
    }

    public function get_distinct_users() {

        global $wpdb;
        return $wpdb->get_results("SELECT DISTINCT(live_visitor_page_view_random_user) FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_end_time IS NULL ORDER BY live_visitor_page_view_start_time, live_visitor_page_view_random_user ASC", ARRAY_A);
    }

    public function get_current_users() {

        $users = array();
        foreach( $this->get_distinct_users() as $user ){

            $users[] = $user["live_visitor_page_view_random_user"];

        }

        return "'" . join('\', \'', $users) . "'";
    }

    public function get_past_users() {

        global $wpdb;

        $users = $wpdb->get_results("SELECT DISTINCT(live_visitor_page_view_random_user) FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user NOT IN (". $this->get_current_users() .")", ARRAY_A);
        return $users;
    }

    private function get_user_data( $historical = false ){

        foreach ( $this->users as $key => $user ){

            $this->users[$key]["user_current_page"] = $this->get_current_page( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_ip"] = $this->get_saved_user_ip( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_name"] = $this->get_saved_user_name( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_os"] = $this->get_saved_user_os( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_browser"] = $this->get_saved_user_browser( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_location"] = trim($this->get_saved_user_location( $user["live_visitor_page_view_random_user"] ));
            $this->users[$key]["user_total_time"] = $this->get_start_time( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_total_time_page"] = $this->secs_to_h($this->get_time_on_page( $user["live_visitor_page_view_random_user"] ));
            $this->users[$key]["user_total_pages"] = $this->get_total_pages( $user["live_visitor_page_view_random_user"] );
            $this->users[$key]["user_iso"] = $this->get_saved_user_iso( $user["live_visitor_page_view_random_user"] );

            if ( $historical == true ){

                $this->users[$key]["user_total_time"] = $this->secs_to_h($this->get_time_on_site( $user["live_visitor_page_view_random_user"] ));

                $this->users[$key]["user_history"] = $this->get_historical_data( $user["live_visitor_page_view_random_user"] );

            }
        }
    }

    private function get_historical_data( $random_id ) {

        global $wpdb;

        $data = $wpdb->get_results(
            $wpdb->prepare("SELECT *, TIMESTAMPDIFF(SECOND, live_visitor_page_view_start_time, live_visitor_page_view_end_time) AS diff FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_start_time ASC", $random_id), ARRAY_A
        );

        foreach ( $data as $key => $d ) {

            $data[$key]["diff"] = $this->secs_to_h($d["diff"]);
            $data[$key]["live_visitor_page_view_start_time"] = date("h:ia", strtotime($d["live_visitor_page_view_start_time"]));
            $data[$key]["live_visitor_page_view_end_time"] = date("h:ia", strtotime($d["live_visitor_page_view_end_time"]));

        }

        return $data;
    }

    private function get_user_start_time( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_start_time FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_start_time ASC LIMIT 0,1", $random_id)
        );
    }

    private function get_user_end_time( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_end_time FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_end_time ASC LIMIT 0,1", $random_id)
        );
    }

    private function get_current_page( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_page_url FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_end_time ASC LIMIT 0,1", $random_id)
        );
    }

    private function get_start_time( $random_id ) {

        global $wpdb;

        $start = $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_start_time FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_start_time ASC LIMIT 0,1", $random_id)
        );

        return $start;
    }

    private function get_time_on_site( $random_id ){

        global $wpdb;

        $start = $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_start_time FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_start_time ASC LIMIT 0,1", $random_id)
        );

        $end = $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_page_view_end_time FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_end_time DESC LIMIT 0,1", $random_id)
        );

        return strtotime( $end ) - strtotime( $start );
    }

    private function get_time_on_page( $random_id ){

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT TIMESTAMPDIFF(SECOND, live_visitor_page_view_start_time, live_visitor_page_view_end_time) AS diff FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s' ORDER BY live_visitor_page_view_end_time DESC LIMIT 0,1", $random_id)
        );
    }

    private function get_total_pages( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT count( live_visitor_page_view_random_user ) AS count FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '%s'", $random_id)
        );
    }

    private function get_saved_user_ip( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_user_ip FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $random_id)
        );
    }

    private function get_saved_user_name( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_user_wp_name FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $random_id)
        );
    }

    private function get_saved_user_os( $random_id ) {

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_user_os FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $random_id)
        );
    }

    private function get_saved_user_browser( $random_id ){

        global $wpdb;

        return $wpdb->get_var(
            $wpdb->prepare("SELECT live_visitor_user_browser FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $random_id)
        );
    }

    private function get_saved_user_location( $random_id ){

        global $wpdb;

        $data = $wpdb->get_row(
            $wpdb->prepare("SELECT live_visitor_user_city, live_visitor_user_region, live_visitor_user_country FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $random_id), ARRAY_A
        );

        if ( $data["live_visitor_user_city"] == $data["live_visitor_user_region"] )
            $data["live_visitor_user_region"] = null;

        if ( $data["live_visitor_user_city"] )
            $data["live_visitor_user_city"] = $data["live_visitor_user_city"] . ",";

        if ( $data["live_visitor_user_region"] )
            $data["live_visitor_user_region"] = $data["live_visitor_user_region"] . ",";

        return $data["live_visitor_user_city"] . " " . $data["live_visitor_user_region"] . " " . $this->country_code_to_country($data["live_visitor_user_country"]);
    }

    private function get_saved_user_iso( $random_id ){

        global $wpdb;

        $data = $wpdb->get_row(
            $wpdb->prepare("SELECT live_visitor_user_country FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '%s'", $random_id), ARRAY_A
        );
        return strtolower($data["live_visitor_user_country"]);
    }

    public function country_code_to_country( $code ){
        $country = '';
        if( $code == 'AF' ) $country = 'Afghanistan';
        if( $code == 'AX' ) $country = 'Aland Islands';
        if( $code == 'AL' ) $country = 'Albania';
        if( $code == 'DZ' ) $country = 'Algeria';
        if( $code == 'AS' ) $country = 'American Samoa';
        if( $code == 'AD' ) $country = 'Andorra';
        if( $code == 'AO' ) $country = 'Angola';
        if( $code == 'AI' ) $country = 'Anguilla';
        if( $code == 'AQ' ) $country = 'Antarctica';
        if( $code == 'AG' ) $country = 'Antigua and Barbuda';
        if( $code == 'AR' ) $country = 'Argentina';
        if( $code == 'AM' ) $country = 'Armenia';
        if( $code == 'AW' ) $country = 'Aruba';
        if( $code == 'AU' ) $country = 'Australia';
        if( $code == 'AT' ) $country = 'Austria';
        if( $code == 'AZ' ) $country = 'Azerbaijan';
        if( $code == 'BS' ) $country = 'Bahamas the';
        if( $code == 'BH' ) $country = 'Bahrain';
        if( $code == 'BD' ) $country = 'Bangladesh';
        if( $code == 'BB' ) $country = 'Barbados';
        if( $code == 'BY' ) $country = 'Belarus';
        if( $code == 'BE' ) $country = 'Belgium';
        if( $code == 'BZ' ) $country = 'Belize';
        if( $code == 'BJ' ) $country = 'Benin';
        if( $code == 'BM' ) $country = 'Bermuda';
        if( $code == 'BT' ) $country = 'Bhutan';
        if( $code == 'BO' ) $country = 'Bolivia';
        if( $code == 'BA' ) $country = 'Bosnia and Herzegovina';
        if( $code == 'BW' ) $country = 'Botswana';
        if( $code == 'BV' ) $country = 'Bouvet Island (Bouvetoya)';
        if( $code == 'BR' ) $country = 'Brazil';
        if( $code == 'IO' ) $country = 'British Indian Ocean Territory (Chagos Archipelago)';
        if( $code == 'VG' ) $country = 'British Virgin Islands';
        if( $code == 'BN' ) $country = 'Brunei Darussalam';
        if( $code == 'BG' ) $country = 'Bulgaria';
        if( $code == 'BF' ) $country = 'Burkina Faso';
        if( $code == 'BI' ) $country = 'Burundi';
        if( $code == 'KH' ) $country = 'Cambodia';
        if( $code == 'CM' ) $country = 'Cameroon';
        if( $code == 'CA' ) $country = 'Canada';
        if( $code == 'CV' ) $country = 'Cape Verde';
        if( $code == 'KY' ) $country = 'Cayman Islands';
        if( $code == 'CF' ) $country = 'Central African Republic';
        if( $code == 'TD' ) $country = 'Chad';
        if( $code == 'CL' ) $country = 'Chile';
        if( $code == 'CN' ) $country = 'China';
        if( $code == 'CX' ) $country = 'Christmas Island';
        if( $code == 'CC' ) $country = 'Cocos (Keeling) Islands';
        if( $code == 'CO' ) $country = 'Colombia';
        if( $code == 'KM' ) $country = 'Comoros the';
        if( $code == 'CD' ) $country = 'Congo';
        if( $code == 'CG' ) $country = 'Congo the';
        if( $code == 'CK' ) $country = 'Cook Islands';
        if( $code == 'CR' ) $country = 'Costa Rica';
        if( $code == 'CI' ) $country = 'Cote d\'Ivoire';
        if( $code == 'HR' ) $country = 'Croatia';
        if( $code == 'CU' ) $country = 'Cuba';
        if( $code == 'CY' ) $country = 'Cyprus';
        if( $code == 'CZ' ) $country = 'Czech Republic';
        if( $code == 'DK' ) $country = 'Denmark';
        if( $code == 'DJ' ) $country = 'Djibouti';
        if( $code == 'DM' ) $country = 'Dominica';
        if( $code == 'DO' ) $country = 'Dominican Republic';
        if( $code == 'EC' ) $country = 'Ecuador';
        if( $code == 'EG' ) $country = 'Egypt';
        if( $code == 'SV' ) $country = 'El Salvador';
        if( $code == 'GQ' ) $country = 'Equatorial Guinea';
        if( $code == 'ER' ) $country = 'Eritrea';
        if( $code == 'EE' ) $country = 'Estonia';
        if( $code == 'ET' ) $country = 'Ethiopia';
        if( $code == 'FO' ) $country = 'Faroe Islands';
        if( $code == 'FK' ) $country = 'Falkland Islands (Malvinas)';
        if( $code == 'FJ' ) $country = 'Fiji the Fiji Islands';
        if( $code == 'FI' ) $country = 'Finland';
        if( $code == 'FR' ) $country = 'France, French Republic';
        if( $code == 'GF' ) $country = 'French Guiana';
        if( $code == 'PF' ) $country = 'French Polynesia';
        if( $code == 'TF' ) $country = 'French Southern Territories';
        if( $code == 'GA' ) $country = 'Gabon';
        if( $code == 'GM' ) $country = 'Gambia the';
        if( $code == 'GE' ) $country = 'Georgia';
        if( $code == 'DE' ) $country = 'Germany';
        if( $code == 'GH' ) $country = 'Ghana';
        if( $code == 'GI' ) $country = 'Gibraltar';
        if( $code == 'GR' ) $country = 'Greece';
        if( $code == 'GL' ) $country = 'Greenland';
        if( $code == 'GD' ) $country = 'Grenada';
        if( $code == 'GP' ) $country = 'Guadeloupe';
        if( $code == 'GU' ) $country = 'Guam';
        if( $code == 'GT' ) $country = 'Guatemala';
        if( $code == 'GG' ) $country = 'Guernsey';
        if( $code == 'GN' ) $country = 'Guinea';
        if( $code == 'GW' ) $country = 'Guinea-Bissau';
        if( $code == 'GY' ) $country = 'Guyana';
        if( $code == 'HT' ) $country = 'Haiti';
        if( $code == 'HM' ) $country = 'Heard Island and McDonald Islands';
        if( $code == 'VA' ) $country = 'Holy See (Vatican City State)';
        if( $code == 'HN' ) $country = 'Honduras';
        if( $code == 'HK' ) $country = 'Hong Kong';
        if( $code == 'HU' ) $country = 'Hungary';
        if( $code == 'IS' ) $country = 'Iceland';
        if( $code == 'IN' ) $country = 'India';
        if( $code == 'ID' ) $country = 'Indonesia';
        if( $code == 'IR' ) $country = 'Iran';
        if( $code == 'IQ' ) $country = 'Iraq';
        if( $code == 'IE' ) $country = 'Ireland';
        if( $code == 'IM' ) $country = 'Isle of Man';
        if( $code == 'IL' ) $country = 'Israel';
        if( $code == 'IT' ) $country = 'Italy';
        if( $code == 'JM' ) $country = 'Jamaica';
        if( $code == 'JP' ) $country = 'Japan';
        if( $code == 'JE' ) $country = 'Jersey';
        if( $code == 'JO' ) $country = 'Jordan';
        if( $code == 'KZ' ) $country = 'Kazakhstan';
        if( $code == 'KE' ) $country = 'Kenya';
        if( $code == 'KI' ) $country = 'Kiribati';
        if( $code == 'KP' ) $country = 'Korea';
        if( $code == 'KR' ) $country = 'Korea';
        if( $code == 'KW' ) $country = 'Kuwait';
        if( $code == 'KG' ) $country = 'Kyrgyz Republic';
        if( $code == 'LA' ) $country = 'Lao';
        if( $code == 'LV' ) $country = 'Latvia';
        if( $code == 'LB' ) $country = 'Lebanon';
        if( $code == 'LS' ) $country = 'Lesotho';
        if( $code == 'LR' ) $country = 'Liberia';
        if( $code == 'LY' ) $country = 'Libyan Arab Jamahiriya';
        if( $code == 'LI' ) $country = 'Liechtenstein';
        if( $code == 'LT' ) $country = 'Lithuania';
        if( $code == 'LU' ) $country = 'Luxembourg';
        if( $code == 'MO' ) $country = 'Macao';
        if( $code == 'MK' ) $country = 'Macedonia';
        if( $code == 'MG' ) $country = 'Madagascar';
        if( $code == 'MW' ) $country = 'Malawi';
        if( $code == 'MY' ) $country = 'Malaysia';
        if( $code == 'MV' ) $country = 'Maldives';
        if( $code == 'ML' ) $country = 'Mali';
        if( $code == 'MT' ) $country = 'Malta';
        if( $code == 'MH' ) $country = 'Marshall Islands';
        if( $code == 'MQ' ) $country = 'Martinique';
        if( $code == 'MR' ) $country = 'Mauritania';
        if( $code == 'MU' ) $country = 'Mauritius';
        if( $code == 'YT' ) $country = 'Mayotte';
        if( $code == 'MX' ) $country = 'Mexico';
        if( $code == 'FM' ) $country = 'Micronesia';
        if( $code == 'MD' ) $country = 'Moldova';
        if( $code == 'MC' ) $country = 'Monaco';
        if( $code == 'MN' ) $country = 'Mongolia';
        if( $code == 'ME' ) $country = 'Montenegro';
        if( $code == 'MS' ) $country = 'Montserrat';
        if( $code == 'MA' ) $country = 'Morocco';
        if( $code == 'MZ' ) $country = 'Mozambique';
        if( $code == 'MM' ) $country = 'Myanmar';
        if( $code == 'NA' ) $country = 'Namibia';
        if( $code == 'NR' ) $country = 'Nauru';
        if( $code == 'NP' ) $country = 'Nepal';
        if( $code == 'AN' ) $country = 'Netherlands Antilles';
        if( $code == 'NL' ) $country = 'Netherlands the';
        if( $code == 'NC' ) $country = 'New Caledonia';
        if( $code == 'NZ' ) $country = 'New Zealand';
        if( $code == 'NI' ) $country = 'Nicaragua';
        if( $code == 'NE' ) $country = 'Niger';
        if( $code == 'NG' ) $country = 'Nigeria';
        if( $code == 'NU' ) $country = 'Niue';
        if( $code == 'NF' ) $country = 'Norfolk Island';
        if( $code == 'MP' ) $country = 'Northern Mariana Islands';
        if( $code == 'NO' ) $country = 'Norway';
        if( $code == 'OM' ) $country = 'Oman';
        if( $code == 'PK' ) $country = 'Pakistan';
        if( $code == 'PW' ) $country = 'Palau';
        if( $code == 'PS' ) $country = 'Palestinian Territory';
        if( $code == 'PA' ) $country = 'Panama';
        if( $code == 'PG' ) $country = 'Papua New Guinea';
        if( $code == 'PY' ) $country = 'Paraguay';
        if( $code == 'PE' ) $country = 'Peru';
        if( $code == 'PH' ) $country = 'Philippines';
        if( $code == 'PN' ) $country = 'Pitcairn Islands';
        if( $code == 'PL' ) $country = 'Poland';
        if( $code == 'PT' ) $country = 'Portugal, Portuguese Republic';
        if( $code == 'PR' ) $country = 'Puerto Rico';
        if( $code == 'QA' ) $country = 'Qatar';
        if( $code == 'RE' ) $country = 'Reunion';
        if( $code == 'RO' ) $country = 'Romania';
        if( $code == 'RU' ) $country = 'Russian Federation';
        if( $code == 'RW' ) $country = 'Rwanda';
        if( $code == 'BL' ) $country = 'Saint Barthelemy';
        if( $code == 'SH' ) $country = 'Saint Helena';
        if( $code == 'KN' ) $country = 'Saint Kitts and Nevis';
        if( $code == 'LC' ) $country = 'Saint Lucia';
        if( $code == 'MF' ) $country = 'Saint Martin';
        if( $code == 'PM' ) $country = 'Saint Pierre and Miquelon';
        if( $code == 'VC' ) $country = 'Saint Vincent and the Grenadines';
        if( $code == 'WS' ) $country = 'Samoa';
        if( $code == 'SM' ) $country = 'San Marino';
        if( $code == 'ST' ) $country = 'Sao Tome and Principe';
        if( $code == 'SA' ) $country = 'Saudi Arabia';
        if( $code == 'SN' ) $country = 'Senegal';
        if( $code == 'RS' ) $country = 'Serbia';
        if( $code == 'SC' ) $country = 'Seychelles';
        if( $code == 'SL' ) $country = 'Sierra Leone';
        if( $code == 'SG' ) $country = 'Singapore';
        if( $code == 'SK' ) $country = 'Slovakia (Slovak Republic)';
        if( $code == 'SI' ) $country = 'Slovenia';
        if( $code == 'SB' ) $country = 'Solomon Islands';
        if( $code == 'SO' ) $country = 'Somalia, Somali Republic';
        if( $code == 'ZA' ) $country = 'South Africa';
        if( $code == 'GS' ) $country = 'South Georgia and the South Sandwich Islands';
        if( $code == 'ES' ) $country = 'Spain';
        if( $code == 'LK' ) $country = 'Sri Lanka';
        if( $code == 'SD' ) $country = 'Sudan';
        if( $code == 'SR' ) $country = 'Suriname';
        if( $code == 'SJ' ) $country = 'Svalbard & Jan Mayen Islands';
        if( $code == 'SZ' ) $country = 'Swaziland';
        if( $code == 'SE' ) $country = 'Sweden';
        if( $code == 'CH' ) $country = 'Switzerland, Swiss Confederation';
        if( $code == 'SY' ) $country = 'Syrian Arab Republic';
        if( $code == 'TW' ) $country = 'Taiwan';
        if( $code == 'TJ' ) $country = 'Tajikistan';
        if( $code == 'TZ' ) $country = 'Tanzania';
        if( $code == 'TH' ) $country = 'Thailand';
        if( $code == 'TL' ) $country = 'Timor-Leste';
        if( $code == 'TG' ) $country = 'Togo';
        if( $code == 'TK' ) $country = 'Tokelau';
        if( $code == 'TO' ) $country = 'Tonga';
        if( $code == 'TT' ) $country = 'Trinidad and Tobago';
        if( $code == 'TN' ) $country = 'Tunisia';
        if( $code == 'TR' ) $country = 'Turkey';
        if( $code == 'TM' ) $country = 'Turkmenistan';
        if( $code == 'TC' ) $country = 'Turks and Caicos Islands';
        if( $code == 'TV' ) $country = 'Tuvalu';
        if( $code == 'UG' ) $country = 'Uganda';
        if( $code == 'UA' ) $country = 'Ukraine';
        if( $code == 'AE' ) $country = 'United Arab Emirates';
        if( $code == 'GB' ) $country = 'United Kingdom';
        if( $code == 'US' ) $country = 'United States of America';
        if( $code == 'UM' ) $country = 'United States Minor Outlying Islands';
        if( $code == 'VI' ) $country = 'United States Virgin Islands';
        if( $code == 'UY' ) $country = 'Uruguay, Eastern Republic of';
        if( $code == 'UZ' ) $country = 'Uzbekistan';
        if( $code == 'VU' ) $country = 'Vanuatu';
        if( $code == 'VE' ) $country = 'Venezuela';
        if( $code == 'VN' ) $country = 'Vietnam';
        if( $code == 'WF' ) $country = 'Wallis and Futuna';
        if( $code == 'EH' ) $country = 'Western Sahara';
        if( $code == 'YE' ) $country = 'Yemen';
        if( $code == 'ZM' ) $country = 'Zambia';
        if( $code == 'ZW' ) $country = 'Zimbabwe';
        if( $country == '') $country = $code;
        return $country;
    }

    public function secs_to_h($secs) {

        $t = round($secs);
        return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
    }

    private function delete_entries() {

        global $wpdb;

        $to_delete = $wpdb->get_results(
            $wpdb->prepare("SELECT DISTINCT(live_visitor_page_view_random_user) FROM {$wpdb->prefix}live_visitor_page_view WHERE UNIX_TIMESTAMP(live_visitor_page_view_end_time) < UNIX_TIMESTAMP(DATE('%s'))", date("Y-m-d", time()) ), ARRAY_A
        );

        foreach( $to_delete as $user ) {

            $wpdb->query("DELETE FROM {$wpdb->prefix}live_visitor_page_view WHERE live_visitor_page_view_random_user = '" . $user['live_visitor_page_view_random_user'] . "'");
            $wpdb->query("DELETE FROM {$wpdb->prefix}live_visitor_user WHERE live_visitor_page_view_random_user = '" . $user['live_visitor_page_view_random_user'] . "'");
        }
    }

    public static function save_redirect(){

        $current_host = $_SERVER['HTTP_HOST'];
        $host_name = parse_url($_POST["redirect"], PHP_URL_HOST);

        if ( $current_host == $host_name ) {

            echo json_encode(array("status" => "error", "message" => "Redirect URL cannot be your site"));
            die();

        } else {

            $input_value = str_replace("http://", "", $_POST["redirect"]);
            $pattern = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS';

            if ( !preg_match($pattern, "http://" . $input_value) ){

                echo json_encode(array("status" => "error", "message" => "Not a valid URL"));
                die();

            }else {

                echo json_encode(array("status" => "success"));
                update_option( "_real-time-stats-redirect", $input_value );
                die();
            }

        }

        die();
    }

    public static function add_ip() {

        $ip_address = $_POST["ip"];

        if ( !filter_var($ip_address, FILTER_VALIDATE_IP) ) {

            echo json_encode(array("status" => "error", "message" => "Not a valid IP address"));
            die();

        } else {

            global $wpdb;

            $count = $wpdb->get_var(
                $wpdb->prepare("SELECT count(*) FROM {$wpdb->prefix}live_ban_list WHERE ip_address = '%s'", $ip_address)
            );

            if ( $count ){

                echo json_encode(array("status" => "error", "message" => "IP Address is already banned"));
                die();

            } else {

                $current_ip = $_SERVER["REMOTE_ADDR"];

                if ( $current_ip == $ip_address ){

                    echo json_encode(array("status" => "error", "message" => "You can't ban yourself"));
                    die();

                }else {

                    $wpdb->query(
                        $wpdb->prepare("INSERT INTO {$wpdb->prefix}live_ban_list (ip_address) VALUES ('%s')", $ip_address)
                    );


                    echo json_encode(array("status" => "success", "data" => array("ip_address" => $ip_address, "time" => date("jS F Y", time()), "id" => $wpdb->insert_id)));
                    die();

                }



            }
        }
    }

    public static function remove_ban(){

        global $wpdb;
        $wpdb->show_errors = true;

        $wpdb->query(
            $wpdb->prepare("DELETE FROM {$wpdb->prefix}live_ban_list WHERE id = %d", $_POST["id"])
        );

        if ( $wpdb->last_error ) {

            echo json_encode(array("status" => "error"));
            die();

        }else {

            echo json_encode(array("status" => "success"));
            die();
        }


    }
}