<?php

namespace App\Console\Commands\Data;

use App\Models\PropertyWeb;
use App\Models\PropertyWebWeather;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Exception;
use Illuminate\Support\Facades\Log;

class WeatherService extends Command
{

    protected $signature = 'cron:weather';

    protected $description = '';

    public function __construct(
        Client $restClient
    )
    {
        parent::__construct();

        $this->restClient = $restClient;
    }


    public function handle()
    {
        try {


            $date = date('Y-m-d');

            $this->info(date('Y-m-d H:i:s') . ' : ' . date('Y-m-d') . ' START');

            $baseUrl = 'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline';
            $apiKey = 'GQG8FVH2C7ZZYZXS6PECE2QFX';

            $this->restClient = new Client(['http_errors' => false]);

            $propertyWeb = PropertyWeb::where('status', 1)
                ->where('weather_active', 1)->with('property.propertyContact')
                //->where('property_id',1231)//TODO:Del
                ->get()->toArray();

            foreach ($propertyWeb as $property) {


                $propertyWebWeatherId = null;
                $propertyWebWeather = PropertyWebWeather::where('property_id', $property['property']['id'])->first();
                if ($propertyWebWeather) {
                    $propertyWebWeatherId = $propertyWebWeather['id'];
                }


                $latitude = $property['property']['property_contact']['latitude'];
                $longitude = $property['property']['property_contact']['longitude'];
                if (!empty($latitude) && !empty($longitude)) {

                    $requestUrl = $baseUrl . '/' . $latitude . ',' . $longitude . '/' . $date . '?key=' . $apiKey . '&include=days&unitGroup=metric&elements=tempmax,tempmin,temp,conditions,icon';

                    $requestWeather = $this->restClient->request('GET', $requestUrl);

                    $getResponseBody = $requestWeather->getBody();
                    $getResponse = $getResponseBody ? json_decode($getResponseBody, 1) : [];

                    $propertyWebWeatherParam = [
                        'property_id' => $property['property']['id'],
                        'date' => $date,
                        'temp' => $getResponse['days'][0]['tempmax'],
                        'conditions' => $getResponse['days'][0]['conditions'],
                        'icon' => $getResponse['days'][0]['icon'],
                        'response' => json_encode($getResponse),
                        'created_by' => 1,
                        'updated_by' => 1,
                    ];

                    if (empty($propertyWebWeatherId)) {

                        $locationUrl = 'https://geocode.maps.co/reverse?lat=' . $latitude . '&lon=' . $longitude . '&api_key=6683d9ee52e5d111344805khdf0451c';
                        $requestLocation = $this->restClient->request('GET', $locationUrl);

                        $getResponseBodyLocation = $requestLocation->getBody();
                        $getResponseLocation = $getResponseBodyLocation ? json_decode($getResponseBodyLocation, 1) : [];


                        if ($getResponseLocation) {

                            $location = null;
                            if(isset($getResponseLocation['address']['province'])) {
                                $location = $getResponseLocation['address']['province'];
                            }elseif(isset($getResponseLocation['address']['town'])) {
                                $location = $getResponseLocation['address']['town'];
                            }elseif(isset($getResponseLocation['address']['city'])) {
                                $location = $getResponseLocation['address']['city'];
                            }

                            $propertyWebWeatherParam['location'] = $location;
                            $propertyWebWeatherParam['address'] = json_encode($getResponseLocation);
                        }

                        PropertyWebWeather::create($propertyWebWeatherParam);
                        $this->info(date('Y-m-d H:i:s') . ' : ' . $propertyWebWeatherParam['property_id'] . ' - ' . $propertyWebWeatherParam['date'] . ' : ' . $propertyWebWeatherParam['conditions']. ' : ' . $propertyWebWeatherParam['temp']);

                    } else {

                        PropertyWebWeather::where('id', $propertyWebWeatherId)->update($propertyWebWeatherParam);
                        $this->line(date('Y-m-d H:i:s') . ' : ' . $propertyWebWeatherParam['property_id'] . ' - ' . $propertyWebWeatherParam['date'] . ' : ' . $propertyWebWeatherParam['conditions']. ' : ' . $propertyWebWeatherParam['temp']);
                    }


                }

            }


            $this->info(date('Y-m-d H:i:s') . ' : ' . date('Y-m-d') . ' FINISHED');

        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $this->error(date('Y-m-d H:i:s') . ' : ' . date('Y-m-d') . ' ERROR: ' . $message);
        }

    }

}
