<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use \Request;
use \Session;
use App\Log;

/**
 * App\User
 *
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @mixin \Eloquent
 * @property int $id
 * @property string $name
 * @property int $level
 * @property int $server
 * @property string $password
 * @property int $lastserver
 * @property string $lastip
 * @property string|null $lastlogin
 * @property string|null $remenber_token
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereLastip($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereLastlogin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereLastserver($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User wherePassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereRemenberToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereServer($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\User whereUpdatedAt($value)
 */
class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function GetClientIP() {
        $ipAddress = $_SERVER['REMOTE_ADDR'];
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
            $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        return $ipAddress;
    }

    public static function getAll() {
        return User::orderBy('level', 'desc')->paginate(10);
    }

    public static function getName() {
        return Session::get('user');
    }

    public static function CheckActiveAdmin() {
        $value = Session::get('user');

        $user = User::where('name', $value)->first();
        if(empty($user)) {
            Log::AddLog(11, $value, '-', User::GetClientIP());
            Session::flush();
            return 'Возникла ошибка: Вы не модератор';
        }

        if($user->lastip != User::GetClientIP()) {
            Log::AddLog(12, $value, $user->lastip, User::GetClientIP());
            Session::flush();
            return 'Возникла ошибка: Ваш IP адрес сменился, авторизуйтесь на вашем основном сервере';
        }

        return 'success';
    }

    public static function IsManagePermissions() {
        $value = Session::get('user');

        $user = User::where('name', $value)->first();
        if(empty($user)) return 'Неизвестная ошибка: админа нет в базе';
        if($user->level < 9) return 'Вам недоступна данная функция';

        return 'success';
    }

    public static function SetPassword($nick, $new) {
        $user = User::where('name', $nick)->first();

        if(empty($user)) return 'Админа нет в базе';
        if(strlen($new) < 6 || strlen($new) > 15) return 'Новый пароль должен быть от 6 до 15 символов!';

        $user->password = md5($new);
        $user->save();

        return 'success';
    }

    public static function SetLastIP($nick, $ip) {
        $user = User::where('name', $nick)->first();

        if(empty($user)) return 'Админа нет в базе';

        $user->lastip = $ip;
        $user->save();

        return 'success';
    }

    public static function SetLevel($nick, $level) {
        $user = User::where('name', $nick)->first();

        if(empty($user)) return 'Админа нет в базе';

        $user->level = $level;
        $user->save();

        return 'success';
    }

    public static function SetServer($nick, $server) {
        $user = User::where('name', '=', $nick)->first();

        if(empty($user)) return 'Админа нет в базе';
        $user->server = $server;
        $user->save();

        return 'success';
    }


    public static function ChangePassword($new_password) {
        $user = User::where('name', Session::get('user'))->first();
        $user->password = md5($new_password);
        $user->save();
        
        Log::AddLog(10, \Session::get('user'), '-', User::GetClientIP());
        
        return 'success';
    }
    
    public static function AddNewAdmin($nick, $level, $server) {
        $user = new User();
        $user->name = $nick;
        $user->level = $level;
        $user->password = '-';
        $user->server = $server;
        $user->lastserver = 0;
        $user->lastip = '-';
        $user->save();
        
        Log::AddLog(0, User::getName(), $nick, '-');
        
        return 'success';
    }
    
    public static function UpAdmin($nick) {
        $user = User::where('name', $nick)->first();
        $user->increment('level');
        $user->save();
        
        Log::AddLog(2, User::getName(), $nick, $user->level);
        
        return 'success';
    }
    
    public static function DownAdmin($nick) {
        $user = User::where('name', $nick)->first();
        $user->decrement('level');
        $user->save();

        Log::AddLog(3, User::getName(), $nick, $user->level);
        
        return 'success';
    }
    
    public static function DelAdmin($nick) {
        User::where('name', $nick)->delete();
        
        Log::AddLog(1, User::getName(), $nick, '-');
        
        return 'success';
    }

    public static function getUser($name) {
        return User::where('name', $name)->first();
    }
}
