<?php
$account = Account::find_by_query("SELECT * FROM account WHERE user_id = $user->id LIMIT 1");
// print_r($account);
$account = array_shift($account);


// $RequestRef = rand(0000000000000, 9999999999999);
// $trackingReference = rand(00000000000, 99999999999);
 
function create_account($accessToken, $user)
{
    try {

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://sandbox.monnify.com/api/v2/bank-transfer/reserved-accounts',
            // CURLOPT_URL => 'https://sandbox.monnify.com/api/v2/bank-transfer/reserved-accounts',
            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 => '{
                "accountReference": "MAGA' . $user->id . '",
                "accountName": "' . $user->first_name . '",
                "currencyCode": "NGN",
                "contractCode": "5689677693",
                "customerEmail": "' . $user->email . '",
                "customerName": "' . $user->first_name . " " . $user->last_name . '",
                
                "getAllAvailableBanks": false,
                "preferredBanks": ["035","232","50515"]
               
            }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json',
                'Authorization: Bearer ' . $accessToken
            ),
        ));

        $response2 = json_decode(curl_exec($curl));

        curl_close($curl);

        // $response2 = '{
        //         "requestSuccessful": true,
        //         "responseMessage": "success",
        //         "responseCode": "0",
        //         "responseBody": {
        //             "contractCode": "222001311614",
        //             "accountReference": "abc1234",
        //             "accountName": "Tes",
        //             "currencyCode": "NGN",
        //             "customerEmail": "test@tester.com",
        //             "customerName": "John Doe",
        //             "accounts": [
        //                 {
        //                     "bankCode": "232",
        //                     "bankName": "Sterling bank",
        //                     "accountNumber": "8952095784",
        //                     "accountName": "Tes"
        //                 },
        //                 {
        //                     "bankCode": "035",
        //                     "bankName": "Wema bank",
        //                     "accountNumber": "7206930470",
        //                     "accountName": "Tes"
        //                 },
        //                 {
        //                     "bankCode": "50515",
        //                     "bankName": "Moniepoint Microfinance Bank",
        //                     "accountNumber": "6254727989",
        //                     "accountName": "Tes"
        //                 },
        //                 {
        //                     "bankCode": "058",
        //                     "bankName": "GTBank",
        //                     "accountNumber": "0784829227",
        //                     "accountName": "Tes"
        //                 }
        //             ],
        //             "collectionChannel": "RESERVED_ACCOUNT",
        //             "reservationReference": "NWA7DMJ0W2UDK1KN5SLF",
        //             "reservedAccountType": "GENERAL",
        //             "status": "ACTIVE",
        //             "createdOn": "2023-04-14 12:04:39.034",
        //             "incomeSplitConfig": [],
        //             "bvn": "21212121212",
        //             "restrictPaymentSource": false
        //         }
        // }';


        // $response2 = json_decode($response2);


        return $response2;
    } catch (\Throwable $th) {
 
        return ($th);
    }
}

$api_settings = Settings::find_by_id(1);

if (!$account) {

    $response = create_account($api_settings->access_key, $user);
    // print_r($response);
    if (isset($response->requestSuccessful) && $response->requestSuccessful) {

        $account = new Account;
        $account->user_id = $user->id;
        $account->trackingReference = $response->responseBody->accountReference;
        $account->accountName = $response->responseBody->accountName;
        $account->account_detail = json_encode($response);
        $account->save();
    } else {
        $apiKey = 'MK_TEST_AX217LDR8E';
        $secretKey = 'FKQEEF5WPUZZ4C4VNSVXJSL6B7NNEQ2Z';
        // $apiKey = 'MK_TEST_M9U740DC6G';
        // $secretKey = '126GWE2UJLQ9E84E71W95YEGLCMGQB9D';

        try {

            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://sandbox.monnify.com/api/v1/auth/login',
                // CURLOPT_URL => 'https://sandbox.monnify.com/api/v1/auth/login',
                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_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Authorization: Basic ' . base64_encode("$apiKey:$secretKey")
                ),
            ));

            $response3 = curl_exec($curl);

            curl_close($curl);
            // echo "<pre>";
            // print_r(json_decode($response3));
            // echo "</pre>";
            $response3 = json_decode($response3);

            if (isset($response3->requestSuccessful) && $response3->requestSuccessful == 1) {
                $accessToken = $response3->responseBody->accessToken;

                $new_api_settings = Settings::find_by_id(1);
                $new_api_settings->access_key = $accessToken; 

                $new_api_settings->save();

                $response =  create_account($accessToken, $user);
                print_r($response);
                if ($response->requestSuccessful) {

                    $new_account = new Account;
                    $new_account->user_id = $user->id;
                    $new_account->trackingReference = $response->responseBody->accountReference;
                    $new_account->accountName = $response->responseBody->accountName;
                    $new_account->account_detail = json_encode($response);
                    $new_account->save();
                }
            }
        } catch (\Throwable $th) {
            print_r($th);
        }
    }
} else {
    // print_r($account);
}
$accounts_detail = isset($account) && !empty($account) ? json_decode($account->account_detail)->responseBody : array();

$accounts = empty($accounts_detail) ? array() : $accounts_detail->accounts;