<?php

namespace App\Modules\CardBalance\Repositories;

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

class CardBalanceRepository
{
    use Makeable;

    /**
     * Show card balance
     */
    public function showCardBalance(Card $record): View
    {
        /** @var \App\Modules\CardBalance\Types\CardBalanceResponse */
        $data = $this->fetchCardBalance(
            passport_serie: user()->passport_serie(),
            passport_id: user()->passport_id(),
            card_masked: Str::mask($record->number, '*', 6, 6),
            card_expire_date: $record->month.'/'.substr($record->year, 2),
        );

        return $data->errCode != 0
            ? view('module.card-balance::error-response', compact('data'))
            : view('module.card-balance::card-balance-modal', compact('data'));
    }

    /**
     * Fetch card balance
     *
     * @param  string|int  $passport_serie
     * @param  string|int  $passport_id
     * @param  string  $card_masked
     * @param  string  $card_expire_date
     */
    public function fetchCardBalance($passport_serie, $passport_id, $card_masked, $card_expire_date): object
    {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => 'http://10.3.158.102:9999/api/clientcardinfo',
            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",
            "cardMaskNumber": "%s",
            "expDate": "%s"
        }', $passport_serie, $passport_id, $card_masked, $card_expire_date),
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic dGJ1c2VyOlFBWndzeDEyMw==',
                'Content-Type: 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;
    }
}
