<?php

namespace App\Services;

use Midtrans\Config;
use Midtrans\Snap;
use Midtrans\Notification;
use App\Models\Transaksi;
use Illuminate\Support\Facades\Log;

class MidtransService
{
    public function __construct()
    {
        // Set Midtrans configuration
        Config::$serverKey = config('midtrans.server_key');
        Config::$clientKey = config('midtrans.client_key');
        Config::$isProduction = config('midtrans.is_production');
        Config::$isSanitized = config('midtrans.is_sanitized');
        Config::$is3ds = config('midtrans.is_3ds');

        // Set append notification URL
        Config::$appendNotifUrl = route('transaksi.notification');
        
        // Set overrideNotifUrl if in development
        if (!config('midtrans.is_production') && config('midtrans.notification_url')) {
            Config::$overrideNotifUrl = config('midtrans.notification_url');
        }
    }

    public function createTransaction(Transaksi $transaksi)
    {
        try {
            $items = [];
            foreach ($transaksi->items as $item) {
                $items[] = [
                    'id' => $item->menu_id,
                    'price' => (int)$item->price,
                    'quantity' => (int)$item->quantity,
                    'name' => $item->menu_name
                ];
            }

            $transaction_details = [
                'order_id' => $transaksi->transaction_code,
                'gross_amount' => (int)$transaksi->final_amount,
            ];

            $customer_details = [
                'first_name' => $transaksi->user->name,
                'email' => $transaksi->user->email,
                'phone' => $transaksi->user->phone ?? '',
            ];

            $enable_payments = [
                "credit_card", "gopay", "shopeepay", "bca_va", "bni_va", "bri_va",
                "echannel", "permata_va", "other_va", "qris"
            ];

            $transaction_data = [
                'transaction_details' => $transaction_details,
                'item_details' => $items,
                'customer_details' => $customer_details,
                'enable_payments' => $enable_payments,
                'callbacks' => [
                    'finish' => route('transaksi.finish') . '?order_id=' . $transaksi->transaction_code,
                    'error' => route('transaksi.error') . '?order_id=' . $transaksi->transaction_code,
                    'unfinish' => route('transaksi.unfinish') . '?order_id=' . $transaksi->transaction_code
                ]
            ];

            Log::info('Creating Midtrans transaction', [
                'transaction_code' => $transaksi->transaction_code,
                'amount' => $transaksi->final_amount,
                'customer' => $customer_details
            ]);

            $snapToken = Snap::getSnapToken($transaction_data);
            
            Log::info('Midtrans snap token created', [
                'transaction_code' => $transaksi->transaction_code,
                'snap_token' => $snapToken
            ]);

            return $snapToken;
        } catch (\Exception $e) {
            Log::error('Error creating Midtrans transaction', [
                'error' => $e->getMessage(),
                'transaction_code' => $transaksi->transaction_code ?? null
            ]);
            throw new \Exception('Error creating Midtrans transaction: ' . $e->getMessage());
        }
    }

    public function handleNotification($rawNotification = null)
    {
        try {
            $notification = $rawNotification ?? new Notification();

            Log::info('Handling Midtrans notification', [
                'order_id' => $notification->order_id,
                'transaction_status' => $notification->transaction_status,
                'payment_type' => $notification->payment_type,
                'fraud_status' => $notification->fraud_status ?? null
            ]);

            return [
                'order_id' => $notification->order_id,
                'transaction_status' => $notification->transaction_status,
                'payment_type' => $notification->payment_type,
                'fraud_status' => $notification->fraud_status ?? null,
                'gross_amount' => $notification->gross_amount,
                'signature_key' => $notification->signature_key
            ];
        } catch (\Exception $e) {
            Log::error('Error handling Midtrans notification', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }
} 