<?php
namespace Mtc\Plugins\RyftPay\Classes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\Modules\Members\Models\Member;
use Mtc\Shop\Order;

/**
 * Accessors
 *
 * @property int $id
 * @property int $order_id
 * @property int $member_id
 * @property string $remote_id
 * @property string $transaction_id
 * @property float $amount
 * @property string $currency
 * @property string $status
 * @property string $method
 *
 * @property Order $order
 * @property Member $member
 */
class RyftPayment extends Model
{
    protected $table = 'ryft_payments';

    protected $fillable = [
        'order_id',
        'member_id',
        'remote_id',
        'transaction_id',
        'amount',
        'currency',
        'status',
        'method',
    ];

    const STATUS_PENDING = 'pending';
    const STATUS_RESERVED = 'reserved';
    const STATUS_PAID = 'paid';
    const STATUS_FAILED = 'failed';
    const STATUS_CANCELLED = 'cancelled';
    const STATUS_REFUNDED = 'refunded';

    const METHOD_CARD = 'card';
    const METHOD_APAY = 'apay';
    const METHOD_GPAY = 'gpay';

    public static array $paymentMethods = [
        self::METHOD_CARD => [
            'name' => 'Ryft Pay',
            'icon' => '/plugins/RyftPay/images/payment/ryft.png',
        ],
        self::METHOD_APAY => [
            'name' => 'Apple Pay',
            'icon' => '/plugins/RyftPay/images/payment/apay.png',
        ],
        self::METHOD_GPAY => [
            'name' => 'Google Pay',
            'icon' => '/plugins/RyftPay/images/payment/gpay.png',
        ],
    ];

    const EVENT_CAPTURED = 'PaymentSession.captured';
    const EVENT_APPROVED = 'PaymentSession.approved';
    const EVENT_REFUNDED = 'PaymentSession.refunded';
    const EVENT_REFUND_FAILED = 'PaymentSession.refund_failed';
    const EVENT_CAPTURE_FAILED = 'PaymentSession.capture_failed';
    const EVENT_DECLINED = 'PaymentSession.declined';

    public static array $successEvents = [
        self::EVENT_CAPTURED,
        self::EVENT_APPROVED,
    ];

    public static array $failEvents = [
        self::EVENT_CAPTURE_FAILED,
        self::EVENT_DECLINED,
    ];

    public function getRefAttribute()
    {
        return config('site.tnx_prefix') . $this->order_id;
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function member(): BelongsTo
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    /**
     * Captures authorised payment
     *
     * @return bool
     */
    public function capturePayment(): bool
    {
        if ($this->status !== self::STATUS_RESERVED) {
            return false;
        }
        return true;
    }
}
