<?php

namespace App\Services;

use App\Models\RoadObserved;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use SoapClient;
use SoapFault;

class NikarayanService
{
    /**
     * @throws SoapFault
     */
    public function updateRoadObservedInfoByNikarayan(Request $request, RoadObserved $roadObserved, $files)
    {
        if (App::isProduction())
        {
            try {
                $url = "https://riws.rmto.ir/WebServices/NRPTrafficStatus.asmx?wsdl";

                $array = array('strUserName' => 'vaytelrop',
                    'strPassword' => 'VaYtelROP*2024',
                    'strAutoID' => $roadObserved->fk_RegisteredEventMessage,
                    'strStateID' => ($request->input('rms-status') == 1) ? '2' : '3',
                    'strDescription' =>  $request->input('rms-description') ?? $roadObserved->rms_description,
                    'strPreviousImageLink' => !empty($files) && isset($files[0]['path']) ? "https://rms.rmto.ir/" . $files[0]['path'] : "",
                    'strNextImageLink' => !empty($files) && isset($files[1]['path']) ? "https://rms.rmto.ir/" . $files[1]['path'] : "",
                    'strRMSDateAndTime' => $roadObserved->updated_at
                );

                $soapClient = new SoapClient($url);
                $result = $soapClient->UpdateInfo_RoadObservedProblems($array);
                Log::channel('nikarayan')->info([json_encode($result), $roadObserved->fk_RegisteredEventMessage]);

                return $result;
            }
            catch (\Exception $e) {
                Log::channel('nikarayan')->error($e->getMessage());
                throw $e;
            }
        }

        return 0;
    }

    /**
     * @throws SoapFault
     */
    public function getRoadObservedProblemsByDate($time)
    {
        try {
            $url = "https://riws.rmto.ir/WebServices/NRPTrafficStatus.asmx?wsdl";

            $month = $time->month < 10 ? '0' . $time->month : $time->month;
            $day = $time->day < 10 ? '0' . $time->day : $time->day;
            $date = $time->year . $month . $day;

            $soap_client = new SoapClient($url);
            return $soap_client->Get_RoadObservedProblems_ByDate(array(
                'strUserName' => 'vaytelrop',
                'strPassword' => 'VaYtelROP*2024',
                'strStartDate' => $date,
                'strEndDate' => $date
            ));
        }
        catch (\Exception $e) {
            Log::channel('nikarayan')->error($e->getMessage());
            throw $e;
        }
    }
}
