<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'first_name',
        'last_name',
        'mobile',
        'password',
        'role',
        'mobile_verify',
        'status',
        'referrer',
    ];

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

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

    public function wallet(): HasOne
    {
        return $this->hasOne(Wallet::class);
    }

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

    public function wishes(): HasMany
    {
        return $this->hasMany(UserWish::class);
    }

    private ?array $wishedProductIds = null;

    public function hasWished(int $productId): bool
    {
        if ($this->wishedProductIds === null) {
            $this->wishedProductIds = $this->wishes()->pluck('product_id')->all();
        }

        return in_array($productId, $this->wishedProductIds, true);
    }

    public function announcementReads(): HasMany
    {
        return $this->hasMany(AnnouncementRead::class);
    }

    public function unreadAnnouncementsCount(): int
    {
        return Announcement::whereDoesntHave('reads', function ($q) {
            $q->where('user_id', $this->id);
        })->count();
    }
}
