<?php

namespace App\Http\Controllers\Webhook;

use App\Http\Controllers\Controller;
use App\Models\WalletTransaction;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RazorpayWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $signature = $request->header('X-Razorpay-Signature');
        $payload = $request->getContent();
        $secret = config('services.razorpay.webhook_secret');

        if (!$secret || !$signature) {
            return response()->json(['message' => 'Missing signature'], 400);
        }

        $expected = hash_hmac('sha256', $payload, $secret);
        if (!hash_equals($expected, $signature)) {
            return response()->json(['message' => 'Invalid signature'], 401);
        }

        $event = $request->input('event');
        $payloadData = $request->input('payload', []);

        if ($event === 'payment.captured') {
            $payment = $payloadData['payment']['entity'] ?? [];
            $orderId = $payment['order_id'] ?? null;
            $amount = isset($payment['amount']) ? ((int)$payment['amount']) / 100 : null;
            $notes = $payment['notes'] ?? [];
            $userId = isset($notes['user_id']) ? (int)$notes['user_id'] : null;

            if ($orderId && $userId && $amount) {
                DB::transaction(function () use ($orderId, $userId, $amount, $payment) {
                    $txn = WalletTransaction::where('razorpay_order_id', $orderId)
                        ->where('user_id', $userId)
                        ->lockForUpdate()
                        ->first();

                    if (!$txn) {
                        $txn = WalletTransaction::create([
                            'user_id' => $userId,
                            'type' => 'credit',
                            'amount' => $amount,
                            'currency' => 'INR',
                            'status' => 'pending',
                            'razorpay_order_id' => $orderId,
                            'meta' => ['source' => 'webhook'],
                        ]);
                    }

                    if ($txn->status !== 'success') {
                        $user = User::findOrFail($userId);
                        $user->wallet_balance = ($user->wallet_balance ?? 0) + $amount;
                        $user->save();

                        $txn->update([
                            'status' => 'success',
                            'razorpay_payment_id' => $payment['id'] ?? null,
                            'balance_after' => $user->wallet_balance,
                        ]);
                    }
                });
            }
        }

        return response()->json(['status' => 'ok']);
    }
}


