<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\SoftDeletes;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
use Venturecraft\Revisionable\RevisionableTrait;
use Wildside\Userstamps\Userstamps;

class Delivery extends Model
{
    use HasRelationships, RevisionableTrait, SoftDeletes, Userstamps;

    protected $guarded = ['id'];

    protected $table = 'shop_deliveries';

    protected $revisionEnabled = true;

    protected $keepRevisionOf = [
        'sale_channel_id',
        'active',
        'is_public',
        'at_house',
        'name',
        'description',
        'address',
        'address2',
        'zipcode',
        'country',
        'event_date_begin',
        'event_date_end',
    ];

    public function customers(): HasManyThrough
    {
        return $this->hasManyThrough(Customer::class, CustomerSaleChannel::class);
    }

    public function sale_channel(): BelongsTo
    {
        return $this->belongsTo(SaleChannel::class);
    }

    public function scopeActive($query)
    {
        return $query->byActive(1);
    }

    public function scopeInactive($query)
    {
        return $query->byActive(0);
    }

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

    public function scopeByPublic($query, $isPublic)
    {
        return $query->where($this->table.'.is_public', $isPublic);
    }

    public function scopeAtHouse($query)
    {
        return $query->where($this->table.'.at_house', 1);
    }

    public function scopeBySaleChannels($query, $ids)
    {
        return $query->whereIn($this->table.'.sale_channel_id', $ids);
    }

    public function scopeBySaleChannel($query)
    {
        return $query->where($this->table.'.sale_channel_id', 1);
    }

    public function scopeManaged($query)
    {
        return $query->byPublic(0);
    }

    public function scopePublic($query)
    {
        return $query->byPublic(1);
    }

    public function scopeByCustomer($query, $customerId)
    {
        return $query->whereHas('customers', function ($query) use ($customerId) {
            return $query->byId($customerId);
        });
    }
}
