<?php
namespace App\Http\Services;


use App\Models\BankWithdrawal;
use App\Models\FundTransfer;
use App\Models\GeneralSetting;
use App\Models\Withdrawal;

/**
 * Laravel/Symfony Developer
 * Name: Muongozo
 * Telegram: @muongozotrader
 * Hire me via Telegram: muongozotrader
 */
class TransferServices
{
    private $setting;
    public function __construct()
    {
        $this->setting = GeneralSetting::first();
    }

    function initiate_transfer($id){
        try {

            $withdrawal = Withdrawal::find($id);

            // Transaction not found
            if(!$withdrawal) throw new \Exception("Sorry transaction id not found");

            $amount = $withdrawal->final_amount;

            // Find Client Bank Account
            $bank_withdrawal = BankWithdrawal::where('withdrawal_id', $withdrawal->id)->first();

            if(!$bank_withdrawal) throw new \Exception("Bank account not found");

            $ref = getTrx();

            // Send Request for Transfer
            $transfer = $this->make_payment($bank_withdrawal->bank_code, $bank_withdrawal->account_number,$amount,"NGN");

            // Exception
            if($transfer instanceof \Exception) throw new \Exception($transfer->getMessage());

            // Successful Transfer
            $payment = new FundTransfer();
            $payment->name = $bank_withdrawal->account_name;
            $payment->description = $this->setting->sitename;
            $payment->account_number = $bank_withdrawal->account_number;
            $payment->bank_code = $bank_withdrawal->bank_code;
            $payment->amount = $amount;
            $payment->withdrawal_id = $id;
            $payment->response = json_encode($transfer);
            $payment->reference = $transfer['data']['reference'];
            $payment->save();
            $withdrawal->status = 1;
            $withdrawal->save();

            // Response
            return array('status' => true, 'message' => 'Withdraw Procced successful');
        } catch (\Exception $th) {
            //throw $th;
            return array('status' => false, 'message' => $th->getMessage());
        }
    }

    function make_payment($account_bank, $account_number, $amount, $currency){

        try {

            // Validate Account
            $validateAccount = $this->validateAccount($account_bank, $account_number);

            // Exception
            if($validateAccount instanceof \Exception) throw new \Exception($validateAccount->getMessage());

            // Request Body
            $postBody = json_encode([
                'amount' => $amount,
                'validation_reference' => $validateAccount['data']['reference']
            ]);

            // Curl Request
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://xxxx.net/api/v2/fund-transfer/process',
            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 => $postBody,
            CURLOPT_HTTPHEADER => array(
                'Authorization: '.$this->setting->kyyy,
                'Content-Type: application/json'
            ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            // there was an error contacting
            if ($err) throw new \Exception('Curl returned error: ' . $err);

            // Convert Json to Json Array
            $response_array = json_decode($response,true);

            // Check status
            if(!in_array($httpcode, ['200'])) throw new \Exception($response_array['message']);

            //create a payment log

            return $response_array;

        } catch (\Exception $th) {
            //throw $th;
            return $th;
        }
    }

    function validateAccount($account_bank, $account_number){

        try {

            // Request Body
            $postBody = json_encode([
                "bank_code" => $account_bank,
                'bank_country' => "Nigeria",
                'account_number' => $account_number
            ]);

            // Curl Request
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://xxxx.net/api/v2/funds/validate-bank-account',
            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 => $postBody,
            CURLOPT_HTTPHEADER => array(
                'Authorization: '.$this->setting->kyyy,
                'Content-Type: application/json'
            ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            // there was an error contacting
            if ($err) throw new \Exception('Curl returned error: ' . $err);

            // Convert Json to Json Array
            $response_array = json_decode($response,true);
            // Check status
            if(!in_array($httpcode, ['200'])) throw new \Exception($response_array['message']);

            // Response
            return $response_array;

        } catch (\Exception $th) {
            //throw $th;
            return $th;
        }
    }

}
