<?php

namespace App\Classes\Modules\Billplzs\Services;

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;

class CreatesBillplzBill
{

    /**
     * @param string $name
     * @param string $email
     * @param string $description
     * @param float $amount
     * @param string $billNumber
     * @param null|string $bankCode
     * @param null|Boolean $wallet
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(string $name, string $email, string $description, float $amount, string $billNumber, ?string $bankCode = null, ?bool $wallet = null) {
        try{
//            config('billplz.maybank')
            $response = Http::withBasicAuth(config('billplz.api_key').':', '')->post(config('billplz.base_url').'/api/v3/bills', [
                'collection_id' => config('billplz.collection_id'),
                'name' => $name,
                'email' => $email,
                'description' => $description,
                'amount' => $this->finalizeAmount($amount),
                'redirect_url' => route('online_payment.redirect'),
                'callback_url' => route('api.online_payment.callback'),
                'reference_1_label' => 'Bank Code',
                'reference_1' => $bankCode ? $bankCode : '',
                'reference_2_label' => 'Bill Number',
                'reference_2' => $billNumber
            ]);

            if($response->successful()){
                $data = $response->json();

                $data['url'] = $data['url'].'?auto_submit=true';

                return (object) $data;
            }else{
                return null;
            }
        }catch(\Exception $exception){
            throw new MalformedRequestException('Unable to get correct response from billplz server' . $exception->getMessage());
        }
    }

    protected function finalizeAmount($amount){
        $number = round($amount, 2) * 100;
        return (string) $number;
    }
}