<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WalletTransaction;
use App\Services\Payments\PaymentSettlementService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MpesaCallbackController extends Controller
{
    protected PaymentSettlementService $settlementService;

    public function __construct(PaymentSettlementService $settlementService)
    {
        $this->settlementService = $settlementService;
    }

    /**
     * Handle M-Pesa STK Push Callback
     */
    public function callback(Request $request)
    {
        $callbackData = $request->input('Body.stkCallback');
        
        Log::info('Mpesa Callback Received', ['data' => $callbackData]);

        if (!$callbackData) {
            return response()->json(['ResultCode' => 1, 'ResultDesc' => 'No callback data found']);
        }

        $merchantRequestId = $callbackData['MerchantRequestID'];
        $checkoutRequestId = $callbackData['CheckoutRequestID'];
        $resultCode = $callbackData['ResultCode'];
        $resultDesc = $callbackData['ResultDesc'];

        $transaction = WalletTransaction::where('merchant_request_id', $merchantRequestId)
            ->where('checkout_request_id', $checkoutRequestId)
            ->first();

        if (!$transaction) {
            Log::error('Mpesa Callback Error: Transaction not found', [
                'merchant_request_id' => $merchantRequestId,
                'checkout_request_id' => $checkoutRequestId
            ]);
            return response()->json(['ResultCode' => 1, 'ResultDesc' => 'Transaction not found']);
        }

        // Check if already processed
        if ($transaction->status !== 'pending') {
            return response()->json(['ResultCode' => 0, 'ResultDesc' => 'Already processed']);
        }

        if ($resultCode == 0) {
            // Success
            $callbackItems = $callbackData['CallbackMetadata']['Item'] ?? [];
            $mpesaReceiptNumber = null;

            foreach ($callbackItems as $item) {
                if ($item['Name'] === 'MpesaReceiptNumber') {
                    $mpesaReceiptNumber = $item['Value'];
                    break;
                }
            }

            $transaction->provider_response = $callbackData;
            $transaction->provider_status = 'Success';
            $transaction->save();

            $this->settlementService->settle($transaction, $mpesaReceiptNumber);

            return response()->json(['ResultCode' => 0, 'ResultDesc' => 'Success']);
        } else {
            // Failure
            $this->settlementService->failTransaction($transaction, $resultDesc, $callbackData);

            return response()->json(['ResultCode' => 0, 'ResultDesc' => 'Acknowledged Failure']);
        }
    }
}
