<?php

namespace App\Models;

use Illuminate\Support\Facades\Config;

class PaymentTransaction extends BaseModel
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'payment_transaction';
    protected $appends = ['paramsArray', 'extraParamsArray', 'responseArray', 'manuelPaymentLink'];

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $dateFormat = 'U';
    protected $guarded = [];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [];


    public function getParamsArrayAttribute()
    {
        if (!is_null($this->params)) {
            return json_decode($this->params, 1);
        } else {
            return null;
        }
    }

    public function getExtraParamsArrayAttribute()
    {
        if (!is_null($this->extra_params)) {
            return json_decode($this->extra_params, 1);
        } else {
            return null;
        }
    }

    public function getResponseArrayAttribute()
    {
        if (!is_null($this->response)) {
            return json_decode($this->response, 1);
        } else {
            return null;
        }
    }

    public function getManuelPaymentLinkAttribute()
    {
        if (!is_null($this->transaction_type == 'LNK')) {
            return Config::get('app.paymentFormLink') . $this['order_id'];
        } else {
            return null;
        }
    }

    public function paymentTypeMapping()
    {
        return $this->hasOne('App\Models\PropertyPaymentMapping', 'id', 'payment_type_mapping_id');
    }

    public function bookingDetail()
    {
        return $this->hasMany('App\Models\Booking', 'booking_code', 'order_id')
            ->select(['id', 'channel_id', 'booking_code', 'checkin_date', 'checkout_date', 'payment_type_code', 'total', 'currency_code', 'created_at', 'updated_at', 'status']);
    }

    public function relatedTransactions()
    {
        return $this->hasMany('App\Models\PaymentTransaction', 'order_id', 'order_id')->where('code', '<>', null)->orderByDesc('id');
    }

    public function paymentTransactionStatus()
    {
        return $this->hasOne('App\Models\PaymentTransactionStatus', 'id', 'status');
    }

    public function parentTransaction()
    {
        return $this->hasOne('App\Models\PaymentTransaction', 'order_id', 'order_id')->where('code', '=', null);
    }

    public function paymentUser()
    {
        return $this->hasOne('App\Models\User', 'id', 'created_by')->select(['id', 'name', 'surname', 'email', 'user_type', 'language', 'phone']);
    }

    public function property()
    {
        return $this->belongsTo("App\Models\Property", "property_id");
    }
}
