<?php

namespace App\Http\Controllers\Gateway;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\TransactionHistory;
use App\Models\User;
use App\Models\VirtualCard;
use App\Models\Wallet;
use App\Models\Withdrawals;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use KingFlamez\Rave\Facades\Rave as Flutterwave;

class BolddController extends Controller
{

    /**
     * Receives Flutterwave webhook
     * @return void
     */
    public function handleWebhook(Request $request)
    {
        // Log the incoming request for debugging
        Log::info('Webhook received', ['headers' => $request->headers->all(), 'body' => $request->all()]);


        // Validate the incoming request
      /*  $validatedData = $request->validate([
            'event_type' => 'required|string',
            'event_status' => 'required|string',
            'card_id' => 'required|string',
            'paid_through' => 'required|string',
            'reference' => 'required|string',
            // Add other necessary validations based on your requirements
        ]);
*/
        $baseUrl = env("CARD_URL");
        $secretKey = env("CARD_SECRET_KEY");
        // Check if the event is a successful virtual card transaction
        if ($request->paid_through === 'virtualcard' && $request->event_status === 'success') {
            // Update the transaction_histories table
            $transaction = TransactionHistory::where('transaction_ref', $request->reference)->first();

            if ($transaction) {
                $transaction->status = $request->event_status;
                $transaction->save();
                if($transaction->status=='success') {


                    // Fetch card details using the card_id
                    $cardDetailsResponse = Http::withHeaders([
                        'Authorization' => 'Bearer YOUR_SECRET_KEY',
                        'Content-Type' => 'application/json',
                    ])->post($baseUrl . '/business/vcard-details', [
                        'cardid' => $request->card_id,
                    ]);

                    if ($cardDetailsResponse->successful()) {
                        $cardDetails = $cardDetailsResponse->json();

                        // Store or update the virtual card details in the database
                        // Update or create the virtual card record
                        $virtualCard = VirtualCard::updateOrCreate(
                            ['card_id' => $request->card_id],
                            [
                                'user_id' => $transaction->user_id,
                                'currency' => $cardDetails['currency'],
                                'card_balance' => $cardDetails['current_bal'],
                                'first_name' => $cardDetails['holdername'],
                                'billing_address' => $cardDetails['billingAddress']['line1'],
                                'billing_city' => $cardDetails['billingAddress']['city'],
                                'billing_state' => $cardDetails['billingAddress']['state'],
                                'billing_postal_code' => $cardDetails['billingAddress']['postalCode'],
                                'billing_country' => $cardDetails['billingAddress']['country'],
                                'status' => $cardDetails['cardstatus'],
                                'card_icon' => $cardDetails['cardicon'],
                                'holdertype' => $cardDetails['holdertype'],
                                'cardbrand' => $cardDetails['cardbrand'],
                                'customerid' => $cardDetails['customerid'],
                                'available_bal' => $cardDetails['available_bal'],
                                'masked_pan' => $cardDetails['cardpan'],
                                'created_at' => now(),
                                'updated_at' => now(),
                            ]
                        );

                        // Fetch the full card PAN details
                        $cardPanResponse = Http::withHeaders([
                            'Authorization' => 'Bearer '.$secretKey,
                            'Content-Type' => 'application/json',
                        ])->post($baseUrl.'/business/vcard-pan', [
                            'cardid' => $request->card_id,
                        ]);

                        if ($cardPanResponse->successful()) {
                            $cardPanDetails = $cardPanResponse->json();

                            // Update the virtual card with full PAN details
                            $virtualCard->card_number = $cardPanDetails['cardnumber'];
                            $virtualCard->cvv = $cardPanDetails['cvv'];
                            $virtualCard->save();
                        } else {
                            Log::error('Failed to fetch card PAN details:', $cardPanResponse->body());
                        }
                    } else {
                        Log::error('Failed to fetch card details:', $cardDetailsResponse->body());
                    }
                }
            } else {
                Log::warning('Transaction not found for reference: ' . $request->reference);
            }
        }

        // Respond to the webhook sender
        return response()->json(['status' => 'success'], 200);
    }

}
