<?php

namespace App\Models\Shop;

use App\Repositories\Core\DateTime;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Venturecraft\Revisionable\RevisionableTrait;
use Wildside\Userstamps\Userstamps;
use Znck\Eloquent\Relations\BelongsToThrough;

class InvoicePayment extends Model
{
    use RevisionableTrait, Userstamps;

    protected $guarded = ['id'];

    protected $table = 'shop_invoice_payments';

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

    public function order(): BelongsToThrough
    {
        return $this->belongsToThrough(Order::class, Invoice::class);
    }

    public function scopeByInvoice($query, $invoiceId)
    {
        return $query->where('invoice_id', $invoiceId);
    }

    public function scopeValidated($query)
    {
        return $query->where('validated', 1);
    }

    public function scopeByOrder($query, $orderId)
    {
        return $query->whereHas('order', function ($query) use ($orderId) {
            return $query->byOrder($orderId);
        });
    }

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

    public function getDateAttribute($value)
    {
        return DateTime::dateToLocale($value);
    }

    public function setDateAttribute($value)
    {
        $this->attributes['date'] = DateTime::convert($value);
    }
}
