<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\VirtualCardRequest;
use App\Models\TransactionHistory;
use App\Models\User;
use App\Models\VirtualCard;
use App\Models\VirtualcardCustomer;
use App\Models\VirtualCardKy;
use App\Models\VirtualCardsSetting;
use App\Traits\RespondsWithHttp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

class VirtualCardController extends Controller
{
    use RespondsWithHttp;

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $virtualCards = VirtualCard::where('user_id', auth()->user()->id)->get();

        if ($this->expectsJson($request)) {
            return $this->respond($request, ['virtualCards' => $virtualCards], 'Virtual cards retrieved.');
        }

        return view('user.virtual-card.index', compact('virtualCards'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request)
    {
        $userid = auth()->user()->id;

        // Check if KYC is created
        $kyc = VirtualCardKy::where('user_id', $userid)->first();
        $virtualCardSetting = VirtualCardsSetting::first();

        if (!$kyc) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Please submit your Virtual card creation KYC first.', 400);
            }
            return Redirect::route('user.virtual-card-kyc.create')->with('error', 'Please submit your Virtual card creation KYC first.');
        }

        // Check KYC status
        if ($kyc->status == 'rejected') {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Your KYC is rejected. Please resubmit, ensuring your ID Card is visible and matches your picture.', 400);
            }
            return Redirect::route('user.virtual-card-kyc.edit')->with('error', 'Your KYC is rejected. Please resubmit, ensuring your ID Card is visible and matches your picture.');
        } elseif ($kyc->status == 'pending') {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Your KYC is still under review. Please try again later or contact our support team.', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Your KYC is still under review. Please try again later or contact our support team.');
        } elseif ($kyc->status != 'approved') {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Your KYC is not approved. Please contact support.', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Your KYC is not approved. Please contact support.');
        }

        // Check the number of existing virtual cards
        $virtualCardCount = VirtualCard::where('user_id', $userid)->count();
        if ($virtualCardCount >= 4) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'You have reached the maximum limit of 4 virtual cards.', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'You have reached the maximum limit of 4 virtual cards.');
        }

        // Check if customer exists
        $customer = VirtualcardCustomer::where('user_id', $userid)->first();
        $virtualCard = $customer ? VirtualCard::where('user_id', $userid)->where('status', 1)->first() : null;

        if ($this->expectsJson($request)) {
            return $this->respond($request, ['virtualCard' => $virtualCard, 'virtualCardSetting' => $virtualCardSetting], 'Virtual card creation data retrieved.');
        }

        return view('user.virtual-card.create', compact('virtualCard', 'virtualCardSetting'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $user = auth()->user();

        $request->validate([
            'card_type' => 'required',
            'funding_amount' => 'required|numeric',
        ]);

        $virtualCardSetting = VirtualCardsSetting::where('status', 'active')->first();
        $fundingAmount = $request->funding_amount;

        if ($fundingAmount < $virtualCardSetting->minimum_funding) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Minimum funding amount is $' . $virtualCardSetting->minimum_funding, 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Minimum funding amount is $' . $virtualCardSetting->minimum_funding);
        }

        // Check virtual card limit
        $virtualCardCount = VirtualCard::where('user_id', $user->id)->count();
        if ($virtualCardCount >= 4) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'You have reached the maximum limit of 4 virtual cards.', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'You have reached the maximum limit of 4 virtual cards.');
        }

        $wallet = $user->getMyWallet();
        if (!$wallet) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Wallet not found', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Wallet not found');
        }

        $cardAmountInUsd = $virtualCardSetting->issuing_fee + $fundingAmount;
        $cardAmountInNaira = $virtualCardSetting->exchange_rate * $cardAmountInUsd;

        if ($wallet->balance < $cardAmountInNaira) {
            \Log::info('Insufficient balance', ['balance' => $cardAmountInNaira]);
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Insufficient balance. Please fund your wallet and try again.', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Insufficient balance. Please fund your wallet and try again.');
        }

        // Deduct wallet balance
        $wallet->balance -= $cardAmountInNaira;

        // Check if customer data already exists
        $virtualCardCustomer = VirtualcardCustomer::where('user_id', $user->id)->first();
        $trackId = null;

        if (!$virtualCardCustomer) {
            // Create new customer data
            $virtualCardKys = VirtualCardKy::where('user_id', $user->id)
                ->where('status', 'approved')
                ->first();

            if (!$virtualCardKys) {
                if ($this->expectsJson($request)) {
                    return $this->respondWithError($request, 'No approved KYC found.', 400);
                }
                return Redirect::route('user.virtual-cards.mycards')->with('error', 'No approved KYC found.');
            }

            $url = env("CARD_URL") . '/business/createcard-customer';
            $secretApi = env("CARD_API_SECRET");
            $headers = [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $secretApi,
            ];

            $data = [
                "first_name" => $user->first_name,
                "last_name" => $user->surname,
                "phone_number" => $user->phone,
                "bvnno" => $virtualCardKys->bvn,
                "email_address" => $user->email,
                "address" => [
                    "house_no" => $virtualCardKys->house_no,
                    "street" => $virtualCardKys->street,
                    "city" => getCityName($virtualCardKys->city),
                    "state" => getStateName($virtualCardKys->state),
                    "country" => $virtualCardKys->country,
                    "postal_code" => $virtualCardKys->postal_code
                ],
                "identity" => [
                    "idtype" => $virtualCardKys->id_type,
                    "idno" => $virtualCardKys->nin_no,
                    "idurl" => getPhoto($virtualCardKys->id_image_url),
                    "issuance_country" => $virtualCardKys->country
                ]
            ];
                        \Log::info('Card Issuance API Data:', $data);

            try {
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                $response = curl_exec($ch);
                if (curl_errno($ch)) {
                    throw new \Exception(curl_error($ch));
                }
                curl_close($ch);

                $apiResponse = json_decode($response, true);

                if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                    $trackId = $apiResponse['trackid'] ?? null;
                    VirtualcardCustomer::create([
                        'user_id' => $user->id,
                        'first_name' => $user->first_name,
                        'last_name' => $user->surname,
                        'phone_number' => $user->phone,
                        'bvnno' => $virtualCardKys->bvn,
                        'email_address' => $user->email,
                        'house_no' => $virtualCardKys->house_no,
                        'street' => $virtualCardKys->street,
                        'city' => $virtualCardKys->city,
                        'state' => getStateName($virtualCardKys->state),
                        'country' => $virtualCardKys->country,
                        'postal_code' => $virtualCardKys->postal_code,
                        'idtype' => $virtualCardKys->id_type,
                        'idno' => $virtualCardKys->nin_no,
                        'idurl' => getPhoto($virtualCardKys->id_image_url),
                        'issuance_country' => $virtualCardKys->country,
                        'trackid' => $trackId,
                    ]);
                } else {
                    $errorMessage = $apiResponse['message'] ?? 'Failed to create customer.';
                    if ($this->expectsJson($request)) {
                        return $this->respondWithError($request, $errorMessage, 400);
                    }
                    return Redirect::route('user.virtual-cards.mycards')->with('error', $errorMessage);
                }
            } catch (\Exception $e) {
                \Log::error('Customer creation failed: ' . $e->getMessage());
                if ($this->expectsJson($request)) {
                    return $this->respondWithError($request, 'Failed to create customer: ' . $e->getMessage(), 400);
                }
                return Redirect::route('user.virtual-cards.mycards')->with('error', 'Failed to create customer: ' . $e->getMessage());
            }
        } else {
            $trackId = $virtualCardCustomer->trackid;
        }

        $cardCreationStatus = $this->issueCard($trackId, $request->card_type, $virtualCardSetting, $wallet, $fundingAmount);
        $httpStatus = $cardCreationStatus['status'] === true ? 201 : 400;
        return $this->respond($request, [], $cardCreationStatus['message'], 'user.virtual-cards.mycards', $httpStatus);
    }

    private function issueCard($trackingId, $cardType, $virtualCardSetting, $wallet, $fundingAmount)
    {
        $userId = auth()->user()->id;
        $cardAmountInUsd = $virtualCardSetting->issuing_fee + $fundingAmount;
        $cardAmountInNaira = $virtualCardSetting->exchange_rate * $cardAmountInUsd;

        $payload = [
            "currency" => "USD",
            "trackingid" => $trackingId,
            "cardbrand" => $cardType,
            "amount" => $fundingAmount,
        ];
        $secretKey = env('CARD_API_SECRET');
        $url = env('CARD_URL') . '/business/vcard-issuance';

        try {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                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($payload),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $secretKey,
                ],
            ]);

            $response = curl_exec($curl);
            if (curl_errno($curl)) {
                throw new \Exception(curl_error($curl));
            }
            curl_close($curl);

            $apiResponse = json_decode($response, true);
            \Log::info('Card Issuance API Response:', $apiResponse);

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $cardTransaction = TransactionHistory::create([
                    'descriptions' => 'Card Issuance',
                    'trade_id' => null,
                    'request_id' => $trackingId,
                    'tradedcard_details_id' => null,
                    'transaction_ref' => $apiResponse['txref'] ?? null,
                    'user_id' => $userId,
                    'amount' => $cardAmountInNaira,
                    'exchange_rate' => $virtualCardSetting->exchange_rate,
                    'transaction_amount_in_usd' => $cardAmountInUsd,
                    'transaction_type' => 'Debit',
                    'created_by' => $userId,
                    'source' => 'Virtual Card',
                    'status' => 'pending',
                    'status_at' => now(),
                    'status_by' => $userId,
                    'status_reason' => $apiResponse['message'] ?? 'Card issuance pending',
                    'refer_bonus' => $virtualCardSetting->referer_bonus,
                    'referer_user_id' => auth()->user()->refer_by,
                    'rate' => null,
                    'currency' => 'USD',
                ]);

                try {
                    $virtualCard = VirtualCard::create([
                        'user_id' => $userId,
                        'card_id' => $apiResponse['card_id'] ?? null,
                        'currency' => 'USD',
                        'holdertype' => 'individual',
                        'cardbrand' => $cardType,
                        'customerid' => $trackingId,
                        'card_balance' => $fundingAmount,
                        'available_bal' => $fundingAmount,
                        'first_name' => auth()->user()->first_name,
                        'last_name' => auth()->user()->surname,
                        'email' => auth()->user()->email,
                        'phone' => auth()->user()->phone,
                        'card_number' => $apiResponse['card_number'] ?? null,
                        'masked_pan' => $apiResponse['masked_pan'] ?? null,
                        'cvv' => $apiResponse['cvv'] ?? null,
                        'expiry_date' => $apiResponse['expiry_date'] ?? null,
                        'card_type' => $cardType,
                        'status' => 1,
                        'is_active' => true,
                        'billing_name' => auth()->user()->first_name . ' ' . auth()->user()->surname,
                        'billing_address' => $apiResponse['billing_address'] ?? null,
                        'billing_city' => $apiResponse['billing_city'] ?? null,
                        'billing_state' => $apiResponse['billing_state'] ?? null,
                        'billing_postal_code' => $apiResponse['billing_postal_code'] ?? null,
                        'billing_country' => $apiResponse['billing_country'] ?? 'NG',
                    ]);

                    \Log::info('VirtualCard created:', $virtualCard->toArray());
                } catch (\Exception $e) {
                    \Log::error('Failed to create VirtualCard: ' . $e->getMessage());
                    return ['status' => 'error', 'message' => 'Failed to save card: ' . $e->getMessage()];
                }

                $wallet->save();

                if (auth()->user()->refer_by) {
                    auth()->user()->saveToClientWallet(
                        $cardTransaction->refer_bonus,
                        $cardTransaction->referer_user_id,
                        'refer',
                        'Virtual Card',
                        $cardTransaction->user_id
                    );
                }

                return ['status' => 'success', 'message' => $apiResponse['message'] ?? 'Card issued successfully'];
            } else {
                $errorReason = $apiResponse['message'] ?? 'Unknown error';
                TransactionHistory::create([
                    'descriptions' => 'Card Issuance',
                    'trade_id' => null,
                    'request_id' => $trackingId,
                    'tradedcard_details_id' => null,
                    'transaction_ref' => null,
                    'amount' => $cardAmountInNaira,
                    'user_id' => $userId,
                    'transaction_type' => 'Debit',
                    'created_by' => $userId,
                    'exchange_rate' => $virtualCardSetting->exchange_rate,
                    'transaction_amount_in_usd' => $cardAmountInUsd,
                    'source' => 'Virtual Card',
                    'status' => 'failed',
                    'status_at' => now(),
                    'status_by' => $userId,
                    'status_reason' => $errorReason,
                    'refer_bonus' => null,
                    'referer_user_id' => null,
                    'rate' => null,
                    'currency' => 'USD',
                ]);

                return ['status' => 'error', 'message' => $errorReason];
            }
        } catch (\Exception $e) {
            \Log::error('Card issuance failed: ' . $e->getMessage());
            TransactionHistory::create([
                'descriptions' => 'Card Issuance',
                'trade_id' => null,
                'request_id' => $trackingId,
                'tradedcard_details_id' => null,
                'transaction_ref' => null,
                'amount' => $cardAmountInNaira,
                'exchange_rate' => $virtualCardSetting->exchange_rate,
                'transaction_amount_in_usd' => $cardAmountInUsd,
                'user_id' => $userId,
                'transaction_type' => 'Debit',
                'created_by' => $userId,
                'source' => 'USDCard',
                'status' => 'failed',
                'status_at' => now(),
                'status_by' => $userId,
                'status_reason' => $e->getMessage(),
                'refer_bonus' => null,
                'referer_user_id' => null,
                'rate' => null,
                'currency' => 'NGN',
            ]);

            return ['status' => 'error', 'message' => 'Card issuance failed: ' . $e->getMessage()];
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, $id)
    {
        $virtualCard = VirtualCard::where('_id', $id)->where('user_id', auth()->user()->id)->first();
        if (!$virtualCard) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Virtual card not found.', 404);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Virtual card not found.');
        }

        getCardBalance($virtualCard->card_id);

        if ($this->expectsJson($request)) {
            return $this->respond($request, ['virtualCard' => $virtualCard], 'Virtual card details retrieved.');
        }

        return view('user.virtual-card.show', compact('virtualCard'));
    }

    public function fundCard(Request $request, $id)
    {
        $virtualCard = VirtualCard::where('_id', $id)
            ->where('user_id', auth()->user()->id)
            ->first();

        if (!$virtualCard) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Virtual card not found.', 404);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Virtual card not found.');
        }

        $validated = $request->validate([
            'funding_amount' => 'required|numeric',
        ]);

        $user = auth()->user();
        $wallet = $user->getMyWallet();
        $fundAmount = $request->funding_amount;
        $cardSetting = getCardSetting();
        $fundInNgn = $cardSetting->exchange_rate * $fundAmount;

        if ($wallet->balance < $fundInNgn) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Insufficient balance. Please fund your wallet and try again.', 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Insufficient balance. Please fund your wallet and try again.');
        }

        $baseUrl = env('CARD_URL');
        $secretKey = env('CARD_API_SECRET');

        $payload = [
            'vcardid' => $virtualCard->card_id,
            'amount' => $fundAmount,
        ];

        try {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => "$baseUrl/business/vcard-fund",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    "Authorization: Bearer $secretKey",
                ],
            ]);

            $response = curl_exec($curl);
            if (curl_errno($curl)) {
                throw new \Exception(curl_error($curl));
            }
            curl_close($curl);

            $apiResponse = json_decode($response, true);

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                TransactionHistory::create([
                    'descriptions' => 'Card Funding',
                    'request_id' => $virtualCard->card_id,
                    'transaction_ref' => $apiResponse['txref'],
                    'amount' => $fundInNgn,
                    'user_id' => $user->id,
                    'transaction_type' => 'Card Funding',
                    'created_by' => $user->id,
                    'source' => 'Virtual Card',
                    'status' => 'success',
                    'status_at' => now(),
                    'status_by' => $user->id,
                    'status_reason' => $apiResponse['message'],
                    'exchange_rate' => $cardSetting->exchange_rate,
                    'transaction_amount_in_usd' => $fundAmount,
                    'rate' => $fundAmount,
                    'currency' => 'USD',
                ]);

                $wallet->balance -= $fundInNgn;
                $wallet->save();

                return $this->respond($request, [], 'Card funded successfully', 'user.virtual-cards.mycards');
            } else {
                $statusReason = $apiResponse['message'] ?? 'Unknown error occurred, please try again later';
                TransactionHistory::create([
                    'descriptions' => 'Card Funding',
                    'request_id' => $virtualCard->card_id,
                    'transaction_ref' => null,
                    'amount' => $fundInNgn,
                    'user_id' => $user->id,
                    'transaction_type' => 'Card Funding',
                    'created_by' => $user->id,
                    'source' => 'Virtual Card',
                    'status' => 'failed',
                    'status_at' => now(),
                    'status_by' => $user->id,
                    'status_reason' => $statusReason,
                    'exchange_rate' => $cardSetting->exchange_rate,
                    'transaction_amount_in_usd' => $fundAmount,
                    'rate' => $fundAmount,
                    'currency' => 'USD',
                ]);

                if ($this->expectsJson($request)) {
                    return $this->respondWithError($request, 'Card funding failed: ' . $statusReason, 400);
                }
                return Redirect::route('user.virtual-cards.mycards')->with('error', 'Card funding failed: ' . $statusReason);
            }
        } catch (\Exception $e) {
            \Log::error('Card funding failed: ' . $e->getMessage());
            TransactionHistory::create([
                'descriptions' => 'Card Funding',
                'request_id' => $virtualCard->card_id,
                'transaction_ref' => null,
                'amount' => $fundInNgn,
                'user_id' => $user->id,
                'transaction_type' => 'Card Funding',
                'created_by' => $user->id,
                'source' => 'Virtual Card',
                'status' => 'failed',
                'status_at' => now(),
                'status_by' => $user->id,
                'status_reason' => $e->getMessage(),
                'exchange_rate' => $cardSetting->exchange_rate,
                'transaction_amount_in_usd' => $fundAmount,
                'rate' => $fundAmount,
                'currency' => 'USD',
            ]);

            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Card funding failed: ' . $e->getMessage(), 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Card funding failed: ' . $e->getMessage());
        }
    }

    public function freezeCard(Request $request, $id)
    {
        $virtualCard = VirtualCard::where('_id', $id)
            ->where('user_id', auth()->user()->id)
            ->first();

        if (!$virtualCard) {
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Virtual card not found.', 404);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Virtual card not found.');
        }

        $baseUrl = env('CARD_URL');
        $secretKey = env('CARD_API_SECRET');
        $updateType = $virtualCard->freeze_status == '1' ? 'unfreeze' : 'freeze';
        $newFreezeStatus = $virtualCard->freeze_status == '1' ? '0' : '1';

        $payload = [
            'vcardid' => $virtualCard->card_id,
            'updatetype' => $updateType,
        ];

        try {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => "$baseUrl/business/vcard-update",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    "Authorization: Bearer $secretKey",
                ],
            ]);

            $response = curl_exec($curl);
            if (curl_errno($curl)) {
                throw new \Exception(curl_error($curl));
            }
            curl_close($curl);

            $apiResponse = json_decode($response, true);

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $virtualCard->freeze_status = $newFreezeStatus;
                $virtualCard->save();

                return $this->respond($request, [], 'Operation successful', 'user.virtual-cards.mycards');
            } else {
                $statusReason = $apiResponse['message'] ?? 'Unknown error occurred';
                if ($this->expectsJson($request)) {
                    return $this->respondWithError($request, 'Operation failed: ' . $statusReason, 400);
                }
                return Redirect::route('user.virtual-cards.mycards')->with('error', 'Operation failed: ' . $statusReason);
            }
        } catch (\Exception $e) {
            \Log::error('Card freeze/unfreeze failed: ' . $e->getMessage());
            if ($this->expectsJson($request)) {
                return $this->respondWithError($request, 'Operation failed: ' . $e->getMessage(), 400);
            }
            return Redirect::route('user.virtual-cards.mycards')->with('error', 'Operation failed: ' . $e->getMessage());
        }
    }

    public function revealCard(Request $request, $id)
    {
        $virtualCard = VirtualCard::where('_id', $id)
            ->where('user_id', auth()->user()->id)
            ->first();

        if ($virtualCard) {
            $data = [
                'expiry_date' => $virtualCard->expiry_date,
                'card_number' => $virtualCard->card_number,
                'cvv' => $virtualCard->cvv
            ];
            return $this->respond($request, $data, 'Operation successful', 'user.virtual-cards.mycards');
        }

        if ($this->expectsJson($request)) {
            return $this->respondWithError($request, 'Unable to perform this operation, please try again later', 400);
        }
        return Redirect::route('user.virtual-cards.mycards')->with('error', 'Unable to perform this operation, please try again later');
    }
}