<?php

namespace Yajny\Member\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Yajny\Member\Traits\MemberScopes;
use Yajny\Traits\HasCurrency;

class UserClaim extends Model
{
    use MemberScopes, HasCurrency;

    protected $table = 'user_claims';
    protected $primaryKey = 'id';
    protected $fillable = ['user_id', 'click_id', 'click_time', 'network_id', 'store_id', 'order_id', 'currency_iso', 'order_amount', 'transaction_date', 'platform', 'message'];

    public $dateColumn = 'created_at';
    public $directTable = 'user_claims';
    public $copyClickInfo = ['click_time', 'network_id', 'store_id'];

    private $currencyFieldName = 'currency_iso';
    private $currencyFormatFields = [
        'order_amount'
    ];

    public function user()
    {
        return $this->belongsTo('Yajny\Member\Models\Member', 'user_id', 'user_id');
    }

    public function click()
    {
        return $this->belongsTo('Yajny\Member\Models\Click', 'click_id', 'id');
    }

    public function store()
    {
        return $this->belongsTo('Yajny\Models\Store', 'store_id', 'id')->withoutGlobalScopes();
    }

    public function comments()
    {
        return $this->hasMany('Yajny\Member\Models\UserClaimComment', 'claim_id', 'id');
    }

    public function updateClickInfo()
    {
        $click_info = $this->click()->first();
        foreach ($this->copyClickInfo as $cpCol)
            $this->{$cpCol} = $click_info->{$cpCol};
    }

    public function getAttachmentsAttribute($value)
    {
        if ($value) {
            $attachmentsURLs = [];
            foreach (json_decode($value) as $attachment)
                $attachmentsURLs[] = Storage::disk('do-spaces')->temporaryUrl($attachment, now()->addHour());

            return $attachmentsURLs;
        } else
            return [];
    }
}
