<?php

/*
 * Copyright © 2020 Miguel Nogueira
 *
 *   This file is part of Raspberry Staff Manager.
 *
 *     Raspberry Staff Manager is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Raspberry Staff Manager is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Raspberry Staff Manager.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Mpociot\Teamwork\Traits\UserHasTeams;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use UserHasTeams, Notifiable, HasRoles, HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'originalIP',
        'registrationIp',
        'username',
        'uuid',
        'dob',
        'email_verified_at',
        'currentIp',
        'discord_user_id',
        'discord_token',
        'discord_refresh_token',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'discord_token' => 'encrypted',
        'discord_refresh_token' => 'encrypted',
    ];

    // RELATIONSHIPS

    public function applications()
    {
        return $this->hasMany('App\Application', 'applicantUserID', 'id');
    }

    public function votes()
    {
        return $this->hasMany('App\Vote', 'userID', 'id');
    }

    public function profile()
    {
        return $this->hasOne('App\Profile', 'userID', 'id');
    }

    public function bans()
    {
        return $this->hasOne('App\Ban', 'userID', 'id');
    }

    public function comments()
    {
        return $this->hasMany('App\Comment', 'authorID', 'id');
    }

    public function files()
    {
        return $this->hasMany('App\TeamFile', 'uploaded_by');
    }

    public function absences()
    {
        return $this->hasMany('App\Absence', 'requesterID');
    }

    public function isEligible(): bool
    {
        $lastApplication = Application::where('applicantUserID', $this->getAttribute('id'))->latest()->first();

        if (is_null($lastApplication)) {
            return true;
        }

        if ($lastApplication->created_at->diffInMonths(now()) > 1 && in_array($lastApplication->applicationStatus, ['DENIED', 'APPROVED'])) {
            return true;
        }

        return false;
    }

    public function isVerified(): bool
    {
        return ! is_null($this->email_verified_at);
    }

    /**
     * Checks if user is staff
     *
     * @deprecated This method is being replaced by a better way of checking permissions, rather than checking for group name.
     *
     * @return bool
     */
    public function isStaffMember(): bool
    {
        return $this->hasAnyRole('reviewer', 'admin', 'hiringManager');
    }

    /**
     * Checks if user has 2fa enabled
     *
     * @return bool
     */
    public function has2FA(): bool
    {
        return ! is_null($this->twofa_secret);
    }

    /**
     * Checks if user has team
     *
     * @param $team
     * @return bool
     */
    public function hasTeam($team): bool
    {
        if ($team instanceof Team || is_int($team)) {
            return $this->teams->contains($team);
        } else {
            /**
             * In PHP 8, we can just use union types and let PHP enforce this for us.
             */
            throw new \InvalidArgumentException('Please pass either a Team object or an integer identifying a Team.');
        }
    }

    /**
     * Check if user linked their Discord account
     *
     * @return bool
     */
    public function hasDiscordConnection(): bool
    {
        return ! is_null($this->discord_token) && ! is_null($this->discord_refresh_token);
    }

    /**
     * Check if user has a password
     *
     * @return bool
     */
    public function hasPassword(): bool
    {
        return ! is_null($this->password);
    }

    /**
     * Returns profile url.
     * TODO: Find nicer way to do this
     * @return string
     */
    public function adminlte_profile_url(): string
    {
        return route('showSingleProfile', ['user' => $this->id]);
    }
}
