<?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, $secret)
    {
        //return $secret;
        // Log the incoming request for debugging
        Log::info('Webhook received', ['headers' => $request->headers->all(), 'body' => $request->all()]);
        // Define your expected secret
        $expectedSecret = env("WEBHOOK_SECRET"); // Replace with your actual secret key

        // Verify the secret
        if ($secret !== $expectedSecret) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        // 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_API_SECRET");
        // 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
                    $curl = curl_init();

                    curl_setopt_array($curl, array(
                        CURLOPT_URL => $baseUrl . '/business/vcard-details',
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_ENCODING => '',
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_TIMEOUT => 0,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_POSTFIELDS => '{
                         "cardid": "'.$request->card_id.'"
                        }',
                        CURLOPT_HTTPHEADER => array(
                            'Content-Type: application/json',
                            'Authorization: ' . 'Bearer '.$secretKey,
                        ),
                    ));

                    $cardDetailsResponse = curl_exec($curl);
                    curl_close($curl);
                    if ($cardDetailsResponse) {
                        $cardDetails = json_decode($cardDetailsResponse, true);
//return $cardDetails;
                        if (isset($cardDetails['currency'])) {
                            // Store or update the virtual card details in the database
                            $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
                            $curl = curl_init();

                            curl_setopt_array($curl, array(
                                CURLOPT_URL => $baseUrl . '/business/vcard-pan',
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_ENCODING => '',
                                CURLOPT_MAXREDIRS => 10,
                                CURLOPT_TIMEOUT => 0,
                                CURLOPT_FOLLOWLOCATION => true,
                                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                CURLOPT_CUSTOMREQUEST => 'POST',
                                CURLOPT_POSTFIELDS => json_encode(['cardid' => $request->card_id]),
                                CURLOPT_HTTPHEADER => array(
                                    'Content-Type: application/json',
                                    'Authorization: ' . 'Bearer ' . $secretKey,
                                ),
                            ));

                            $cardPanResponse = curl_exec($curl);
                            curl_close($curl);

                            if ($cardPanResponse) {
                                $cardPanDetails = json_decode($cardPanResponse, true);
//return $cardPanDetails;
                                if (isset($cardPanDetails['cardnumber'])) {
                                    // Update the virtual card with full PAN details
                                    $virtualCard->card_number = $cardPanDetails['cardnumber'];
                                    $virtualCard->cvv = $cardPanDetails['cvv'];
                                    $virtualCard->expiryyr = $cardPanDetails['expiryyr'];
                                    $virtualCard->expirymnt = $cardPanDetails['expirymnt'];
                                    $virtualCard->expiry_date = $cardPanDetails['expirymnt'].'/'.$cardPanDetails['expiryyr'];
                                    $virtualCard->cardstatus= $cardPanDetails['cardstatus'];
                                    $virtualCard->save();
                                    if($transaction->referer_user_id) {
                                        saveReferTracking($transaction->referer_user_id,'VirtualCard',$transaction->user_id,$transaction->refer_bonus);
                                    }
                                    @email([
                                        'email'   => $virtualCard->user->email,
                                        'name'    => $virtualCard->user->name,
                                        'subject' => 'Virtual Card Issued',
                                        'message' => 'Congratulation Your virtual card is live enjoy!!',
                                    ]);
                                } else {
                                    Log::error('Failed to fetch card PAN details:', ['response' => $cardPanDetails]);
                                }
                            } else {
                                Log::error('Failed to fetch card PAN details: No response from API.');
                            }
                        } else {
                            Log::error('Failed to fetch card details:', ['response' => $cardDetails]);
                        }
                    } else {
                        Log::error('Failed to fetch card details: No response from API.');
                    }
                }

            }
        } else {
            Log::warning('Transaction not found for reference: ' . $request->reference);
        }


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

}
