<?php


namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;

use App\Services\PaymentOrderService;
use App\Services\Payment\NoPayService;
use App\Services\Payment\ZimuPayService;

class Pay extends Controller
{
    // 同步通知
    public function returnHandle(Request $request)
    {

    }

    // 异步通知
    public function notifyHandle(Request $request)
    {
        $data = $request->all();
        $context = $this->callbackContext($request, $data);
        Log::error('支付提现回调收到', $context);

        try {
            $res = PaymentOrderService::receiveOrder($data);
            Log::error('支付提现回调处理结果', $context + ['success' => (bool)$res]);
            if (NoPayService::getWithdrawMerchantId() !== '' && ($data['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
                return response($res ? 'SUCCESS' : 'fail');
            }
            if (ZimuPayService::getAppId() !== '' && ($data['appId'] ?? '') === ZimuPayService::getAppId()) {
                return response($res ? 'success' : 'fail');
            }
            return response('success');
        } catch (\Throwable $e) {
            Log::error('支付提现回调处理异常', $context + [
                'error' => $e->getMessage(),
                'exception' => get_class($e),
            ]);
            return response('fail', 500);
        }
    }

    // 用户支付异步通知
    public function harvestHandle(Request $request)
    {
        $data = $request->all();
        $context = $this->callbackContext($request, $data);
        Log::error('支付充值回调收到', $context);

        try {
            $res = PaymentOrderService::receivePay($data);
            Log::error('支付充值回调处理结果', $context + ['success' => (bool)$res]);
            if (NoPayService::getDepositMerchantId() !== '' && ($data['appId'] ?? '') === NoPayService::getDepositMerchantId()) {
                return response($res ? 'SUCCESS' : 'fail');
            }
            if (ZimuPayService::getAppId() !== '' && ($data['appId'] ?? '') === ZimuPayService::getAppId()) {
                return response($res ? 'success' : 'fail');
            }
            return response('success');
        } catch (\Throwable $e) {
            Log::error('支付充值回调处理异常', $context + [
                'error' => $e->getMessage(),
                'exception' => get_class($e),
            ]);
            return response('fail', 500);
        }
    }

    private function callbackContext(Request $request, array $data): array
    {
        if (isset($data['sign'])) {
            $data['sign'] = substr((string)$data['sign'], 0, 8) . '***';
        }

        return [
            'ip' => $request->ip(),
            'url' => $request->fullUrl(),
            'content_type' => $request->header('Content-Type'),
            'user_agent' => $request->userAgent(),
            'data' => $data,
            'raw_body' => $request->getContent(),
        ];
    }
}
