<?php

namespace App\Services\Apcopay;

use Illuminate\Support\Facades\Log;

class ApcopayPaymentService extends ApcopayClient
{
    /**
     * 创建托管支付页面token
     */
    public function createHostedPaymentPageToken(array $params): array
    {
        // 记录详细的请求参数
        Log::info('Apcopay createHostedPaymentPageToken request', [
            'params' => $params
        ]);
        
        // 确保必要的参数存在
        if (!isset($params['BrandId'])) {
            $params['BrandId'] = $this->config['brand_code'];
        }
        
        // 确保金额是字符串类型
        if (isset($params['Amount']) && !is_string($params['Amount'])) {
            $params['Amount'] = (string)$params['Amount'];
        }
        
        // 发送请求并获取响应
        $response = $this->post('/merchanttools/api/hpptoken/create', $params);
        
        // 记录详细的响应
        Log::info('Apcopay createHostedPaymentPageToken response', [
            'response' => $response
        ]);
        
        return $response;
    }

    /**
     * 生成支付URL
     */
    public function getPaymentPageUrl(string $token): string
    {
        // 检查token是否已经是完整的URL
        if (strpos($token, 'http') === 0) {
            return $token;
        }
        
        $baseUrl = rtrim($this->config['api_url'], '/');
        return $baseUrl . '/merchanttools/hpp/' . $token;
    }

    /**
     * 查询交易
     */
    public function queryTransaction(array $params): array
    {
        // 记录查询参数
        Log::info('Apcopay queryTransaction request', [
            'params' => $params
        ]);
        
        $response = $this->get('/merchanttools/api/transactions/retrieve', $params);
        
        // 记录响应
        Log::info('Apcopay queryTransaction response', [
            'response' => $response
        ]);
        
        return $response;
    }

    /**
     * 执行直接支付（提现）
     * 
     * @param array $params 支付参数
     * @return array 响应结果
     */
    public function executeDirectPayment(array $params): array
    {
        // 记录详细的请求参数
        Log::info('Apcopay executeDirectPayment request', [
            'params' => $params
        ]);
        
        // 确保必要的参数存在
        if (!isset($params['BrandId'])) {
            $params['BrandId'] = $this->config['brand_code'];
        }
        
        // 确保金额是字符串类型
        if (isset($params['Amount']) && !is_string($params['Amount'])) {
            $params['Amount'] = (string)$params['Amount'];
        }
        
        // 发送请求并获取响应
        $response = $this->post('/merchanttools/api/directconnect/execute', $params);
        
        // 记录详细的响应
        Log::info('Apcopay executeDirectPayment response', [
            'response' => $response
        ]);
        
        return $response;
    }
} 