<?php

namespace App\Models;

use App\Http\Traits\PasswordTrait;
use App\Http\Traits\StatusTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable, HasRoles, PasswordTrait, StatusTrait;

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    public static $rules = [
        "name" => 'required|max:255',
        "email" => 'required|email|max:255|unique:users,email,',
        'password' => 'same:confirm_password|min:8|',
        'confirm_password' => 'required_with:password',
        'role_id' => 'required|exists:roles,id|not_in:1,2,3',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */

    protected $appends = ['status_text', 'status_color'];
    protected function casts(): array
    {
        return [
            'password' => 'hashed',
        ];
    }


    public function scopeAdmin($query)
    {
        return $query->whereDoesntHave('roles', function ($q) {
            $q->where('name', 'superadmin');
        });
    }

    public function scopeFilter($query, $role)
    {
        $role = explode(',', $role);
        return $query->whereHas('roles', function ($q) use ($role) {
            $q->whereIn('name', $role);
        });
    }
}
