<?php namespace Tps\Birzha\Components;

use Cms\Classes\ComponentBase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use October\Rain\Support\Facades\Event;
use TPS\Birzha\Models\Payment;

class PaymentApi extends ComponentBase
{
    public $balance_message;
    public $orderStatusCode;

    public function componentDetails() {
        return [
            'name' => 'Payment API',
            'description' => 'Payment API'
        ];
    }

    public function defineProperties()
    {
        return [
            'payment_id' => [
                'title'       => 'Payment ID',
                'description' => 'Payment ID',
                'default'     => '{{ :payment_id }}',
                'type'        => 'string',
            ]
        ];
    }

    public function onRun() {
        $payment_id = $this->property('payment_id');
        $payment = Payment::find($payment_id);

        if(is_null($payment)) {
            return Redirect::to('/404');
        } elseif($payment->payment_type == 'bank') {
            return Redirect::to('/404');
        }

        $onlinePaymentClass = Config::get('bank.' . $payment->card_type . '.class');
        $onlinePayment = new $onlinePaymentClass;

        if($onlinePayment->checkReturnUrlParams(\Input::all(), $payment)) {

            // todo check order Status
            $responce = json_decode($onlinePayment->getStatus($payment->order_id), true);

            if($onlinePayment->checkOrderStatusResponseCodes($responce)) {

                // if page bank_result page is refreshed
                if($payment->status === 'approved') {
                    return Redirect::to('/');
                }

                $payment->status = 'approved';

                if($payment->save()){
                    Event::fire('tps.payment.received',[$payment]);
                    $this->balance_message = trans('validation.balance.fill_up_succes');                            
                }

            } else {

                $payment->status = 'failed';

                if($payment->save()) {
                    $this->balance_message = trans('validation.balance.fill_up_fail');
                }
            }

        } else {

            // if page bank_result page is refreshed
            if($payment->status === 'approved') {
                return Redirect::to('/');
            }
            
            $payment->status = 'failed';

            if($payment->save()) {
                $this->balance_message = trans('validation.balance.fill_up_fail');
            }
        }

    }
}
