<?php

namespace App\Models;

use App\Notifications\TemplateResetPasswordNotification;
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', 'username', 'email', 'password', 'role', 'status',
        'avatar', 'bio', 'phone', 'country', 'website',
        'twitter', 'facebook', 'linkedin',
        'blogs_quota', 'blogs_used',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password'          => 'hashed',
        'blogs_quota'       => 'integer',
        'blogs_used'        => 'integer',
    ];

    /* ------------------------- Role Helpers ------------------------- */
    public function isSuperAdmin(): bool { return $this->role === 'superadmin'; }
    public function isReseller(): bool   { return $this->role === 'reseller'; }
    public function isUser(): bool       { return $this->role === 'user'; }

    public function blogsRemaining(): int
    {
        return max(0, ((int)$this->blogs_quota) - ((int)$this->blogs_used));
    }

    public function canWriteBlog(): bool
    {
        return $this->isReseller() && $this->blogsRemaining() > 0;
    }

    /* ---------------------------- Relations -------------------------- */
    public function blogs()    { return $this->hasMany(Blog::class); }
    public function invoices() { return $this->hasMany(Invoice::class); }
    public function payments() { return $this->hasMany(Payment::class); }

    public function avatarUrl(): string
    {
        $displayName = $this->displayName();
        if ($this->avatar) {
            return asset('uploads/avatars/' . $this->avatar);
        }
        // Generate gravatar-like fallback
        return 'https://ui-avatars.com/api/?name=' . urlencode($displayName)
             . '&background=1B3B2F&color=D4AF37&size=128';
    }

    public function displayName(): string
    {
        $name = trim((string) $this->name);
        if ($name !== '') {
            return $name;
        }

        $username = trim((string) $this->username);
        if ($username !== '') {
            return $username;
        }

        return (string) $this->email;
    }

    public function sendPasswordResetNotification($token): void
    {
        $this->notify(new TemplateResetPasswordNotification((string) $token));
    }
}
