<?php

namespace App\Components;

use Carbon\Carbon;
use GuzzleHttp\Client;

class ZaloPayServices {
	public function createOrder( $params ) {
		$zaloPayEnv     = env( 'ZALOPAY_ENV', 'DEV' );
		$appId          = config( 'zalopay_services.' . $zaloPayEnv . '.APP_ID' );
		$createOrderUrl = config( 'zalopay_services.' . $zaloPayEnv . '.CREATE_ORDER_URL' );
		$appUser        = $params['app_user'];
		//$appUser = '123456';
		$amount         = $params['amount'];
		$order          = [
			"appid"      => $appId,
			"apptime"    => round(microtime(true) * 1000),
			"apptransid" => Carbon::now()->format( 'Ymd' ) . '_' . $appId . '_' . uniqid(),
			"appuser"    => $appUser,
			"bankcode"   => "zalopayapp",
			"amount"     => $amount,
			"embeddata"  => '',
			"item"       => ''
		];

		$order['mac'] = self::compute( self::createOrderMacData( $order ) );
		$client       = new Client();
		$res          = $client->request( 'POST', $createOrderUrl, [
			'headers'     => [
				'application/x-www-form-urlencoded'
			],
			'form_params' => $order
		] );
		$content      = $res->getBody()->getContents();

		return json_decode( $content, true );
	}


	static function compute( $params, $key = null ) {
		$zaloPayEnv = env( 'ZALOPAY_ENV', 'DEV' );
		if ( is_null( $key ) ) {
			$key = config( 'zalopay_services.' . $zaloPayEnv . '.KEY_1' );
		}

		return hash_hmac( "sha256", $params, $key );
	}

	private static function createOrderMacData( Array $order ) {
		return $order["appid"] . "|" . $order["apptransid"] . "|" . $order["appuser"] . "|" . $order["amount"]
		       . "|" . $order["apptime"] . "|" . $order["embeddata"] . "|" . $order["item"];
	}
}
