<?php

namespace App\Console\Commands\Data;

use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Exception;
use Illuminate\Support\Facades\Log;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;

class HotelBedsList extends Command
{

    protected $signature = 'cron:hotelbeds-list';

    protected $description = '';

    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {
        try {

            $hotelList = [];

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

            $baseUrl = 'https://api.hotelbeds.com';
            $apiKey = 'ddaa6y6zpf6sy8fne4n2zj7q';
            $secret = 'wc87VEfTSD';

            $countryCode = 'TR';
            $language = 'TUR';
            $destinationCode = 'AYT';

            $fields = ['code', 'name', 'email', 'countryCode', 'destinationCode', 'city','phones'];


            $chunk = 500;

            $from = 1;
            $to = $chunk;

            $isContinue = true;
            while ($isContinue) {

                $xSignature = hash("sha256", $apiKey . $secret . time());
                $urlGenerate = $baseUrl . '/hotel-content-api/1.0/hotels?fields=' . implode(',', $fields) . '&countryCode=' . $countryCode . '&language=' . $language . '&from=' . $from . '&to=' . $to.'&destinationCode='.$destinationCode;

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

                $request = $this->restClient->GET($urlGenerate, [
                    'headers' => [
                        'content-type' => 'application/json',
                        'Api-key' => $apiKey,
                        'X-Signature' => $xSignature,
                    ],
                    'body' => null,
                ]);
                Log::debug($xSignature);
                $requestResponse = $request->getBody();
                $requestResponse = json_decode($requestResponse, 1);

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

                $from += $chunk;
                $to = $from + $chunk - 1;

                if (empty($requestResponse['hotels'])) {
                    $isContinue = false;
                }

                foreach ($requestResponse['hotels'] as $hotel) {

                    if(!isset($hotel['email'])) {
                        continue;
                    }

                    $email = mb_strtolower($hotel['email']);

                    $hotelList[$email] = [
                        'code' => $hotel['code'],
                        'content' => (string)uCase($hotel['name']['content']),
                        'countryCode' => $hotel['countryCode'],
                        'email' => $email
                    ];

                    foreach ($hotel['phones'] as $phone) {
                        if(in_array($phone['phoneType'], ['PHONEHOTEL','PHONEMANAGEMENT'])) {
                            $hotelList[$email]['phone'] = $phone['phoneNumber'];
                            break;
                        }
                    }
                }
            }



            // Open a file in write mode ('w')
            $fileName = $countryCode.(!empty($destinationCode) ? '-'.$destinationCode : '');
            $fp = fopen(resource_path().'/data/'.$fileName.'.csv', 'w');

            // Loop through file pointer and a line
            foreach ($hotelList as $hotel) {
                fputcsv($fp, $hotel);
            }

            fclose($fp);

            $this->info(date('Y-m-d H:i:s') . ' : Total: ' . count($hotelList).' / '. $requestResponse['total']);


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

    }

}
