<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("../main_includes/init.php");

// Get user details from the database
$user_id = isset($user_id) ? $user_id : $_SESSION['user_id'];
$user = User::find_by_id($user_id);

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

// Access Token Integration
$authorizationEndpoint = "https://sandbox.monnify.com/api/v1/auth/login";

$clientID = "MK_TEST_AX217LDR8E";
$clientSecret ="FKQEEF5WPUZZ4C4VNSVXJSL6B7NNEQ2Z";

 $headers = array(
    "Content-Type: application/json",
    "Authorization: Basic " . base64_encode($clientID . ":" . $clientSecret)
);

$ch = curl_init($authorizationEndpoint);
 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

$responseData = json_decode($response);
$access_token = $responseData->responseBody->accessToken;

// Check if the user is found in the database
if ($user) {
    // RESERVED ACCOUNT INTEGRATION
    $apiUrl = 'https://sandbox.monnify.com/api/v1/bank-transfer/reserved-accounts';

    // Request data including the user's name
    $requestData = array(
        "accountReference" => "MAGADATA". $user->id,
        "accountName" => $user->first_name, 
        "currencyCode" => "NGN",
        "contractCode" => "5689677693",
        "customerEmail" => $user->email,
        // "customerEmail" => "alawee7@gmail.com",
        "bvn" => $user->bvn,
        "customerName" => $user->first_name . "" . $user->first_name,
        "getAllAvailableBanks" => true,
        // "preferredBankCodes" => ["035","232","50515"] 
    );

    $requestPayload = json_encode($requestData);

    // Set up cURL
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $requestPayload,
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Authorization: Bearer $access_token"
        ),
    ));

    // Execute cURL request
    $response = curl_exec($curl);
    $err = curl_error($curl);

    // Close cURL
    curl_close($curl);

    // Handle cURL errors
    if ($err) {
        echo "cURL Error: $err";
    } else {
        // Output response
        echo $response;
        $responseData = json_decode($response);

        if ($responseData->requestSuccessful) {
            if(!$account){
                // Create a new Account instance
                $new_account = new Account;
                $new_account->user_id = $user->id; 
                // $new_account->user_id = "222";
                $new_account->trackingReference = $responseData->responseBody->accountReference;
                $new_account->accountName = $responseData->responseBody->accountName;
                $new_account->account_detail = json_encode($responseData);
                
                // Save the new account to the database
                $new_account->save();
        
                // echo "Record inserted successfully";
            } else {
                echo "user already have an account";
            }
            
        
    } else {
        echo "API request was not successful";
        }
    }

    // Insert user's name into the session 
    // $_SESSION['user_name'] = $user->name;
} else {
    echo "User not found in the database.";
}

include 'webhook_handler.php';

    $accounts_detail = isset($account) && !empty($account) ? json_decode($account->account_detail)->responseBody : array();
    
    $accounts = empty($accounts_detail) ? array() : $accounts_detail->accounts;
    
    