<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\logic\api\AppleStorePayLogic;
use App\Jobs\Order;
use App\Models\Treasure\GameScoreInfo;
use App\Services\OrderServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class AppleStorePayController extends Controller
{
    public $config = [
        'ouro777.490' => 500,
        'ouro777.990' => 1000,
        'ouro777.1990' => 2000,
        'vencedor.490' => 500,
        'vencedor.990' => 1000,
        'vencedor.1990' => 2000,
    ];
    public function pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIp, $AdId, $eventType)
    {
        $logic = new AppleStorePayLogic();
        $name = \Illuminate\Support\Facades\Request::input('productID');

        if (!isset($this->config[$name])) {
            return apiReturnFail(__('messages.api.payment.unknown_product'));
        }
        $payAmt = $this->config[$name];
        $res = $logic->pay_order($userId, $payAmt,$name, $userPhone, $userEmail, $userName, $GiftsID, $buyIp, $AdId, $eventType);
        if ($res === false) {
            return apiReturnFail($logic->getError());
        }

        return apiReturnSuc($res);
    }

    public function confirm(Request $request)
    {
        Log::channel('appleStorePay')->info('app store pay validate request', [
            'request' => $request->all(),
        ]);
        $validator =  Validator::make($request->all(), [
            'is_sandbox' => 'required|in:0,1',
            'receipt' => 'required',
            'order_sn' => 'required'
        ]);
        if ($validator->fails()) {
            return apiReturnFail($validator->errors()->first());
        }
        $isSandbox = $request->input('is_sandbox');
        $receipt = $request->input('receipt');
        $orderSN = $request->input('order_sn');
        $result = $this->verifyReceipt($receipt, 1);
        if ($result === false) {
            $result = $this->verifyReceipt($receipt, 0);
            if ($result === false) {
                return apiReturnFail(['web.payment.valid_failed',__('messages.api.payment.valid_failed')]);
            }
        }
        // 验证成功了
        // 查询订单信息
        $order = DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $orderSN)->first();
        if (!$order) {
            Log::channel('appleStorePay')->info('订单不存在');
            return apiReturnSuc();
        }

        if (!empty($order->pay_at) || !empty($order->finished_at)) {
            Log::channel('appleStorePay')->info('订单已支付');
            return apiReturnSuc();
        }
        $GiftsID = $order->GiftsID ?: '';
        $userID = $order->user_id ?: '';
        $AdId = $order->AdId ?: '';
        $eventType = $order->eventType ?: '';
        $payAmt = (int)($order->amount/100);
        $body = [
            'payment_sn' => $result['receipt']['in_app'][0]['transaction_id'],
            'updated_at' => date('Y-m-d H:i:s'),
            'pay_status' => 1,
            'pay_at' => date('Y-m-d H:i:s'),
            'finished_at' => date('Y-m-d H:i:s'),
        ];
        $apply_data = [
            'order_id' => $order->id,
            'payment_sn' => $body['payment_sn'],
            'payment_code' => 'AppleStore',
            'return' => \GuzzleHttp\json_encode($result),
            'is_error' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        // 获取金额
        $service = new OrderServices();
        [$give, $favorable_price, $Recharge, $czReason, $cjReason] = [0,$payAmt,$payAmt,1,45];

        // 增加充值记录
        [$Score] = $service->addRecord(
            $userID,
            $payAmt,
            $favorable_price,
            $orderSN,
            $GiftsID,
            $Recharge,
            $czReason,
            $give,
            $cjReason,
            $AdId,
            $eventType
        );

        // 成功处理回调
        Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $orderSN]);

        $order_up = DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $orderSN)
            ->update($body);

        $apply = DB::connection('write')->table('agent.dbo.payment_apply')
            ->insert($apply_data);

        if (($order_up && $apply) != true) {
            Log::channel('appleStorePay')->info('订单更新失败');
            return apiReturnFail(['web.payment.valid_failed',__('messages.api.payment.valid_failed')]);
        }

        Log::channel('appleStorePay')->info('success', [
            'order_sn' => $orderSN
        ]);
        $gameScoreInfo = GameScoreInfo::query()->where('UserID', $userID)->first();
        return apiReturnSuc([
            'give' => $give,
            'total' => $gameScoreInfo->Score ?? $give
        ]);
    }

    /**
     * 验证苹果收据
     * @param $receipt
     * @param $isSandbox
     * @return \Illuminate\Http\JsonResponse
     */
    private function verifyReceipt($receipt, $isSandbox)
    {
        $endpoint = $isSandbox ? 'https://sandbox.itunes.apple.com/verifyReceipt'
            : 'https://buy.itunes.apple.com/verifyReceipt';
        $postData = json_encode(array('receipt-data' => str_replace(' ', '+', $receipt)));

        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        $errmsg = curl_error($ch);
        curl_close($ch);
        Log::channel('appleStorePay')->info('curl app server result', [
            'endpoint' => $endpoint,
            'data' => $postData,
            'response' => $response,
            'errmsg' => $errmsg,
        ]);

        if ($errno != 0) {
            Log::channel('appleStorePay')->error('curl app server error', [
                'endpoint' => $endpoint,
                'data' => $postData,
                'response' => $response,
                'errmsg' => $errmsg,
            ]);
            return false;
        }

        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::channel('appleStorePay')->error('curl app server error', [
                'endpoint' => $endpoint,
                'data' => $postData,
                'response' => $response,
            ]);
            return false;
        }
        if (($data['status'] ?? null) !== 0) {
            Log::channel('appleStorePay')->error('app server validated failed', [
                'endpoint' => $endpoint,
                'data' => $postData,
                'response' => $response,
            ]);
            return false;
        }

        return $data;
    }
}
