<?php

namespace App\Models;

use App\Scopes\DailyCountBetweenDate;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable, DailyCountBetweenDate;

    protected $fillable = [
        'stripe_id',
        'plan_id',
        'name',
        'email',
        'photo',
        'auth_token',
        'verify_token',
        'otp',
        'blocked',
        'admin',
    ];

    protected $hidden = [
        'auth_token',
        'verify_token',
        'otp',
    ];

    protected function casts(): array
    {
        return [
            'blocked' => 'boolean',
            'admin' => 'boolean'
        ];
    }

    public function scopeExcludeAdmin(Builder $query)
    {
        return $query->where('admin', false);
    }

    public function favoriteds()
    {
        return $this->belongsToMany(Page::class, 'favoriteds');
    }

    public function coloreds()
    {
        return $this->hasMany(Colored::class);
    }

    public function coloredPages()
    {
        return $this->belongsToMany(Page::class, Colored::class);
    }

    public function pages()
    {
        return $this->hasMany(Page::class);
    }

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

    public function subscription()
    {
        return $this->hasOne(Subscription::class)->latestOfMany();
    }

    public function activeSubscription()
    {
        return $this->hasOne(Subscription::class)
            ->latestOfMany()
            ->whereNull('canceled_at');
    }

    public function plan()
    {
        return $this->belongsTo(Plan::class);
    }

    public function credit()
    {
        return $this->hasOne(Credit::class);
    }
}
