<?php

namespace App\Models;

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',
        'password',
        'role',
        'points',
        'bio',
        'avatar',
        'phone',
        'status',
    ];

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

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

    // ── Role helpers ──────────────────────────────────────────
    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isModerator(): bool
    {
        return in_array($this->role, ['admin', 'moderator']);
    }

    public function isEditor(): bool
    {
        return in_array($this->role, ['admin', 'moderator', 'editor']);
    }

    public function hasRole(string $role): bool
    {
        return $this->role === $role;
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function getAvatarUrlAttribute(): string
    {
        if ($this->avatar) {
            return asset('storage/' . $this->avatar);
        }
        return 'https://ui-avatars.com/api/?name=' . urlencode($this->name) . '&background=random';
    }

    // ── Relationships ──────────────────────────────────────────
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }

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

    public function blogComments()
    {
        return $this->hasMany(BlogComment::class);
    }

    public function forumTopics()
    {
        return $this->hasMany(ForumTopic::class);
    }

    public function forumPosts()
    {
        return $this->hasMany(ForumPost::class);
    }

    public function interviewAttempts()
    {
        return $this->hasMany(InterviewAttempt::class);
    }

    public function interviewSimulations()
    {
        return $this->hasMany(InterviewSimulation::class);
    }

    public function notifications()
    {
        return $this->hasMany(Notification::class);
    }

    public function chatMessages()
    {
        return $this->hasMany(ChatMessage::class);
    }

    public function calculations()
    {
        return $this->hasMany(Calculation::class);
    }

    public function leaderboard()
    {
        return $this->hasMany(Leaderboard::class);
    }
}
