<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PaymentController extends Controller
{
    private $key = 'Train37There28Metal';
    private $url = 'https://gateway.universaltp.com/paymentform/';

    public function paymentTest(Request $request)
    {
        
        if (!$request->has('responseCode')) {
            // Prepare the request data
            $req = [
                'merchantID' => '101073',
                'action' => 'SALE',
                'type' => 1,
                'countryCode' => 826,
                'currencyCode' => 826,
                'amount' => 1001,
                'orderRef' => 'Test purchase',
                'transactionUnique' => uniqid(),
                'redirectURL' => $request->secure() ? 'https://' : 'http://' . $request->getHost() . $request->getRequestUri(),
            ];

            // Create the signature
            $req['signature'] = $this->createSignature($req, $this->key);

            return view('payment', ['req' => $req, 'url' => $this->url]);
        } else {
            // Handle the response posted back
            return $this->handleResponse($request);
        }
    }

    private function createSignature(array $data, $key)
    {
        // Sort by field name
        ksort($data);
        // Create the URL encoded signature string
        $ret = http_build_query($data, '', '&');
        // Normalize line endings
        $ret = str_replace(["%0D%0A", "%0A%0D", "%0D"], '%0A', $ret);
        // Hash the signature string and the key
        return hash('SHA512', $ret . $key);
    }

    private function handleResponse(Request $request)
    {
        $res = $request->all();
        $signature = $res['signature'] ?? null;

        if ($signature) {
            unset($res['signature']);
        }

        // Check the return signature
        if (!$signature || $signature !== $this->createSignature($res, $this->key)) {
            return response()->json(['error' => 'Sorry, the signature check failed'], 400);
        }

        // Check the response code
        if ($res['responseCode'] === "0") {
            return response()->json(['message' => 'Thank you for your payment.']);
        } else {
            return response()->json(['error' => 'Failed to take payment: ' . htmlentities($res['responseMessage'])], 400);
        }
    }
}
