<?php

namespace App\Http\Controllers;

use Midtrans\Config;
use App\Models\Peserta;
use Midtrans\Notification;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MidtransCallbackController extends Controller
{
    public function handle(Request $request)
    {
    Log::info('Midtrans Callback Triggered');
    Log::info('Raw callback payload:', $request->all());

    // Set config secara manual
    Config::$serverKey = config('midtrans.server_key');
    Config::$isProduction = config('midtrans.is_production');
    Config::$isSanitized = config('midtrans.sanitize');
    Config::$is3ds = config('midtrans.enable_3ds');

    try {
        // Ambil data JSON
        $data = $request->all();

        $orderId = $data['order_id'] ?? null;
        $transactionStatus = $data['transaction_status'] ?? null;
        $paymentType = $data['payment_type'] ?? null;
        $fraudStatus = $data['fraud_status'] ?? null;

        Log::info('Midtrans Notification Parsed', [
            'order_id' => $orderId,
            'transaction_status' => $transactionStatus,
            'payment_type' => $paymentType,
            'fraud_status' => $fraudStatus,
        ]);

        $transaction = Peserta::where('order_id', $orderId)->first();

        if (!$transaction) {
            Log::warning("Transaction not found for order_id: {$orderId}");
            return response()->json(['message' => 'Transaction not found'], 404);
        }

        // Update status berdasarkan notifikasi
        if ($transactionStatus == 'capture') {
            $transaction->pembayaran = $fraudStatus == 'challenge' ? 'pending' : 'Paid';
        } elseif ($transactionStatus == 'settlement') {
            $transaction->pembayaran = 'Paid';
        } elseif (in_array($transactionStatus, ['deny', 'cancel', 'expire'])) {
            $transaction->pembayaran = 'Failed';
        } elseif ($transactionStatus == 'pending') {
            $transaction->pembayaran = 'Pending';
        }

        $transaction->save();
        Log::info("Updated Transaction Status: {$transaction->pembayaran}");

        return response()->json(['message' => 'Callback handled'], 200);

    } catch (\Exception $e) {
        Log::error('Midtrans Callback Error: ' . $e->getMessage());
        return response()->json(['message' => 'Callback error'], 500);
    }
}

}
