<?php

namespace App\Laravue\Models;

use App\Category;
use App\Counseling;
use App\Photo;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Laravel\Sanctum\HasApiTokens;

/**
 * Class User
 *
 * @property string $name
 * @property string $email
 * @property string $password
 * @property Role[] $roles
 *
 * @method static User create(array $user)
 * @package App
 */
class User extends Authenticatable
{
    use Notifiable, HasRoles, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'slug', 'full_name', 'furigana_name', 'email', 'password', 'avatar', 'gender', 'age',
        'post_code', 'address', 'address2', 'line_id', 'phone_number', 'career', 'qualification', 'introduction',
        'contact_method', 'counseling_id', 'reset_password_code', 'reset_password_time', 'login_url', 'created_by', 'created_at', 'updated_at',
    ];

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

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

    protected $appends = ['projectCount', 'posterCount'];

    /**
     * Set permissions guard to API by default
     * @var string
     */
    protected $guard_name = 'api';

    /**
     * @inheritdoc
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @inheritdoc
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * Check if user has a permission
     * @param String
     * @return bool
     */
    public function hasPermission($permission): bool
    {
        foreach ($this->roles as $role) {
            if (in_array($permission, $role->permissions->toArray())) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return bool
     */
    public function isAdmin(): bool
    {
        foreach ($this->roles as $role) {
            if ($role->isAdmin()) {
                return true;
            }
        }

        return false;
    }

    public function counseling() {
        return $this->belongsTo(Counseling::class, 'counseling_id', 'id')->select('id', 'title', 'description');
    }

    public function project() {
        return $this->hasMany(Category::class, 'user_id', 'id');
    }

    public function getProjectCountAttribute() {
        return $this->project()->count();
    }

    public function poster() {
        return $this->hasMany(Photo::class, 'assigned_id', 'id');
    }

    public function getPosterCountAttribute() {
        return $this->poster()->count();
    }
}
