<?php

namespace App\Models;

use App\Notifications\User\VerifyEmailNotification;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $guarded = [
        'id'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'last_login' => 'datetime',
    ];

    protected $appends = [
        'name'
    ];

    public function products()
    {
        return $this->hasMany('App\Models\Product');
    }

    public function media()
    {
        return $this->hasMany('App\Models\Media');
    }

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

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

    public function getNameAttribute()
    {
        if (isset($this->first_name, $this->last_name)) {
            return $this->first_name . ' ' . $this->last_name;
        } else {
            return $this->email;
        }
    }

    public function sendEmailVerificationNotification()
    {
        $this->notify(new VerifyEmailNotification());
    }

    public function billingAddress(): HasOne
    {
        return $this->hasOne(BillingAddress::class, 'user_id');
    }

    public function tickets()
    {
        return $this->hasMany(Ticket::class);
    }

    public function ticketMessages()
    {
        return $this->hasMany(TicketMessage::class);
    }

    public function posts()
    {
        return $this->hasMany(BlogPost::class, 'author_id');
    }

    public function comments()
    {
        return $this->hasMany(PostComment::class);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }

    public function licenses()
    {
        return $this->hasMany(License::class);
    }

    public function meta()
    {
        return $this->hasMany(UserMeta::class);
    }
}
