<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

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

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

    // Relationships
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function memberProfile()
    {
        return $this->hasOne(MemberProfile::class);
    }

    public function member_profile()
    {
        return $this->memberProfile();
    }

    public function leasingProfile()
    {
        return $this->hasOne(LeasingProfile::class);
    }

    // Alias for view/snake_case compatibility
    public function leasing_profile()
    {
        return $this->leasingProfile();
    }

    public function subscriptions()
    {
        return $this->hasMany(Subscription::class);
    }

    public function activeSubscription()
    {
        return $this->hasOne(Subscription::class)->where('subscription_status', 'active');
    }

    // Helpers
    public function isAdmin(): bool
    {
        return $this->role && $this->role->name === 'admin';
    }

    public function isLeasing(): bool
    {
        return $this->role && $this->role->name === 'leasing';
    }

    public function isMember(): bool
    {
        return $this->role && $this->role->name === 'member';
    }

    public function isActive(): bool
    {
        if ($this->isAdmin()) return true;
        
        // At the very least, account must be active (not suspended/pending)
        if ($this->account_status !== 'active') return false;

        // If the admin has manually set the user to 'active', 
        // they should be able to at least access the portal.
        return true;
    }
}
