<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use OwenIt\Auditing\Contracts\Auditable;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Str;

class User extends Authenticatable implements Auditable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes, HasRoles;
    use \OwenIt\Auditing\Auditable;

    protected $fillable = [
        'uid', 'name', 'email', 'nuit', 'password', 'phone',
        'account_type', 'status', 'company_name', 'country',
        'address', 'avatar_url', 'last_login_at', 'last_login_ip',
    ];

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

    protected $auditExclude = ['password', 'remember_token', 'last_login_ip'];

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

    protected static function boot(): void
    {
        parent::boot();
        static::creating(function (User $user) {
            do {
                $uid = strtoupper(Str::random(8));
            } while (self::where('uid', $uid)->exists());
            $user->uid = $uid;
        });
    }

    public function isAdmin(): bool { return $this->hasRole(['admin', 'super_admin']); }
    public function isSuperAdmin(): bool { return $this->hasRole('super_admin'); }
    public function isInvestor(): bool { return $this->hasRole('investor'); }

    public function proposals(): HasMany { return $this->hasMany(InvestmentProposal::class); }
    public function expressionsOfInterest(): HasMany { return $this->hasMany(ExpressionOfInterest::class); }
    public function meetings(): HasMany { return $this->hasMany(Meeting::class, 'investor_id'); }
    public function sentMessages(): HasMany { return $this->hasMany(Message::class, 'sender_id'); }
    public function receivedMessages(): HasMany { return $this->hasMany(Message::class, 'receiver_id'); }
}
