<?php

namespace App\Models\Shop;

use App\Notifications\ResetPassword;
use App\Notifications\VerifyEmail;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
use Venturecraft\Revisionable\RevisionableTrait;
use Yadahan\AuthenticationLog\AuthenticationLogable;

class Customer extends Authenticatable
{
    use AuthenticationLogable, HasRelationships, Notifiable, RevisionableTrait, SoftDeletes;

    protected $guarded = ['id'];

    protected $table = 'shop_customers';

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

    protected $casts = ['email_verified_at' => 'datetime'];

    public function delivery_addresses(): HasMany
    {
        return $this->addresses()->byDelivery();
    }

    public function invoice_addresses(): HasMany
    {
        return $this->addresses()->byInvoicing();
    }

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

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

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

    public function deliveries()
    {
        return $this->hasManyDeepFromRelations($this->sale_channels(), (new SaleChannel())->deliveries())
            ->whereNull('shop_customer_sale_channels.deleted_at');
    }

    public function sale_channels(): BelongsToMany
    {
        return $this->belongsToMany(SaleChannel::class, CustomerSaleChannel::class)->wherePivotNull('deleted_at');
    }

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

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

    public function scopeById($query, $id)
    {
        return $query->where($this->table.'.id', $id);
    }

    public function scopeBySaleChannel($query, $saleChannelId)
    {
        return $query->whereHas('sale_channels', function ($query) use ($saleChannelId) {
            return $query->byId($saleChannelId);
        });
    }

    public function sendEmailVerificationNotification()
    {
        if (config('boilerplate.auth.verify_email')) {
            $this->notify(new VerifyEmail());
        }
    }

    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPassword($token));
    }

    public function getNameAttribute()
    {
        return $this->getAttribute('first_name').' '.$this->getAttribute('last_name');
    }
}
