<?php

namespace Mtc\Plugins\Realex\Classes;

use Illuminate\Database\Eloquent\Model;


class OrderRealex extends Model
{

    protected $table = 'order_realex';

    protected $fillable = [
        'order_id',
        'amount_paid',
        'tnx_id',
        'paid_time',
    ];

    const REALEX_ORDER_PREFIX = 'VYNE_PAYMENT_';


    public static function getPrefixedOrderRef($order_id, $token = null)
    {
        $reference = self::REALEX_ORDER_PREFIX . $order_id;
        if ($token !== null) {
            $reference .= '-' . $token;
        }

        return $reference;
    }


    public static function getStrippedOrderRef($prefixed_order_ref)
    {
        $withoutPrefix = str_replace(self::REALEX_ORDER_PREFIX, '', $prefixed_order_ref);
        if (strpos($withoutPrefix, '-') !== false) {
            $withoutPrefix = strstr($withoutPrefix, '-', true);
        }

        return $withoutPrefix;
    }


    public function capture()
    {
        $output = [
            'success' => false,
        ];

        $realex = new Realex();
        $output = $realex->settleDelayedCaptureTransaction($this);
        if ($output['success']) {
            $this->paid_time = date('Y-m-d H:i');
            $this->save();
        }

        return $output;
    }

}
