<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use LaracraftTech\LaravelDateScopes\DateScopes;
use Venturecraft\Revisionable\RevisionableTrait;

class Order extends Model
{
    use DateScopes, RevisionableTrait, SoftDeletes;

    protected $guarded = ['id'];

    protected $table = 'shop_orders';

    protected $revisionCreationsEnabled = false;

    protected $keepRevisionOf = ['customer_address_id', 'delivery_id', 'payment_type', 'status'];

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

    public function delivery_address(): BelongsTo
    {
        return $this->belongsTo(CustomerAddress::class, 'delivery_address_id')->withTrashed();
    }

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

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

    public function invoice(): HasOne
    {
        return $this->hasOne(Invoice::class);
    }

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

    public function scopeByID($query, $id)
    {
        return $query->where('id', $id);
    }

    public function scopeByUUID($query, $uuid)
    {
        return $query->where('uuid', $uuid);
    }

    public function scopeByCustomer($query, $customerId)
    {
        return $query->where('customer_id', $customerId);
    }

    public function scopeByDelivery($query, $deliveryId)
    {
        return $query->where('delivery_id', $deliveryId);
    }

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

    public function scopePreparation($query)
    {
        return $query->byStatus(1);
    }

    public function scopeSended($query)
    {
        return $query->byStatus(2);
    }

    public function scopeReceived($query)
    {
        return $query->byStatus(3);
    }

    public function scopeNotCancelled($query)
    {
        return $query->where('status', '!=', 4);
    }

    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function scopeByPaymentType($query, $paymentType)
    {
        return $query->where('payment_type', $paymentType);
    }

    public function scopeByPeriod($query, $start, $end, $field = 'created_at')
    {
        return $query->whereBetween($field, [$start, $end]);
    }

    public function scopeByInvoice($query, $invoiceId)
    {
        return $query->whereHas('invoice', function ($query) use ($invoiceId) {
            $query->byId($invoiceId);
        });
    }
}
