GOOD SHELL MAS BOY
Server: Apache/2.4.52 (Ubuntu)
System: Linux vmi1836763.contaboserver.net 5.15.0-130-generic #140-Ubuntu SMP Wed Dec 18 17:59:53 UTC 2024 x86_64
User: www-data (33)
PHP: 8.4.10
Disabled: NONE
Upload Files
File: /var/www/console.fixgini.com/app/Http/Controllers/Seller/BankDetailController.php
<?php

namespace App\Http\Controllers\Seller;

use App\Models\User;
use App\Models\Wallet;
use App\Models\BankDetail;
use App\Models\Transaction;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Services\ActivityLogger;
use App\Mail\FundRequestAdminMail;
use App\Mail\FundRequestSellerMail;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;

class BankDetailController extends Controller
{
    public function index()
    {

        try {
            $user = Auth::user();
            $bankDetail = BankDetail::where('user_id', $user->id)->first();
            return response()->json(['status' => 'success', 'message' => 'Fetched successfully', 'data' => $bankDetail], 200);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => $th->getMessage()], 401);
        }
    }

    public function requestWithdraw(Request $request)
    {
        try {
            $user = Auth::user();
            $user = User::findOrFail($user->id);
            // Check if the user has any available balance to withdraw
            if ($user->wallet->pending_withdraw <= 0) {
                return response()->json(['message' => 'No available balance to withdraw', 'status' => 'error'], 400);
            }

            // Log the user activity
            $device = $request->userAgent();
            $activityLogger = app(ActivityLogger::class);
            $activityLogger->log("Provider {$user->name} requested a withdrawal using device", $user->id, $user->role, $device);
            // Send mail to admin
            $adminMail = 'fixginiservices@gmail.com';
            Mail::to($adminMail)->send(new FundRequestAdminMail($user));
            // Send mail to seller
            // Mail::to($user->email)->send(new FundRequestSellerMail($user));

            $trxRef = strtoupper('FIXGINI-WITHDRAW' . Str::random(16));
            // record it in the wallet request history
            Transaction::create([
                'user_id' => $user->id,
                'type' => 'withdraw',
                'description' => "Withdrawal request [{$user->wallet->currency} {$user->wallet->pending_withdraw}] was successfully initiated",
                'amount' => $user->wallet->pending_withdraw,
                'status' => 'pending',
                'tx_ref' => $trxRef
            ]);

            // $userWallet = Wallet::where('user_id', $user->id)->update(['pending_withdraw' => $user->wallet->pending_withdraw]);


            return response()->json(['status' => 'success', 'message' => 'Withdraw Request sent.'], 200);
        } catch (\Throwable $th) {
            Log::error($th->getMessage());
            return response()->json(['status' => 'error', 'message' => $th->getMessage()], 401);
        }
    }

    public function transactionHistory()
    {
        try {
            $transactions = Transaction::where('user', Auth::user()->id)->first();
            return response()->json(['status' => 'success', 'message' => 'Fetched successfully', 'data' => $transactions], 200);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => $th->getMessage()], 401);
        }
    }

    public function store(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'user_id' => 'required|exists:users,id',
                'bank_name' => 'required|string|max:200',
                'account_no' => 'required|max:10|unique:bank_details,account_no,' . ($request->user_id ? BankDetail::where('user_id', $request->user_id)->value('id') : 'NULL'),
                'account_name' => 'required|string',
                'bank_code' => 'required|string',
            ]);

            // Check if the user already has a bank detail
            $existingBankDetail = BankDetail::where('user_id', $validatedData['user_id'])->first();

            if ($existingBankDetail) {
                // Update the existing bank details
                $existingBankDetail->update($validatedData);
                return response()->json(['status' => 'success', 'message' => 'Bank details updated successfully', 'data' => $existingBankDetail], 200);
            }

            // If no existing record, create a new one
            $bankDetail = BankDetail::create($validatedData);
            return response()->json(['status' => 'success', 'message' => 'Bank details added successfully', 'data' => $bankDetail], 201);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => $th->getMessage()], 400);
        }
    }

    public function destroy(Request $request)
    {
        try {
            $validatedData = $request->validate(
                [
                    'user_id' => 'required|exists:bank_details,user_id',
                ]
            );
            $bankDetail = BankDetail::where('user_id', $validatedData['user_id'])->first();
            $bankDetail->delete();
            return response()->json(['status' => 'success', 'message' => 'Deleted successfully']);
        } catch (\Throwable $th) {
            return response()->json(['status' => 'error', 'message' => $th->getMessage()], 401);
        }
    }

    public function queryAccountNo(Request $request)
    {
        try {
            // Validate request input
            $validated = $request->validate([
                'account_number' => 'required|numeric',
                'account_bank' => 'required|numeric',
            ]);

            // Prepare request body
            $body = [
                'account_number' => $validated['account_number'],
                'account_bank' => $validated['account_bank'], // Convert to integer
            ];

            // Flutterwave API endpoint for account verification
            $flwUrl = "https://api.flutterwave.com/v3/accounts/resolve";

            // Send request to Flutterwave API
            $response = Http::withHeaders([
               'Authorization' => 'Bearer ' . config('flutterwave.secret_key'), // Use the key from .env
                'Content-Type'  => 'application/json',
            ])->post($flwUrl, $body); // Ensure the request body is passed here

            // Decode response
            $responseData = $response->json();

            // Log response for debugging
            Log::info('Flutterwave Account Verification Response:', $responseData);

            // Check if API call was successful
            if ($response->successful() && isset($responseData['status']) && $responseData['status'] === 'success') {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Account verified successfully',
                    'data' => $responseData['data'], // Only return relevant data
                ], 200);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => $responseData['message'] ?? 'Failed to verify account',
                    'error_details' => $responseData,
                ], 400);
            }
        } catch (\Exception $e) {
            Log::error('Error in account verification: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Bank verification error occurred',
                'error_details' => $e->getMessage(),
            ], 500);
        }
    }
    
    public function bankList()
    {
        try { 
            // Flutterwave API endpoint for account verification
            $flwUrl = "https://api.flutterwave.com/v3/banks/NG";

            // Send request to Flutterwave API
            $response = Http::withHeaders([
               'Authorization' => 'Bearer ' . config('flutterwave.secret_key'), // Use the key from .env
                'Content-Type'  => 'application/json',
                    'accept' => 'application/json',
            ])->get($flwUrl); // Ensure the request body is passed here

            // Decode response
            $responseData = $response->json();

            // Log response for debugging
            // Log::info('Flutterwave Bank list Response:', $responseData);

            // Check if API call was successful
            if ($response->successful() && isset($responseData['status']) && $responseData['status'] === 'success') {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Bank listed successfully',
                    'data' => $responseData['data'], // Only return relevant data
                ], 200);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => $responseData['message'] ?? 'Failed to list banks',
                    'error_details' => $responseData,
                ], 400);
            }
        } catch (\Exception $e) {
            // Log::error('Error to list banks: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Bank list error occurred',
                'error_details' => $e->getMessage(),
            ], 500);
        }
    }

  
}