<?php

namespace App\Console\Commands\Data;

use App\Exceptions\ApiErrorException;
use App\Models\PropertyWeb;
use App\Models\PropertyWebWeather;
use App\Models\vwActiveProperty;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class DashboardCacheService extends Command
{

    protected $signature = 'cron:dashboard-cache';

    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') . ' : START');

            $bookingService = App::make("App\Core\Service\BookingService");
            $propertyWebController = App::make("App\Http\Controllers\V1\PropertyWebController");

            $vwActiveProperty = vwActiveProperty::where('commission', '>', 1)->orderBy('id')->get()->toArray();


            //$dashboardCountablePlaceCacheKey
            $this->info(date('Y-m-d H:i:s') . ' : $dashboardCountablePlaceCacheKey');
            foreach ($vwActiveProperty as $property) {


                //$dashboardCountablePlaceCacheKey
                $dashboardCountablePlaceCacheKey = md5('dashboardCountablePlace-' . $property['id']);

                try {

                    $this->line(date('Y-m-d H:i:s') . ' : ' . $property['id'] . ' - ' . $property['name']);

                    $propertyWeb = PropertyWeb::where('property_id', $property['id'])->where('status', 1)->orderByDesc('id')->first();
                    $propertyWeb = $propertyWeb ? $propertyWeb->toArray() : null;
                    if (empty($propertyWeb)) {
                        throw new Exception('Empty Web ID');
                    }

                    $dashboardCountablePlaceParam = ['property_id' => $property['id']];
                    $dashboardCountablePlace = $propertyWebController->dashboardCountablePlace($dashboardCountablePlaceParam, $propertyWeb['id']);

                    if ($dashboardCountablePlace['status']) {
                        Cache::put($dashboardCountablePlaceCacheKey, $dashboardCountablePlace, 24 * 60 * 60);//1 Day
                    }


                } catch (Exception $e) {
                    $this->error(date('Y-m-d H:i:s') . ' : ' . $e->getMessage());
                }

            }


            //$getBookingDetailedListCacheKey
            $this->info(date('Y-m-d H:i:s') . ' : GetBookingDetailedListCacheKey');
            foreach ($vwActiveProperty as $property) {
                $getBookingDetailedListCacheKey = md5('getBookingDetailedList-' . $property['id']);

                try {

                    $this->line(date('Y-m-d H:i:s') . ' : ' . $property['id'] . ' - ' . $property['name']);

                    $getBookingDetailedListParam = ['property_id' => $property['id'], 'channel_id' => 1];
                    $getBookingDetailedList = $bookingService->getBookingDetailedList($getBookingDetailedListParam);

                    if ($getBookingDetailedList['status'] == 'success') {


                        $bookings = collect($getBookingDetailedList['data']);
                        $channelBookings = $bookings->where('channel_id', '=', 1);
                        $getBookingEngineBookings = $channelBookings->all();
                        $paxCountArray = $channelBookings->where('status', '=', 1)->map(function ($booking) {
                            $roomPaxCount = collect($booking['booking_room'])->map(function ($room) {
                                return collect($room['room_pax'])->count();
                            })->values()->first();
                            return [
                                'booking_id' => $booking['id'],
                                'room_pax_count' => $roomPaxCount,
                            ];

                        })->values()->all();

                        $totalPaxCount = collect($paxCountArray)->sum('room_pax_count');

                        $allBookingCount = $channelBookings->count();
                        $preBookingCount = $channelBookings->where('status', '=', 2)->count();
                        $successBookingCount = $channelBookings->where('status', '=', 1)->count();

                        $conversionRate = $allBookingCount > 0 ? ($successBookingCount * 100) / $allBookingCount : 0;

                        $responseData['all_booking_count'] = $allBookingCount;
                        $responseData['success_booking_count'] = $successBookingCount;
                        $responseData['pre_booking_count'] = $preBookingCount;
                        $responseData['conversion_rate'] = number_format($conversionRate, 2);
                        $responseData['total_pax_count'] = $totalPaxCount;

                        Cache::put($getBookingDetailedListCacheKey, $responseData, 24 * 60 * 60);//1 Day


                    }


                } catch (Exception $e) {
                    $this->error(date('Y-m-d H:i:s') . ' : ' . $e->getMessage());
                }
                //$getBookingDetailedListCacheKey


            }


            $this->info(date('Y-m-d H:i:s') . ' : 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);
        }

    }

}
