<?php

namespace App\Http\Controllers\Gateway;

use App\Models\Payment;
use Auth;


use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;


class Zypay extends AbstractPayment
{

    public function purchase(Request $request): JsonResponse
    {
        $payment = $this->creatNewPayment(Auth::id(), $request->input('id'), $request->input('amount'));

//        switch ($request->input('type')) {
//            case 2:
//                $type = 'qqpay';
//                break;
//            case 3:
//                $type = 'wxpay';
//                break;
//            case 1:
//            default:
//                $type = 'alipay';
//                break;
//        }
        $key = "6f13dd44826918a5fc7ab6baa255d99c51b505b3";
        $data = [
            'app_id' => "WTQwSt5Dytzs",
            'out_trade_no' => $payment->trade_no,
            'total_amount' => $payment->amount * 100,
            'notify_url' => route('payment.notify', ['method' => 'zpay']),
            'return_url' => route('invoice'),
        ];
        ksort($data);
        $str = http_build_query($data);
        $data['sign'] = strtolower(md5($str .  $key));

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://api.hmcheckout.com" . '/api/v1/tron');
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['User-Agent: Alpha']);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res, true);
        if (!$result) {
            return Response::json(['status' => 'success', 'url' => "", 'message' => '网络异常!']);
        }

        Log::info("[河马支付]请求支付接口". var_export($result, true));
        if ($result["code"] === 0 ){
            return Response::json(['status' => 'fail', 'message' => '创建订单失败!'.$result['error']]);
        }
        return Response::json(['status' => 'success', 'url' => $result['url'], 'message' => '创建订单成功!']);


    }

    public function notify(Request $request): void
    {
        if ($this->verifySign($request->post())){
            exit('SIGN FAIL');
        }
        if ($request->has(['out_trade_no']) && $this->paymentReceived($request->input(['out_trade_no']))  ) {
            $this->addPamentCallback($request->input('out_trade_no'),$request->input('trade_no'),"");
            Log::info('【河马支付】paymentReceived:'.var_export($request->all(), true));
            exit(json_encode(['status' => 200]));
        }
    }

    function verifySign($params)
    {
        $key = "6e13274fe90055e38f0751c3e242af1882abc849";
        $sign = $params['sign'];
        unset($params['sign']);
        ksort($params);
        $str = strtolower(http_build_query($params) . $key);
        if ($sign !== md5($str)) {
            return false;
        }
        return $str;

        // 剃离sign,sign_type,空值
//        unset($data['sign'], $data['sign_type'] , $data["method"]);


//    if ($filter) {
//        $data = array_filter($data);
//    }

        // 排序
//        ksort($data, SORT_STRING);
//        reset($data);
//
//
//        $data["key"] = $key;
//        return strtoupper(md5(urldecode(http_build_query($data))));
    }
}