<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Gateway\PaymentController;
use App\Models\CryptPayment;
use App\Models\Deposit;
use App\Models\GatewayCurrency;
use App\Models\Transaction;
use App\Models\Wallet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WalletController extends Controller
{

    function fl_callback(Request $request)
    {
        $payload = $request->all();
        // It's a good idea to log all received events.
        //Log::info($payload);


        // Do something (that doesn't take too long) with the payload


        // Retrieve the request's body
        $body = @file_get_contents("php://input");

// retrieve the signature sent in the reques header's.
        $signature = (isset($_SERVER['verif-hash']) ? $_SERVER['verif-hash'] : '');

        /* It is a good idea to log all events received. Add code *
         * here to log the signature and body to db or file       */

        if (!$signature) {
            // only a post with rave signature header gets our attention
            //exit();
        }

// Store the same signature on your server as an env variable and check against what was sent in the headers
        $local_signature = getenv('SECRET_HASH');

// confirm the event's signature
        if ($signature !== $local_signature) {
            // silently forget this ever happened
            //    exit();
        }

        http_response_code(200); // PHP 5.4 or greater
// parse event (which is json string) as object
// Give value to your customer but don't give any output
// Remember that this is a call from rave's servers and
// Your customer is not seeing the response here at all

        $event = json_decode($body);

        switch ($event->event) {
            case 'charge.completed':

                $datas = $event->data;
                $ref = $event->data->tx_ref;

                //find deposit

                $track = $ref;
                Log::info($track);
                $deposit = Deposit::where('trx', $track)
                    ->where('status', 0)
                    ->first();

                //Log::info($deposit->status);

                if (!$deposit) {
                    //abort(404);
                    return;
                }


                /*$result = array();
                //The parameter after verify/ is the transaction reference to be verified
                //https://api.budpay.com/api/v2/transaction/verify/$reference
                $url = 'https://api.budpay.com/v2/transaction/verify/' . $track;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $secret_key]);
                $response = curl_exec($ch);
                curl_close($ch);*/


                $am = $event->data->amount;// / 100;
                $sam = $deposit->final_amo;

                //Log::info($am);
                //Log::info($sam);

                if ($am >= $sam && $deposit->status == 0) {
                    PaymentController::userDataUpdate($deposit);
                }


                break;

            default:
                break;
        }


        exit();

        return response(200);
    }

    function budWebhook()
    {
        //


        $body = @file_get_contents("php://input");
        $signature = (isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] : '');


        if (!$signature) {
            //// only a post with paystack signature header gets our attention
            //$dump['no_signature'] = true;
            //exit();
        }

        // confirm the event's signature
        if ($signature !== hash_hmac('sha512', $body, env('PAYSTACK_SECRET_KEY'))) {
            // silently forget this ever happened
            //$dump['signature_not_auth'] = true;
            //exit();
        }

        http_response_code(200);


        Log::info($body);
        $event = json_decode($body);

        switch ($event->notifyType) {
            // charge.success
            case 'successful':
                $ref = $event->data->reference;

                $track = $ref;
                $deposit = Deposit::where('trx', $track)
                    ->where('status', 0)
                    ->first();

                //Log::info($deposit->status);

                if (!$deposit) {
                    //abort(404);
                    return;
                }

                $secret_key = config('settings')->bud_pay_key;

                /*$result = array();
                //The parameter after verify/ is the transaction reference to be verified
                //https://api.budpay.com/api/v2/transaction/verify/$reference
                $url = 'https://api.budpay.com/v2/transaction/verify/' . $track;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $secret_key]);
                $response = curl_exec($ch);
                curl_close($ch);*/


                $am = $event->data->amount;// / 100;
                $sam = $deposit->final_amo;

                if ($am >= $sam && $deposit->status == 0) {
                    PaymentController::userDataUpdate($deposit);
                }
                break;
            default:
                break;


        }


        exit();

    }

    function bud_payment_callback(Request $request)
    {
        $reference = $track = $ref = $request->reference;

        //dd($reference);

        //find deposit with the reference

        $deposit = Deposit::where('trx', $reference)
            ->where('status', 0)
            ->first();


        if (!$deposit) {
            abort(404);
        }

        return redirect()->route('user.deposit.history');


        $secret_key = env("BUD_SECRETE_KEY");

        $result = array();
        //The parameter after verify/ is the transaction reference to be verified
        //https://api.budpay.com/api/v2/transaction/verify/$reference
        $url = 'https://api.budpay.com/v2/transaction/verify/' . $track;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $secret_key]);
        $response = curl_exec($ch);
        curl_close($ch);

        if ($response) {
            $result = json_decode($response, true);

            if ($result) {
                if ($result['data']) {

                    //$deposit_data->server_dump
                    $deposit->server_dump = $response;
                    $deposit->save();

                    if ($result['data']['status'] == 'success') {

                        $am = $result['data']['amount'];// / 100;
                        $sam = $deposit->final_amo;

                        if ($am >= $sam && $deposit->status == 0) {
                            PaymentController::userDataUpdate($deposit);
                        }
                    }
                }
            }
        }

        return redirect()->route('user.deposit.history');
    }
	
    function payment_callback(Request $request){

        $body = @file_get_contents("php://input");
        $signature = (isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ? $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] : '');


        $wallet = $request->address_in;

        if($wallet == ""){
            return;
        }

        Log::debug($wallet);

        //check wallet owner

        $check_wallet = Wallet::where("wallet_address", $wallet)->with('user')->first();

        if(!$check_wallet){
            return;
        }

        $payment_ref = $request->uuid;

        //check existing payment with same ID

        $exisitng_pay = CryptPayment::where("uuid", $payment_ref)->first();

        if($exisitng_pay){
            Log::debug($payment_ref);
            return;
        }

        //update user's balance

        $gate = GatewayCurrency::find(2);
        $rate = $gate->rate;

        $credited = $request->value_coin * 750 ;/// $rate;// - 1; //$request->value_forwarded_coin;// (98.5/100) * $request->value_coin;// // $request->value_forwarded_coin;
        $check_wallet->user->balance += $credited;
        $check_wallet->user->save();


        $payment = new CryptPayment();
        $payment->user_id = $check_wallet->user_id;
        $payment->wallet_address = $wallet;
        $payment->uuid = $payment_ref;
        $payment->address_out = $request->address_out;
        $payment->value_coin = $request->value_coin;
        $payment->value_forwarded_coin = $request->value_forwarded_coin;
        $payment->coin = $request->coin;
        $payment->response_log = json_encode($request);
        $payment->save();

        $transaction = new Transaction();
        $transaction->user_id = $check_wallet->user_id;
        $transaction->amount = getAmount($credited);
        $transaction->post_balance = getAmount($check_wallet->user->balance);
        $transaction->charge = 0;// getAmount($request->value_coin - $credited);
        $transaction->trx_type = '+';
        $transaction->details = 'Deposit using usdt Wallet';
        $transaction->trx =  getTrx();
        $transaction->save();

        //create demo deposit and notify user



        $data = new Deposit();
        $data->user_id = $check_wallet->user_id;
        $data->method_code = $gate->method_code;
        $data->method_currency = strtoupper($gate->currency);
        $data->amount = (750 * $request->value_coin);// - $transaction->charge;
        $data->charge = $transaction->charge;
        $data->rate = $rate;
        $data->final_amo = getAmount($credited);
        $data->btc_amo = 0;
        $data->btc_wallet = "";
        $data->trx = getTrx();
        $data->try = 0;
        $data->status = 1;
        $data->save();


        notify($check_wallet->user, 'DEPOSIT_APPROVE', [
            'method_name' => $data->gatewayCurrency()->name, //$deposit->gatewayCurrency()->name
            'method_currency' => $data->method_currency,
            'method_amount' => getAmount($data->final_amo),
            'amount' => getAmount($data->amount),
            'charge' => getAmount($data->charge),
            'currency' => config('settings')->cur_text,
            'rate' => getAmount($data->rate),
            'trx' => $data->trx,
            'post_balance' => $check_wallet->user->balance
        ]);

        $msg = "Congratulations ".$check_wallet->user->username.", your deposit of $request->value_coin USDT has been confirmed";
        send_to_telegram($msg);

        return "*ok*";
    }

}
