<?php

namespace App\Http\Controllers\Gateway;

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

class FlutterwaveController extends Controller
{

    /**
     * Receives Flutterwave webhook
     * @return void
     */
    public function webhook(Request $request)
    {
        Log::info($request);
        //This verifies the webhook is sent from Flutterwave
        $verified = Flutterwave::verifyWebhook();
       Log::info($request);
        // if it is a charge event, verify and confirm it is a successful transaction
        if ($verified && $request->event == 'charge.completed') {
            if($request['event.type']=="BANK_TRANSFER_TRANSACTION") {
                $data = $request->data;
                $deposit = Deposit::where('txn_id', $data['flw_ref'])->first();
                if (!$deposit) {
                    $wallet = Wallet::where('flw_ref', $data['tx_ref'])->first();
                    $deposit = new Deposit();
                    $deposit->user_id = $wallet->user_id;
                    $deposit->user_info = $data['narration'];
                    $deposit->status = $data['status'];
                    $deposit->txn_id = $data['flw_ref'];
                    $deposit->amount = $data['charged_amount'];
                    $deposit->method = 'Account';
                    $deposit->currency_id = 'NGN';
                    $deposit->charge = $data['app_fee'];
                    $deposit->flw_id = $data['id'];
                    $deposit->flw_ref = $data['flw_ref'];
                    $deposit->flw_tx_ref = $data['tx_ref'];
                    $deposit->save();

                    $wallet->balance = $wallet->balance + $data['charged_amount'];
                    $wallet->save();

                    TransactionHistory::create([
                        'descriptions' => 'Deposit of ' . $data['charged_amount'] . ' to your wallet',
                        'trade_id' => null,
                        'request_id' => $data['tx_ref'],
                        'tradedcard_details_id' => null,
                        'transaction_ref' => $data['tx_ref'],
                        'user_id' => $wallet->user_id,
                        'amount' => $data['charged_amount'],
                        'exchange_rate' => 1,
                        'transaction_amount_in_usd' => 1,
                        'transaction_type' => 'Credit',
                        'created_by' => auth()->user()->id,
                        'source' => 'Deposit',
                        'status' => 'success',
                        'status_at' => now(),
                        'status_by' => auth()->user()->id,
                        'status_reason' => $data['narration'],

                        'rate' => null,
                        'currency' => "NGN",
                    ]);

                    //send notifications
                }
            }


        }
//Log::info('flutterwwqave webhoot');

        // if it is a transfer event, verify and confirm it is a successful transfer
        if ($verified && $request->event == 'transfer.completed') {

            $transfer = Flutterwave::transfers()->fetch($request->data['id']);
$data = $transfer['data'];
            Log::info($transfer);
            $withdraw = Withdrawals::where('flw_transfer_id', $data['id'])->first();
            $transaction = Transaction::where('transaction_ref', $withdraw->trx)->first();
            if($transfer['data']['status'] === 'SUCCESSFUL') {
                $withdraw->flw_transfer_status = $data['status'];
                $withdraw->flw_complete_message = $data['complete_message'];
                $withdraw->flw_is_approved = $data['is_approved'];
                $withdraw->status =1;
                if($transaction) {
                    $transaction->status = 'success';
                    $transaction->status_reason = $withdraw->flw_complete_message;
                }
                // update transfer status to successful in your db

            } else if ($transfer['data']['status'] === 'FAILED') {
                // update transfer status to failed in your db
                $withdraw->flw_transfer_status = $data['status'];
                $withdraw->flw_complete_message = $data['complete_message'];
                $withdraw->flw_is_approved = $data['is_approved'];
                $withdraw->status =2;
                if($transaction) {
                    $transaction->status = 'failed';
                    $transaction->status_reason = $withdraw->flw_complete_message;
                }
                // revert customer balance back
            } else if ($transfer['data']['status'] === 'PENDING') {
                // update transfer status to pending in your db
                $withdraw->flw_transfer_status = $data['status'];
                $withdraw->flw_complete_message = $data['complete_message'];
                $withdraw->flw_is_approved = $data['is_approved'];

            }
            if($transaction) {
                $transaction->save();
            }
            $withdraw->save();

        }
    }

}
