<?php

/**
 * Class RefundItem
 *
 * @package Mtc\Plugins\Refunds\Classes
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
namespace Mtc\Plugins\Refunds\Classes;

use Illuminate\Database\Eloquent\Model;
use MTC\Shop\Order;
use Mtc\Shop\Order\Item as OrderItem;

/**
 * Class RefundItem
 *
 * Refund Item object model.
 * Represents item that is being refunded
 *
 * @package Mtc\Plugins\Refunds\Classes
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class RefundItem extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'order_refund_items';

    /**
     * Mass assignable attributes
     *
     * @var string[]
     */
    protected $fillable = [
        'refund_id',
        'order_id',
        'order_item_id',
        'item_id',
        'quantity',
        'amount_refunded',
        'created_at',
        'updated_at',
    ];

    /**
     * To which refund this item does belong
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function refund()
    {
        return $this->belongsTo(Refund::class, 'refund_id');
    }

    /**
     * Relationship to order from which the refund originated
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    /**
     * Relationship to order line item that is being refunded
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function orderItem()
    {
        return $this->belongsTo(OrderItem::class, 'order_item_id');
    }

    /**
     * Relationship to item that is refunded
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function item()
    {
        return $this->belongsTo(\Mtc\Shop\Item::class, 'item_id');
    }

    /**
     * Check the quantity already refunded for this line item
     *
     * @param int $order_item_id order item id that we are filtering
     * @return float amount that has been refunded
     */
    public static function getRefundedLineItemQty($order_item_id)
    {
        return self::where('order_item_id', $order_item_id)->sum('quantity');
    }

    /**
     * Check the amount already refunded for this line item
     *
     * @param int $order_item_id order item id that we are filtering
     * @return float amount that has been refunded
     */
    public static function getRefundedLineItemAmount($order_item_id)
    {
        return self::where('order_item_id', $order_item_id)->sum('amount_refunded');
    }
}
