<?php

namespace App\Http\Controllers;

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

class WebhookController extends Controller
{
    public function paystack(Request $request)
    {
        // Verify webhook is actually from Paystack
        $secretKey = config('services.paystack.secret_key');
        $signature = $request->header('x-paystack-signature');
        $payload   = $request->getContent();

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

        $event = $request->input('event');
        $data  = $request->input('data');

        if ($event === 'charge.success') {
            $reference = $data['reference'];
            $amount    = $data['amount'] / 100; // Convert kobo to naira

            // Find transaction by reference
            $transaction = Transaction::where('reference', $reference)
                                      ->where('status', 'pending')
                                      ->first();

            if (!$transaction) {
                return response()->json(['message' => 'Transaction not found'], 404);
            }

            // Credit user wallet
            $user   = $transaction->user;
            $wallet = $user->wallet;
            $wallet->increment('balance', $amount);

            // Update transaction
            $transaction->update([
                'status'       => 'success',
                'api_response' => $data,
            ]);

            // Notify user
            Notification::create([
                'user_id' => $user->id,
                'title'   => 'Wallet Funded',
                'message' => "₦" . number_format($amount, 2) . " has been added to your wallet.",
            ]);
        }

        return response()->json(['message' => 'Webhook received'], 200);
    }
}