<?php

namespace App\Http\Controllers\Api;

use App\Http\logic\api\SafePayLogic;
use App\Http\logic\api\SafePayCashierLogic;
use App\Inter\PayMentInterFace;
use App\Notification\TelegramBot;
use App\Services\SafePay;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class SafePayController implements PayMentInterFace
{
    /**
     * 代收下单
     */
    public function pay_order(
        $userId,
        $payAmt,
        $userName,
        $userEmail,
        $userPhone,
        $GiftsID,
        $buyIP,
        $AdId,
        $eventType,
        $pay_method = ''
    ) {
        $logic = new SafePayLogic();
        try {
            $res = $logic->pay_order($userId, $payAmt, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method);
        } catch (\Exception $exception) {
            Redis::set("PayErro_SafePay", 1);
            Redis::expire("PayErro_SafePay", 600);
            Util::WriteLog('SafePay_error', $exception->getMessage() . json_encode($logic->result ?? []));
            TelegramBot::getDefault()->sendProgramNotify("SafePay Except ", $exception->getMessage(), $exception);
            return apiReturnFail($logic->getError());
        }

        if (!empty($res) && isset($res['code']) && $res['code'] == 200) {
            // SafePay 成功返回: data.order_data 是支付链接
            $data = [
                'content'  => $res['data']['order_data'] ?? '',
                'money'    => $payAmt,
                'prdOrdNo' => $res['data']['order_no'] ?? '',
            ];
            return apiReturnSuc($data);
        }

        if ($res == false) {
            return apiReturnFail($logic->getError() ?: 'Payment failed');
        }

        // 非200的响应，记录错误
        Redis::set("PayErro_SafePay", 1);
        Redis::expire("PayErro_SafePay", 600);
        $errMsg = $res['message'] ?? 'Unknown error';
        TelegramBot::getDefault()->sendProgramNotify("SafePay ReturnFail ", $errMsg . " | " . json_encode($res)."$userId");
        return apiReturnFail(['web.payment.paytype_error', $errMsg]);
    }

    /**
     * 代收异步回调通知
     * 
     * SafePay回调格式（POST JSON）:
     * {
     *   "mer_no": 600000,
     *   "order_no": "xxx",
     *   "order_amount": "1000.00",
     *   "order_reality_amount": "1000.00",
     *   "pay_type_code": 1301,
     *   "status": "success",
     *   "ref_no": "xxx",
     *   "sign": "xxx"
     * }
     */
    public function notify(Request $request)
    {
        $post = $request->all();
        $payload = json_encode($post);

        Util::WriteLog('SafePay', "SafePay回调订单\n" . $payload);

        $service = new SafePay();

        // 验签（平台公钥）
        try {
            $verify = $service->verifySign($post);
        } catch (\Exception $e) {
            Util::WriteLog('SafePay', '验签失败：' . $e->getMessage());
            return 'fail';
        }

        if (!$verify) {
            Util::WriteLog('SafePay', '签名错误');
            return 'fail';
        }

        $order_sn = $post['order_no'] ?? '';
        if (empty($order_sn)) {
            Util::WriteLog('SafePay', '缺少订单号');
            return 'fail';
        }

        // 代收回调加锁，防止并发重复处理
        $lockKey = 'pay_notify_SafePay_' . $order_sn;
        if (!SetNXLock::getExclusiveLock($lockKey, 60)) {
            Util::WriteLog('SafePay', '代收回调并发，订单已处理或处理中: ' . $order_sn);
            return 'ok';
        }

        $logic = new SafePayLogic();
        try {
            $ret = $logic->notify($post);
            return $ret;
        } catch (\Exception $exception) {
            Redis::set("PayErro_SafePay", 1);
            Redis::expire("PayErro_SafePay", 600);
            TelegramBot::getDefault()->sendProgramNotify("SafePay 订单回调执行异常 ", json_encode($post), $exception);
            Util::WriteLog("SafePay_error", $post);
            return 'fail';
        } finally {
            SetNXLock::release($lockKey);
        }
    }

    /**
     * 代付异步回调通知
     *
     * SafePay 代付回调格式（POST JSON）:
     * {
     *   "mer_no": 600000,
     *   "order_no": "xxx",
     *   "order_amount": "10.00",
     *   "order_reality_amount": "10.00",
     *   "currency": "USD",
     *   "result": "success",
     *   "sys_no": "212073",
     *   "sign": "xxx"
     * }
     */
    public function cash_notify(Request $request)
    {
        $post = $request->all();
        $payload = json_encode($post);

        Util::WriteLog('SafePay', "SafePay 提现回调\n" . $payload);

        $service = new SafePay();

        // 验签（平台公钥）
        try {
            $verify = $service->verifySign($post);
        } catch (\Exception $e) {
            Util::WriteLog('SafePay', '提现回调验签失败：' . $e->getMessage());
            return 'FAIL';
        }

        if (!$verify) {
            Util::WriteLog('SafePay', '提现回调签名错误');
            return 'FAIL';
        }

        $logic = new SafePayCashierLogic();
        try {
            return $logic->notify($post);
        } catch (\Exception $exception) {
            TelegramBot::getDefault()->sendProgramNotify(
                "SafePay 提现异步回调执行异常 ",
                json_encode($post),
                $exception
            );
            Util::WriteLog("SafePay_error", $post);
            return 'SUCCESS';
        }
    }
}
