<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo; 

#[Fillable([
    'name', 'username', 'store_slug', 'email', 'phone', 'country_id', 'password', 'role', 'managed_store_id', 
    'avatar_path', 'cover_path', 'store_avatar_path', 'store_cover_path',
    'company_name', 'business_type', 'established_year', 'company_overview','flash_sale_percentage',
    'main_products', 'total_employees',
    'contact_email', 'contact_phone', 'contact_whatsapp', 'contact_messenger', 'contact_options', 'two_factor_secret', 'two_factor_recovery_codes', 'two_factor_confirmed_at'
])]
#[Hidden(['password', 'remember_token', 'two_factor_secret', 'two_factor_recovery_codes'])]
class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable;

    /**
     * Get the country that the user belongs to.
     */
    public function country(): BelongsTo
    {
        return $this->belongsTo(Country::class);
    }

    protected $appends = ['has_2fa_enabled'];

    // Add the accessor method
    public function getHas2faEnabledAttribute(): bool
    {
        return !is_null($this->two_factor_secret) && !is_null($this->two_factor_confirmed_at);
    }

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'contact_options' => 'array',
            'two_factor_confirmed_at' => 'datetime', 
        ];
    }

    public function favorites(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'favorites', 'user_id', 'product_id')->withTimestamps();
    }

    public function managedStore(): BelongsTo
    {
        return $this->belongsTo(User::class, 'managed_store_id');
    }

    public function managers()
    {
        return $this->hasMany(User::class, 'managed_store_id');
    }

}
