<?php

namespace App\Models\Shop;

use App\Traits\Model\HasComments;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Kirschbaum\PowerJoins\PowerJoins;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;

class Tariff extends Model
{
    use HasComments, HasRelationships, PowerJoins;

    protected $guarded = ['id'];

    protected $table = 'shop_tariffs';

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

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

    public function sale_channels(): HasManyThrough
    {
        return $this->HasManyThrough(SaleChannel::class, PriceList::class, 'id', 'id', 'id', 'sale_channel_id');
    }

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

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

    public function price_list_values(): HasManyThrough
    {
        return $this->hasManyThrough(PriceListValue::class, PriceList::class);
    }

    public function scopeByAutocomplete($query, $str)
    {
        return $query->where($this->table.'.name', 'LIKE', "%${str}%")
            ->orWhere($this->table.'.ref', 'LIKE', "${str}%")
            ->orWhere($this->table.'.code', 'LIKE', "${str}%");
    }

    public function scopeBySaleChannel($query, $id)
    {
        return $query->active()->whereHas('price_lists', function ($query) use ($id) {
            $query->bySaleChannel($id);
        });
    }

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

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

    public function scopeByOffer($query, $id)
    {
        return $query->whereHas('offers', function ($query) use ($id) {
            $query->byID($id);
        });
    }

    public function scopeActive($query)
    {
        return $query->byStatus(0)->hasPriceListsActive();
    }

    public function scopeHasPriceListsActive($query)
    {
        return $query->whereHas('price_lists', function ($query) {
            $query->active();
        });
    }
}
