<?php

namespace App\Console\Commands;

use App\Enums\NikarayanComplaints;
use App\Services\NikarayanService;
use App\Services\NominatimService;
use Exception;
use Illuminate\Support\Facades\Log;
use SoapFault;
use SoapClient;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
use App\Models\RoadObserved;
use App\Models\EdarateShahri;
use App\Models\Province;
use App\Models\City;

class RoadObservationProblems extends Command
{
   /**
    * The name and signature of the console command.
    *
    * @var string
    */
   protected $signature = 'webservice:roadobserved';

   /**
    * The console command description.
    *
    * @var string
    */
   protected $description = 'get road observed problems from 141 (samaneh sawaneh)';

   /**
    * Create a new command instance.
    *
    * @return void
    */
   public function __construct()
   {
      parent::__construct();
   }

    /**
     * Execute the console command.
     *
     * @return int|string
     * @throws Exception
     */
   public function handle(NikarayanService $nikarayanService, NominatimService  $nominatimService)
   {
      //   try {
      //       $soap_client = new SoapClient($url);
      //       $result = $soap_client->Get_RoadObservedProblems_Current(array('strUserName' => 'vaytelrop', 'strPassword' => 'VaYtelROP*2024'));
      //   } catch (SoapFault $e) {
      //       echo $e->getMessage();
      //       $msg = 'rms: error in get road observation webservice babe!!!!'."\n";
      //       $msg .= $e->getMessage();
      //       // self::sms_sender('09398586633', $msg);
      //       // self::sms_sender('09367487107', $msg);
      //       return 0;
      //   }

     $result = $nikarayanService->getRoadObservedProblemsByDate();

      $result = serialize($result);
      $x = strpos($result, '<Document');
      $y = strpos($result, '</Document');
      $q = intval($y) - intval($x) + 18;
      if ($x !== false and $y !== false) {
         $final_data = substr($result, $x, $q);
         $xml = simplexml_load_string($final_data);

         $affectedRows = 0;
         $cities = [];
         foreach ($xml as $value) {
            //  if ($value->fk_FeatureType >= 1 && $value->fk_FeatureType <= 6) { //// code ghabli
            if (RoadObserved::where('fk_RegisteredEventMessage', $value->fk_RegisteredEventMessage)->exists()) {
               continue;
            }

            if ($value->fk_FeatureType >= 1 && $value->fk_FeatureType <= 18) {
               $mobile = null;

               if ($value->MobileForSendEventSms && (strlen($value->MobileForSendEventSms) == 11)) {
                  $mobile = $value->MobileForSendEventSms;
               }

               $city = findCityFromGeoJson($value->YGeo, $value->XGeo);
               $cityModel = $city ? City::find($city['city_id']) : null;
               $rop = RoadObserved::query()->updateOrCreate(
                  ['fk_RegisteredEventMessage' => $value->fk_RegisteredEventMessage],
                  [
                     'fk_RegisteredEventMessage' => $value->fk_RegisteredEventMessage ?? null,
                     'Title' => $value->Title ?? null,
                     'StartTime' => $value->StartTime ?? null,
                     'EndTime' => $value->EndTime ?? null,
                     'StartDate' => $value->StartDate ?? null,
                     'EndDate' => $value->EndDate ?? null,
                     'StartTime_DateTime' => $value->StartTime_DateTime ?? null,
                     'StartTime_DateTime_fa' => Verta::instance($value->StartTime_DateTime) ?? null,
                     'EndTime_DateTime' => $value->EndTime_DateTime ?? null,
                     'AutoID' => $value->AutoID ?? null,
                     'fk_Country' => $value->fk_Country ?? null,
                     'ProvinceName' => $value->ProvinceName ?? null,
                     'fk_Province' => $value->fk_Province ?? null,
                     'fk_Town' => $value->fk_Town ?? null,
                     'TownName' => $value->TownName ?? null,
                     'lng' => $value->XGeo ?? null,
                     'lat' => $value->YGeo ?? null,
                     'XLAM' => $value->XLAM ?? null,
                     'YLAM' => $value->YLAM ?? null,
                     'WeatherName' => $value->WeatherName ?? null,
                     'fk_Weather' => $value->fk_Weather ?? null,
                     'EventTypeTitle' => $value->EventTypeTitle ?? null,
                     'fk_EventType' => $value->fk_EventType ?? null,
                     'FeatureTypeTitle' => $value->FeatureTypeTitle ?? null,
                     'fk_FeatureType' => $value->fk_FeatureType ?? null,
                     'Description' => (strlen($value->Description) > 5) ? $value->Description : null,
                     'MobileForSendEventSms' => $mobile,
//                     'rms_province_id' => $rmsProvinceId[(int) $value->fk_Province] ?? null,
//                     'rms_city_id' => $rmsCityId[(int) $value->fk_Town]["InvarID"] ?? null,
//                     'observed_way_id' => self::get_way_id_from_nominatim($value->XGeo, $value->YGeo) ?? null,
                     'rms_province_id' => NikarayanComplaints::mapProvinces((int) $value->fk_Province) ?? null,
                     'rms_city_id' => NikarayanComplaints::mapCities((int) $value->fk_Town) ?? null,
                     'observed_way_id' => $nominatimService->get_way_id_from_nominatim($value->XGeo, $value->YGeo) ?? null,

                     'province_id' => $city ? $city['province_id'] : null,
                     'city_id' => $city ? $city['city_id'] : null,
                     // 'handler_type' => EdarateShahri::class,
                     'edarate_shahri_id' => $cityModel ? ($cityModel->edarateShahri()->where('is_primary', 1)->exists() ? $cityModel->edarateShahri()->where('is_primary', 1)->first()->id : null) : null,
                     'province_fa' => (isset($city['province_id']) ? Province::find($city['province_id'])->name_fa : null),
                     'city_fa' => $cityModel ? $cityModel->name_fa : null,
                  ]
               );
                $affectedRows += 1;
            }
         }
      }
      else {
          $this->info('the received body is empty');
          Log::channel('nikarayan')->error("the received body is empty" . date('Y-m-d H:i:s'));
          return $result;
      }
      echo 'done at: ' . date("Y-m-d H:i:s") . "\n";
      $this->info("{$affectedRows} row's affected");
      return 0;
   }
}
