<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;

use App\Notifications\ResetPasswordNotification;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

/**
 * @mixin IdeHelperUser
 */
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public function consultantProfile()
    {
        return $this->hasOne(ConsultantProfile::class);
    }

    public function company()
    {
        return $this->hasOne(Company::class);
    }

    public function permissions()
    {
        return $this->belongsToMany(
            Permission::class,
            'user_permissions',
            'user_id',
            'permission_id'
        )->withTimestamps();
    }

    public function hasPermission(string $permissionKey): bool
    {
        return $this->permissions()
            ->where('key', $permissionKey)
            ->where('is_active', true)
            ->exists();
    }

    public function savedListings()
    {
        return $this->belongsToMany(Listing::class, 'saved_listings')->withTimestamps();
    }

    public function blogPosts()
    {
        return  $this->hasMany(BlogPost::class, 'author_id');
    }


    public function buyerConversations()
    {
        return $this->hasMany(
            Conversation::class,
            'buyer_id'
        );
    }

    public function sentMessages()
    {
        return $this->hasMany(
            Message::class,
            'sender_id'
        );
    }

    public function recentlyViewedListings()
    {
        return $this->hasMany(RecentlyViewedListing::class);
    }

    public function notedListing()
    {
        return $this->hasMany(ListingNotes::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function logs()
    {
        return $this->hasMany(AuditLogs::class);
    }

    public function sendPasswordResetNotification($token): void
    {
        $this->notify(
            new ResetPasswordNotification($token)
        );
    }
}
