<?php

namespace App\Services\CMMS;

use Exception;
use Illuminate\Support\Facades\Log;
use SoapClient;

class GetMachinesInfoListService
{
    protected string $url;
    protected string $channelName;
    protected string $password;
    protected string $viewName;

    public function __construct()
    {
        $this->url = config('cmms_web_services.MACHINE_INFO.url');
        $this->password = config('cmms_web_services.MACHINE_INFO.password');
        $this->viewName = config('cmms_web_services.MACHINE_INFO.ViewName');
        $this->channelName = 'cmms_machines_info';
        ini_set('memory_limit', '512M');
    }

    /**
     * @throws Exception
     */
    public function run(): array
    {
        try {
            $xmlResponse = $this->sendRequest();

            return $this->xmlToArray($xmlResponse);
        }
        catch (Exception $e) {
            Log::channel($this->channelName)
                ->error(get_class($this),
                    [
                        'message' => $e->getMessage(),
                    ]
                );

            throw $e;
        }
    }

    public function sendRequest()
    {
        $client = new SoapClient($this->url);

        return $client->GetView([
            'ViewName' => $this->viewName,
            'Password' => $this->password,
        ])->GetViewResult;
    }

    public function xmlToArray($xmlString)
    {
        $xmlObject = simplexml_load_string($xmlString);
        $json = json_encode($xmlObject);
        return json_decode($json, true);
    }
}
