<?php

class ThemeMakersUser {

    public function __construct() {

    }

    public static function get_profile_url($user_id = 0) {
      //  $profile_url = ThemeMakersThemeModel::get_option("user_profile_link");
        if ($user_id > 0) {
            $profile_url.="?author=" . $user_id;
        }

        return $profile_url;
    }

    public static function init() {

        function my_new_contactmethods($contactmethods) {
            $contactmethods['twitter'] = 'Twitter';
            $contactmethods['facebook'] = 'Facebook';
            $contactmethods['icq'] = 'ICQ';
            $contactmethods['skype'] = 'Skype';
            return $contactmethods;
        }

        add_filter('user_contactmethods', 'my_new_contactmethods', 10, 1);
    }

    public static function logout() {
        wp_logout();
    }

    public static function login() {
        $user_login = trim($_REQUEST['user_login']);
        $user_pass = trim($_REQUEST['user_pass']);
        //*****
        if (user_pass_ok($user_login, $user_pass)) {
            $credentials['user_login'] = $user_login;
            $credentials['user_password'] = $user_pass;
            $credentials['remember'] = true;
            $user = wp_signon($credentials, false);
            if (is_wp_error($user))
                echo 0;
            else
                echo 1;
            exit;
        }
        echo 0;
        exit;
    }

    public static function register() {
        $user_name = trim($_REQUEST['login_name']);
        $user_email = trim($_REQUEST['user_email']);

        if (!is_email($user_email)) {
            _e('Wrong email!', THEMEMAKERS_THEME_FOLDER_NAME);
            exit;
        }

        $user_id = username_exists($user_name);
        if (!$user_id AND email_exists($user_email) == false) {
            $random_password = wp_generate_password();
            $user_id = wp_create_user($user_name, $random_password, $user_email);
            //*****
            update_user_option($user_id, THEMEMAKERS_APP_MAIL_SUBSCRIBER_PREFIX . 'user_group', Application_Mail_Subscriber::get_users_groups());
            //*****
            $subject = __("User registration", THEMEMAKERS_THEME_FOLDER_NAME);
            $content = ThemeMakersThemeModel::get_option("user_registration_text");
            if (empty($content)) {
                $content = 'Hello __USERNAME__! Your password is: __PASSWORD__';
            }

            $content = str_replace("__USERNAME__", $user_name, $content);
            $content = str_replace("__PASSWORD__", $random_password, $content);

            self::send_email($user_email, $content, $subject);
            _e('A password e-mailed to you.', THEMEMAKERS_THEME_FOLDER_NAME);
            exit;
        }

        _e('User already exists. Password inherited.', THEMEMAKERS_THEME_FOLDER_NAME);
        exit;
    }

    public static function send_email($email, $content, $subject) {
        $attachments = array();
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        $headers .= 'To: <' . $email . '>' . "\r\n";
        $headers .= 'From: ' . get_option("blogname") . ' <' . $subject . '>' . "\r\n";
        add_filter('wp_mail_content_type', create_function('', 'return "text/html"; '));
        return wp_mail($email, $subject, $content, $headers, $attachments);
    }
    

    public static function get_user_info($user_id) {
        $user_info = get_userdata($user_id);
        $user = array();
        $user['user_id'] = $user_id;
        $user['user_role'] = $user_info->roles[0];
        $user['nickname'] = $user_info->nickname;
        $user['user_login'] = $user_info->user_login;
        $user['first_name'] = $user_info->first_name;
        $user['last_name'] = $user_info->last_name;
        $user['twitter'] = get_the_author_meta('twitter', $user_id);
        $user['facebook'] = get_the_author_meta('facebook', $user_id);
        $user['jabber'] = get_the_author_meta('jabber', $user_id);
        $user['skype'] = get_the_author_meta('skype', $user_id);
        $user['icq'] = get_the_author_meta('icq', $user_id);
        $user['yim'] = get_the_author_meta('yim', $user_id);
        $user['aim'] = get_the_author_meta('aim', $user_id);
        $user['url'] = get_the_author_meta('url', $user_id);
        $user['email'] = get_the_author_meta('email', $user_id);
        $user['description'] = get_the_author_meta('description', $user_id);
		//$user['avatar']= get_the_author_meta('upload_avatar', $user_id);
        //*****
        $user['youtube_items'] = get_the_author_meta('youtube_items', $user_id);
        //*****

        $my_games = get_the_author_meta('my_games', $user_id);

        if (!empty($my_games)) {
            $my_games = implode(',', $my_games);
            $user['my_games_consoles'] = get_the_author_meta('my_games_consoles', $user_id);

            global $wpdb;
            $user['my_games'] = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID IN($my_games) AND post_type= 'games' AND post_status='publish'");
        } else {
            $user['my_games'] = array();
        }

        return $user;
    }

    public static function save_user_profile() {
        $user_id = get_current_user_id();
        if (!$user_id) {
            return;
        }
        $data = array();
        parse_str($_REQUEST['values'], $data);

        if (!empty($data['nickname'])) {
            update_user_meta($user_id, 'nickname', $data['nickname']);
        }

        if (!empty($data['subscribe_themes'])) {
            $subscribe_themes = array();
            foreach ($data['subscribe_themes'] as $theme_name => $perm) {
                if ($perm != 0) {
                    $subscribe_themes[] = $theme_name;
                }
            }
            Application_Mail_Subscriber::update_user_subscription($user_id, $subscribe_themes);
        }

        update_user_meta($user_id, 'first_name', $data['first_name']);
        update_user_meta($user_id, 'last_name', $data['last_name']);
        update_user_meta($user_id, 'twitter', $data['twitter']);
        update_user_meta($user_id, 'facebook', $data['facebook']);
        update_user_meta($user_id, 'url', $data['url']);
        update_user_meta($user_id, 'aim', $data['aim']);
        update_user_meta($user_id, 'yim', $data['yim']);
        update_user_meta($user_id, 'jabber', $data['jabber']);
        update_user_meta($user_id, 'skype', $data['skype']);
        update_user_meta($user_id, 'icq', $data['icq']);
        update_user_meta($user_id, 'description', $data['description']);
		//update_user_meta($user_id, 'upload_avatar', $data['avatar']);
        //*****
        @update_user_meta($user_id, 'youtube_items', @$data['youtube_items']);
			
        @update_user_meta($user_id, 'my_games', @$data['my_games']);
        self::update_game_using_stat($user_id, @$data['my_games']);
        @update_user_meta($user_id, 'my_games_consoles', $data['my_games_consoles']);

		
        exit;
    }
	


	public static function update_game_using_stat($user_id, $users_games) {
        $users_use_games = ThemeMakersThemeModel::get_option("users_use_games");
        if (empty($users_use_games)) {
            $users_use_games = array();
        }
        //clean of user with $user_id
        if (!empty($users_use_games)) {
            foreach ($users_use_games as $key => $users) {
                if (!empty($users)) {
                    foreach ($users as $key2 => $u_id) {
                        if ($user_id == $u_id) {
                            unset($users_use_games[$key][$key2]);
                        }
                    }
                }
            }
        }
        //*****
        if (!empty($users_games)) {
            foreach ($users_games as $game_id) {
                if (!isset($users_use_games[$game_id])) {
                    $users_use_games[$game_id] = array();
                }

                array_push($users_use_games[$game_id], $user_id);
                $users_use_games[$game_id] = array_unique($users_use_games[$game_id], SORT_NUMERIC);
            }
        }

        ThemeMakersThemeModel::update_option('users_use_games', $users_use_games);
    }

    public static function get_game_using_stat($game_id) {
        $users_use_games = ThemeMakersThemeModel::get_option("users_use_games");
        $result = array();
        if (isset($users_use_games[$game_id])) {
            $result = $users_use_games[$game_id];
        }
        return $result;
    }

    public static function add_user_to_favourites() {
        $current_user_id = get_current_user_id();
        $fav_user_id = $_REQUEST['user_id'];
        if (!$current_user_id OR $current_user_id == $fav_user_id) {
            return;
        }

        $favourites_users = self::get_favourites_users_ids($current_user_id);
        if (!in_array($fav_user_id, $favourites_users)) {
            $favourites_users[] = $fav_user_id;
            @update_user_meta($current_user_id, 'favourites_users', $favourites_users);
        } else {
            echo 'already_exists';
            exit;
        }

        echo 'succsess';
        exit;
    }

    public static function delete_favourite_user() {
        $current_user_id = get_current_user_id();
        $fav_user_id = $_REQUEST['user_id'];
        if (!$current_user_id) {
            return;
        }
        $favourites_users = self::get_favourites_users_ids($current_user_id);
        if (!empty($favourites_users)) {
            foreach ($favourites_users as $key => $user_id) {
                if ($user_id == $fav_user_id) {
                    unset($favourites_users[$key]);
                    break;
                }
            }
        }

        @update_user_meta($current_user_id, 'favourites_users', $favourites_users);
        exit;
    }

    public static function get_favourites_users_ids($user_id) {
        $favourites_users = get_the_author_meta('favourites_users', $user_id);
        if (empty($favourites_users)) {
            $favourites_users = array();
        }
        return $favourites_users;
    }

    public static function get_favourites_users($user_id) {
        $favourites_users = self::get_favourites_users_ids($user_id);
        $favourites_users = implode(',', $favourites_users);
        if (!empty($favourites_users)) {
            global $wpdb;
            $favourites_users = $wpdb->get_results("SELECT ID, user_nicename, display_name  FROM $wpdb->users WHERE ID IN($favourites_users)");
        } else {
            return array();
        }
        return $favourites_users;
    }

    public static function is_user_in_favourites($user_id) {
        $favourites_users = self::get_favourites_users_ids(get_current_user_id());

        if (in_array($user_id, $favourites_users)) {
            return true;
        }


        return false;
    }

}

