<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;

class TripayService
{
    private $apiKey;
    private $privateKey;
    private $merchantCode;
    private $baseUrl;
    
    public function __construct()
    {
        $this->apiKey = config('services.tripay.api_key');
        $this->privateKey = config('services.tripay.private_key');
        $this->merchantCode = config('services.tripay.merchant_code');
        $this->baseUrl = config('services.tripay.base_url');
    }
    
    public function getPaymentChannels()
    {
        try {
            $client = new Client(['verify' => false]);
            
            $response = $client->get($this->baseUrl . '/merchant/payment-channel', [
                'headers' => ['Authorization' => 'Bearer ' . $this->apiKey],
            ]);
            
            $data = json_decode($response->getBody()->getContents(), true);
            
            return $data['success'] ? ['success' => true, 'data' => $data['data']] : ['success' => false];
            
        } catch (\Exception $e) {
            Log::error('Tripay Channels Error', ['error' => $e->getMessage()]);
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
    
    public function createTransaction($data)
{
    try {
        $merchantRef = $data['merchant_ref'] ?? 'INV-' . time() . '-' . rand(1000, 9999);
        
        // Parse order_items kalo ada
        $orderItems = $data['order_items'] ?? [[
            'name' => $data['product_name'] ?? 'Product',
            'price' => $data['amount'] ?? 0,
            'quantity' => 1,
        ]];
        
        $payload = [
            'method' => $data['method'],  // ← FIX: dari 'payment_method' ke 'method'
            'merchant_ref' => $merchantRef,
            'amount' => $data['amount'],
            'customer_name' => $data['customer_name'],
            'customer_email' => $data['customer_email'],
            'customer_phone' => $data['customer_phone'] ?? '081234567890',
            'order_items' => $orderItems,  // ← FIX: pake order_items yang udah di-pass
            'return_url' => $data['return_url'] ?? url('/payment/success'),  // ← FIX: pake return_url yang di-pass
            'expired_time' => (time() + (24 * 60 * 60)),
            'signature' => $this->generateSignature($merchantRef, $data['amount']),
        ];
        
        $client = new Client(['verify' => false]);
        
        $response = $client->post($this->baseUrl . '/transaction/create', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'json' => $payload,
        ]);
        
        $result = json_decode($response->getBody()->getContents(), true);
        
        if ($result['success']) {
            return [
                'success' => true,
                'data' => [
                    'reference' => $result['data']['reference'],
                    'merchant_ref' => $merchantRef,
                    'checkout_url' => $result['data']['checkout_url'],  // ← FIX: dari 'payment_url' ke 'checkout_url'
                    'qr_url' => $result['data']['qr_url'] ?? null,
                    'amount' => $result['data']['amount'],
                    'total_fee' => $result['data']['total_fee'] ?? 0,
                    'payment_name' => $result['data']['payment_name'] ?? null,
                    'instructions' => $result['data']['instructions'] ?? null,
                    'expired_time' => $result['data']['expired_time'] ?? null,
                ]
            ];
        }
        
        return ['success' => false, 'message' => $result['message'] ?? 'Failed'];
        
    } catch (\Exception $e) {
        Log::error('Tripay Create Error', ['error' => $e->getMessage(), 'data' => $data]);
        return ['success' => false, 'message' => $e->getMessage()];
    }
}
    
    public function verifyCallbackSignature($json, $signature)
    {
        return $signature === hash_hmac('sha256', $json, $this->privateKey);
    }
    
    private function generateSignature($merchantRef, $amount)
    {
        return hash_hmac('sha256', $this->merchantCode . $merchantRef . $amount, $this->privateKey);
    }
    public function calculateFee($paymentCode, $amount)
{
    // Fee structure based on Tripay
    $feeStructure = [
        'QRIS' => ['type' => 'percent', 'value' => 0.7],
        'QRISC' => ['type' => 'percent', 'value' => 0.7],
        'SHOPEEPAY' => ['type' => 'percent', 'value' => 1.5],
        'DANA' => ['type' => 'percent', 'value' => 1.5],
        'OVO' => ['type' => 'percent', 'value' => 2],
        'BRIVA' => ['type' => 'flat', 'value' => 4000],
        'BCAVA' => ['type' => 'flat', 'value' => 4000],
        'BNIVA' => ['type' => 'flat', 'value' => 4000],
        'MANDIRIVA' => ['type' => 'flat', 'value' => 4000],
        'PERMATAVA' => ['type' => 'flat', 'value' => 4000],
        'ALFAMART' => ['type' => 'flat', 'value' => 2500],
        'INDOMARET' => ['type' => 'flat', 'value' => 2500],
    ];
    
    $fee = $feeStructure[strtoupper($paymentCode)] ?? ['type' => 'percent', 'value' => 1];
    
    if ($fee['type'] === 'percent') {
        return (int) ceil($amount * ($fee['value'] / 100));
    }
    
    return (int) $fee['value'];
}
/**
 * Check transaction status from Tripay
 */
public function checkTransactionStatus($reference)
{
    try {
        $client = new Client(['verify' => false]);
        
        $response = $client->get($this->baseUrl . '/transaction/detail', [
            'headers' => ['Authorization' => 'Bearer ' . $this->apiKey],
            'query' => ['reference' => $reference],
        ]);
        
        $data = json_decode($response->getBody()->getContents(), true);
        
        if ($data['success']) {
            return [
                'success' => true,
                'data' => [
                    'reference' => $data['data']['reference'],
                    'status' => $data['data']['status'],
                    'paid_at' => $data['data']['paid_at'] ?? null,
                ],
            ];
        }
        
        return ['success' => false, 'message' => $data['message'] ?? 'Failed'];
        
    } catch (\Exception $e) {
        Log::error('Tripay Status Check Error', ['error' => $e->getMessage()]);
        return ['success' => false, 'message' => $e->getMessage()];
    }
}
}
