<?php

namespace Kylin\Payment\Gateways;

/**
 * PayPal支付网关
 */
class PaypalGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建支付参数
        $payParams = [
            'intent' => 'CAPTURE',
            'purchase_units' => [
                [
                    'reference_id' => $params['out_trade_no'],
                    'amount' => [
                        'currency_code' => $params['currency'] ?? 'USD',
                        'value' => $params['total_amount']
                    ],
                    'description' => $params['description'] ?? ''
                ]
            ],
            'application_context' => [
                'return_url' => $this->getConfig('return_url'),
                'cancel_url' => $this->getConfig('cancel_url'),
                'brand_name' => $params['brand_name'] ?? '',
                'user_action' => $params['user_action'] ?? 'PAY_NOW'
            ]
        ];

        // 获取访问令牌
        $accessToken = $this->getAccessToken();

        // 构建请求URL
        $url = $this->getApiUrl() . '/v2/checkout/orders';

        // 发起请求
        $result = $this->request($url, $payParams, 'POST', [
            'Authorization' => 'Bearer ' . $accessToken,
            'Content-Type' => 'application/json'
        ]);

        return $result;
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // 获取访问令牌
        $accessToken = $this->getAccessToken();

        // 构建请求URL
        $url = $this->getApiUrl() . '/v2/checkout/orders/' . $orderNo;

        // 发起请求
        $result = $this->request($url, [], 'GET', [
            'Authorization' => 'Bearer ' . $accessToken
        ]);

        return $result;
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // 构建退款参数
        $refundParams = [
            'amount' => [
                'currency_code' => $params['currency'] ?? 'USD',
                'value' => $params['refund_amount']
            ],
            'invoice_id' => $params['invoice_id'] ?? ''
        ];

        // 获取访问令牌
        $accessToken = $this->getAccessToken();

        // 构建请求URL
        $url = $this->getApiUrl() . '/v2/payments/captures/' . $params['capture_id'] . '/refunds';

        // 发起请求
        $result = $this->request($url, $refundParams, 'POST', [
            'Authorization' => 'Bearer ' . $accessToken,
            'Content-Type' => 'application/json'
        ]);

        return $result;
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // 获取访问令牌
        $accessToken = $this->getAccessToken();

        // 构建请求URL
        $url = $this->getApiUrl() . '/v2/checkout/orders/' . $orderNo . '/cancel';

        // 发起请求
        $result = $this->request($url, [], 'POST', [
            'Authorization' => 'Bearer ' . $accessToken
        ]);

        return $result;
    }

    /**
     * 回调处理
     */
    public function callback(array $data): mixed
    {
        // 验证签名（实际项目中需要根据PayPal webhook验证规则验证）
        // $signature = $data['auth_algo'];
        // $certUrl = $data['cert_url'];
        // $transmissionId = $data['transmission_id'];
        // $transmissionTime = $data['transmission_time'];
        // $webhookId = $this->getConfig('webhook_id');
        // $webhookEvent = $data['webhook_event'];
        // $generatedSignature = $this->generateSignature($data, $this->getConfig('client_secret'));
        // if (!$this->verifyWebhookSignature($data)) {
        //     return ['code' => 'FAIL', 'message' => '签名验证失败'];
        // }

        // 处理支付结果
        $eventType = $data['event_type'] ?? '';
        if (in_array($eventType, ['CHECKOUT.ORDER.APPROVED', 'PAYMENT.CAPTURE.COMPLETED'])) {
            // 支付成功，处理订单
            return [
                'code' => 'SUCCESS',
                'message' => '回调处理成功',
                'data' => [
                    'order_id' => $data['resource']['id'] ?? '',
                    'status' => $data['resource']['status'] ?? '',
                    'event_type' => $eventType
                ]
            ];
        } else {
            // 支付失败
            return [
                'code' => 'FAIL',
                'message' => '支付失败',
                'data' => [
                    'event_type' => $eventType
                ]
            ];
        }
    }

    /**
     * 获取访问令牌
     */
    protected function getAccessToken(): string
    {
        // 构建请求参数
        $params = [
            'grant_type' => 'client_credentials'
        ];

        // 构建请求URL
        $url = $this->getApiUrl() . '/v1/oauth2/token';

        // 发起请求
        $result = $this->request($url, $params, 'POST', [
            'Authorization' => 'Basic ' . base64_encode($this->getConfig('client_id') . ':' . $this->getConfig('client_secret')),
            'Content-Type' => 'application/x-www-form-urlencoded'
        ]);

        return $result['access_token'] ?? '';
    }

    /**
     * 获取API URL
     */
    protected function getApiUrl(): string
    {
        return $this->getConfig('mode') === 'sandbox' ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
    }
}
