<?php
namespace PortalPeople\paygate\models;

use Yii;
use backend\models\Cartsbe;

class Payment
{
    /**
     * Create a Computop Paygate checkout session and return a redirect URL.
     *
     * @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);
        $sessionData = Paygate::getPayload($cart);
        if (!$sessionData['success']) {
            Yii::error($sessionData['error'], 'paygate Payment Session Error');
            return ['type' => 'error', 'body' => $sessionData['error'], 'status' => 502];
        }
        return [
            'type' => 'redirect',
            'url' => $sessionData['paymentUrl'],
            'header' => 'Computop Paygate Payment',
            'status' => 200,
        ];
    }

    /**
     * Process Computop Paygate payment callback.
     * Handles both GET browser redirect and POST webhook notifications.
     *
     * @param array $params
     * @return array|string
     */
    public static function paygatepay(array $params)
    {
        $request = Yii::$app->request;

        if ($request->isPost) {
            // Server-to-server webhook POST
            $body = $request->getRawBody();
            $signature = $request->headers->get('X-Computop-Signature', '');
            $paygateData = Paygate::processResponse($body, $signature);
            $id = $paygateData['order']['orderId'] ?? '';
            $site = '/';
        } else {
            // Browser redirect GET
            $data = $request->get();
            $id = $data['id'] ?? '';
            $site = $data['site'] ?? '';
            // Validate redirect base URL against whitelist
            $allowedDomains = Yii::$app->params['paygate']['allowed_redirect_hosts'] ?? [];
            $parsed = parse_url($site);
            $host = $parsed['host'] ?? '';
            if (!$host || !in_array($host, $allowedDomains)) {
                $site = '/';
            }
            // Build body from GET params for processResponse
            $body = json_encode(array_intersect_key($data, array_flip(['payId', 'status', 'amount', 'currency', 'transactionId'])));
            $paygateData = Paygate::processResponse($body);
        }

        Yii::warning($paygateData, 'paygate Payment Response Data');

        $status = $paygateData['status'] ?? '';
        if ($status === 'CAPTURED' || $status === 'AUTHORIZED') {
            $payment = new \backend\models\Paymentresponsesbe();
            $payment->type = 'Payment';
            $payment->basketid = $id;
            $payment->currency = $paygateData['currency'] ?? (Yii::$app->params['paygate']['currency_iso'] ?? 'EUR');
            $payment->trxdate = date('Y-m-d H:i:s');
            $payment->camount = ($paygateData['amount'] ?? 0) / 100;
            $payment->amount = ($paygateData['amount'] ?? 0) / 100;
            $payment->paymentref = $paygateData['transactionId'] ?? ($paygateData['payId'] ?? '');
            $payment->status = 'Paid';
            $payment->paymentmethod = 'paygate';
            $payment->source = $site;
            $payment->comments = json_encode($paygateData);

            if ($request->isPost) {
                return $payment->save() ? ['status' => 'ok'] : ['status' => 'error'];
            }
            return $payment->save() ? $site . '/orderthanks/' . $id : $site . '/' . $id;
        }

        if ($request->isPost) {
            return ['status' => 'ok', 'message' => 'non-capture event acknowledged'];
        }
        return $site . $id . '?message=payment_failed';
    }
}