<?php

namespace Modules\Refund\Models;

use App\Services\Upload\FileService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Order\Models\Order;
use Modules\Order\Models\OrderProduct;
use Modules\Reason\Models\Reason;
use Modules\Refund\Enums\RefundStatusEnum;
use Modules\User\Models\Address;
use Modules\User\Models\UserCard;

class Refund extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable =
    [
        'status','image','order_product_id','order_id','user_card_id','address_id','note','uuid','reason_id'
    ];

    public function getDateAttribute()
    {
        $date = date('d',strtotime($this->created_at));
        $date .= ' '.__('web.monthes.'.date('m',strtotime($this->created_at)));
        $date .= ' '.date('Y',strtotime($this->created_at));
        return $date;
    }
    public function setImageAttribute($value)
    {
        if($value)
        {
            if(is_string($value))
            {
                $this->attributes['image'] = $value;
            }
            else
            {
                $photo = FileService::uploadImage($value);
                $this->attributes['image'] = $photo;
            }
        }
        else
        {
            $this->attributes['image'] = request()->method() == 'post'  ? 'logo.png' : $this->photo;
        }
        return $this->belongsTo(UserCard::class,'user_card_id')->withTrashed();
    }
    public function order()
    {
        return $this->belongsTo(Order::class)->withTrashed();
    }
    public function address()
    {
        return $this->belongsTo(Address::class)->withTrashed();
    }
    public function card()
    {
        return $this->belongsTo(UserCard::class,'user_card_id')->withTrashed();
    }
    public function reason()
    {
        return $this->belongsTo(Reason::class,'reason_id')->withTrashed();
    }
    public function statuses()
    {
        return $this->hasMany(RefundStatus::class);
    }

    public function orderProduct()
    {
        return $this->belongsTo(OrderProduct::class)->with(['product','option']);
    }
    public function statusFetch($status)
    {
        if($status == -1)
        {
            $refund = RefundStatus::where('status',RefundStatusEnum::ACCEPT->value)->where('refund_id',$this->id)->first();
            if (!$refund)
            {
                $refund = RefundStatus::where('status',RefundStatusEnum::REFUSE->value)->where('refund_id',$this->id)->first();
            }
        }
        else
        {
            $refund = RefundStatus::where('status',$status)->where('refund_id',$this->id)->first();
        }
        return  [
            'status'=>$refund ? $refund->status : $status,
            'item'=>$refund
        ];
    }
}
