<?php

namespace App\Modules\Loan\Repositories;

use App\Modules\Loan\Models\Loan;
use App\Modules\Makeable;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Str;

class LoanRepository
{
    use Makeable;

    /**
     * Show remaining loan
     */
    public function showRemainingLoan(Loan $record): View
    {
        $data = $this->fetchCardBalance(
            passport_serie: user()->passport_serie(),
            passport_id: user()->passport_id(),
            account_number: $record->account_number,
        );

        return view('module.loan::loan-remaining', compact('data'));
    }

    /**
     * Fetch card card balance from abs
     */
    public function fetchCardBalance(string $passport_serie, int|string $passport_id, int|string $account_number): object
    {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => 'http://10.3.158.102:9999/api/loaninfo',
            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 => sprintf('
            {
                "idSeria": "%s",
                "idNo": "%s",
                "accountCode": "%s"
            }
            ',
                $passport_serie,
                $passport_id,
                $account_number,
            ),
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic dGJ1c2VyOlFBWndzeDEyMw==',
                'Content-Type: application/json',
                'Accept: application/json',
            ],
        ]);

        $response = curl_exec($curl);

        curl_close($curl);

        /** @var object */
        $safeResponse = Str::isJson($response)
            ? json_decode($response)
            : emptyClass(errCode: 1, message: 'Connection issue to VP');

        return $safeResponse;
    }
}
