<?php

namespace App\Console\Commands\Google;

use App\Models\PropertyWeb;
use App\Models\PropertyWebComponentMapping;
use App\Models\PropertyWebReview;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Exception;
use Illuminate\Support\Facades\Log;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

class GoogleReview extends Command
{

    protected $signature = 'cron:google-review {--property_id=}';

    protected $description = '';

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

        $this->restClient = $restClient;
    }

    public function handle()
    {
        try {

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

            $baseUrl = 'https://maps.googleapis.com/maps/api/place/details/json';
            $apiKey = 'AIzaSyAPsKZ_XasAieKEhbmpOLUpArY2u2UcXuk';
            $availableRating = [4,5];

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


            if (!is_null($this->option('property_id'))) {
                $propertyWebComponentMapping = PropertyWebComponentMapping::where('status', 1)->where('component_id', 3)->where('property_id', $this->option('property_id'))->get()->toArray();
            } else {
                $propertyWebComponentMapping = PropertyWebComponentMapping::where('status', 1)->where('component_id', 3)->get()->toArray();
            }

            foreach ($propertyWebComponentMapping as $propertyWebComponent) {

                if (!isset($propertyWebComponent['parameterArray']['placeId'])) {
                    continue;
                }

                $googlePlaceId = trim($propertyWebComponent['parameterArray']['placeId']);

                Log::debug('google-review: '.$googlePlaceId);


                $params = [
                    'query' => [
                        'place_id' => $googlePlaceId,
                        'key' => $apiKey,
                        'fields' => 'name,rating,reviews',
                        'reviews_sort' => 'newest',
                        'reviews_no_translations' => true,
                        //'language' => 'tr'
                    ]
                ];

                $requestReview = $this->restClient->request('GET', $baseUrl, $params);

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

                $reviews = [];
                if(isset($getResponse['result']['reviews'])) {
                    $reviews = collect($getResponse['result']['reviews'])->sortBy('time')->toArray();
                }

                foreach ($reviews as $review) {

                    if(!in_array(fillOnUndefined($review, 'rating'),$availableRating)) {
                        continue;
                    }

                    try {

                        $code = md5($propertyWebComponent['property_id'].'-'.$review['author_name'] . '-' . $review['time']);

                        $propertyWebReviewCheck = PropertyWebReview::where('code', $code)->first();
                        if ($propertyWebReviewCheck) {
                            $this->error(date('Y-m-d H:i:s') . ' : ' . $propertyWebComponent['property_id'] . ' - ' . $review['author_name'] . ' : ' . $review['rating']);
                            continue;
                        }

                        $propertyWebWeatherParam = [
                            'property_id' => $propertyWebComponent['property_id'],
                            'channel' => 'google',
                            'code' => $code,
                            'language_code' => fillOnUndefined($review, 'language') ? substr($review['language'],0,2) : null,
                            'author' => $review['author_name'],
                            'profile_photo' => fillOnUndefined($review, 'profile_photo_url'),
                            'rating' => fillOnUndefined($review, 'rating'),
                            'review' => fillOnUndefined($review, 'text'),
                            'time' => fillOnUndefined($review, 'time'),
                            'status' => 1,
                            'created_by' => 1,
                            'updated_by' => 1,
                        ];

                        $propertyWebReviewCreate = PropertyWebReview::create($propertyWebWeatherParam);

                        $this->info(date('Y-m-d H:i:s') . ' : ' . $propertyWebComponent['property_id'] . ' - ' . $review['author_name'] . ' : ' . $review['rating']);


                    } 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);
                    }


                }


                $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);
        }

    }

}
