<?php 
namespace PortalPeople\paygate\models;

use Yii;
use backend\models\Cartsbe;
class Payment 
{
    /**
     * Create paygate Payment Request
     *
     * @param array $params
     * @return array
     */
    public static function paygatecreate(array $params){
        yii::Warning($params, 'paygate Payment Request Params');
        $id = $params['id'] ?? null;
        $cart = Cartsbe::findOne($id);
        $response = [
				'type'=> 'form', 
				'body' => Yii::$app->view->render('/payments/paygate', ['data' => Paygate::getPayload($cart)]),
				'header' => 'Paygate Payment',
				'status' => 200,
			];
        return $response;
    }

    /**
     * Process Paygate Payment Response
     *
     * @param array $params
     * @return array
     */
    public static function paygatepay(array $params){
        $data = Yii::$app->request->get();
        $paygateData = Paygate::processResponse($data['data']);
        Yii::warning($paygateData, 'paygate Payment Response Data');
        if($paygateData['Ds_Response'] < 100){
            // Decode URL-encoded date and hour
            $dsDate = urldecode($paygateData['Ds_Date']);
            $dsHour = urldecode($paygateData['Ds_Hour']);
            $date = \DateTime::createFromFormat('d/m/Y H:i', $dsDate . ' ' . $dsHour);
            $payment = new \backend\models\Paymentresponsesbe();
            $payment->type = 'Payment';
            $payment->basketid = $data['id'];
            $payment->currency = 'EUR';
            $payment->trxdate = $date->format('Y-m-d H:i:s');
            $payment->camount = $paygateData['Ds_Amount']/100;
            $payment->amount = $paygateData['Ds_Amount']/100;
            $payment->paymentref = $paygateData['Ds_AuthorisationCode'];
            $payment->status = 'Paid';
            $payment->paymentmethod = 'paygate';
            $payment->source = $data['site'];
            $payment->comments = json_encode($paygateData);
            return $payment->save() ? $data['site'] . '/orderthanks/' . $data['id'] : $data['site'] . '/' . $data['id'];
        } else {
            return $data['site'] . $data['id'].'?message=payment_failed';
        }
    }
}