<?php

namespace App\Http\logic\api;

use App\dao\Pay\AccountPayInfo;
use App\dao\Pay\PayController;
use App\Http\helper\CreateOrder;
use App\Http\helper\NumConfig;
use App\Jobs\Order as OrderJob;
use App\Notification\TelegramBot;
use App\Services\CoinPay;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Services\CreateLog;
use App\Util;
use Illuminate\Support\Facades\DB;

class CoinPayLogic extends BaseApiLogic
{
    public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
    {
        $dao = new AccountPayInfo();
        [$userPhone, $userName, $userEmail] = $dao->payInfo($userId);

        $PayVerify = new PayController();
        if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
            $this->error = $PayVerify->getError();
            return false;
        }
        if ($pay_amount < 0) {
            $this->error = 'Payment error_4';
            return false;
        }

        $service = new CoinPay();
        $config = $service->getConfig();

        $order_sn = CreateOrder::order_sn($userId);
        $orderLogic = new OrderLogic();
        $amountInt = (int) round($pay_amount * NumConfig::NUM_VALUE);
        $orderLogic->orderCreate($order_sn, $amountInt, 'CoinPay', $userId, $pay_method, $GiftsID, $AdId, $eventType);

        $language = strtoupper($config['language'] ?? 'en');
        $coin = strtoupper($config['coin'] ?? 'USDT');
        $protocol = strtoupper($config['protocol'] ?? 'TRC20');
        $rateType = (int)($config['rateType'] ?? 2);
        $currency = strtoupper($config['currency'] ?? 'USD');

        $coinbase = [
            64 => [
                'coin' => 'USDT',
                'protocol' => 'TRC20',
            ],
            128 =>[
                'coin' => 'USDT',
                'protocol' => 'ERC20',
            ],
            256 => [
                'coin' => 'USDC',
                'protocol' => 'TRC20',
            ],
            512 =>[
                'coin' => 'USDC',
                'protocol' => 'ERC20',
            ]
        ];

        $select = $coinbase[$pay_method] ?? $coinbase[64];

        $params = [
            'merchantMemberNo' => (string)$userId,
            'merchantOrderNo' => $order_sn,
//            'amount' => $pay_amount,
            'language' => $language,
            'coin' => $select['coin'],
            'rateType' => $rateType,
            'protocol' => $select['protocol'],
            'notifyUrl' => $config['notify'] ?? '',
            'timestamp' => time(),
        ];

        if ($rateType === 1) {
            $params['amount'] = number_format($pay_amount, 8, '.', '');
            $params['rate'] = $config['rate'] ?? '1';
        } else {
            $params['currencyAmount'] = number_format($pay_amount, 2, '.', '');
            $params['currency'] = $currency;
        }

        if (!empty($config['extra'])) {
            $params = array_merge($params, $config['extra']);
        }

        $signedParams = $service->sign($params);
        CreateLog::pay_request($userPhone, json_encode($signedParams), $order_sn, $userEmail, $userId, $userName);

        $response = $service->post('/order/depositOrderCoinCreate', $signedParams);
        Util::WriteLog('CoinPay', 'pay request => ' . json_encode($signedParams, JSON_UNESCAPED_UNICODE));
        Util::WriteLog('CoinPay', 'pay response => ' . $response);

        try {
            $data = \GuzzleHttp\json_decode($response, true);
        } catch (\Throwable $e) {
            Util::WriteLog('CoinPay_error', $e->getMessage());
            $this->error = 'Payment processing error';
            return false;
        }

        if (!isset($data['code']) || (int)$data['code'] !== 0) {
            $this->error = $data['msg'] ?? 'Payment request failed';
        }

        return $data;
    }

    public function notify(array $post)
    {
        $order_sn = $post['merchantOrderNo'] ?? '';
        if (!$order_sn) {
            return '{"success":false,"message":"missing order"}';
        }

        $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();
        if (!$order) {
            Util::WriteLog('CoinPay', 'order not found: ' . $order_sn);
            return '{"success":false,"message":"order not found"}';
        }

        if (!empty($order->pay_at) && !empty($order->finished_at)) {
            return 'SUCCESS';
        }

        $status = (int)($post['state'] ?? 0);
        $payAmt = (float)($post['currencyAmount'] ?? $post['amount'] ?? 0);

        $body = [
            'payment_sn' => $post['orderNo'] ?? '',
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $GiftsID = $order->GiftsID ?: '';
        $userID = $order->user_id ?: '';
        $AdId = $order->AdId ?: '';
        $eventType = $order->eventType ?: '';

        switch ($status) {
            case 3:
                $body['pay_status'] = 1;
                $body['pay_at'] = date('Y-m-d H:i:s');
                $body['finished_at'] = date('Y-m-d H:i:s');
                $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);

                $config = (new PayConfig())->getConfig('CoinPay');
                if (!empty($config['payin_fee'])) {
                    $body['payment_fee'] = $body['amount'] * (float)$config['payin_fee'];
                }

                try {
                    $service = new OrderServices();
                    if ((int)$order->amount !== $body['amount']) {
                        $body['GiftsID'] = 0;
                        $Recharge = $payAmt;
                        $give = 0;
                        $favorable_price = $Recharge;
                        $czReason = 1;
                        $cjReason = 45;
                    } else {
                        [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmt);
                    }

                    [$Score] = $service->addRecord($userID, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType, $body['payment_fee'] ?? 0);
                    OrderJob::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_sn]);
                } catch (\Throwable $exception) {
                    Util::WriteLog('CoinPay_error', $exception->getMessage());
                    TelegramBot::getDefault()->sendProgramNotify('CoinPay notify error', $exception->getMessage(), $exception);
                }
                break;

            case 4:
            case 5:
                $body['pay_status'] = 2;
                break;

            default:
                return 'fail';
        }

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

        return 'SUCCESS';
    }
}

