<?php

namespace App\Classes\Modules\Accounting\Processors;

use App\Classes\Exceptions\MalformedRequestException;
use App\Models\Transaction;
use Illuminate\Support\Facades\Log;

class ChecksBillNumber
{
    public function execute($bill_no, $system_reference)
    {
        if ($system_reference == 'izyim') {
            try {
                $url = 'https://izyim.cief-malaysia.com/public/api/v1/transactions/mappable/query';
                $client = new \GuzzleHttp\Client(['verify' => false]);
                $response = $client->request('GET', $url . '?api-key=510acd13d8d24375cf038ad626c282565451461a9c2399357e0b65365300787e&filters={"bill_no":"' . $bill_no . '"}');
                $body = $response->getBody();
                $data = json_decode($body, true);
                $payload = $data['payload'];
                return $payload['data'];
            } catch (\Exception $exception) {
                throw new MalformedRequestException($exception->getMessage());
            }
        }

        if ($system_reference == 'exchange') {
            $transaction = Transaction::where('bill_no', $bill_no)->first();
            if ($transaction) {
                return $transaction;
            }
        }

        // if not found
        throw new MalformedRequestException('Bill Number Not Found.');
    }
}
