<?php

namespace App\Console\Commands\Jobs;

use App\Core\Mail\BookingEngineSearchReportMail;
use App\Core\Service\PropertyService;
use App\Exceptions\ApiErrorException;
use App\Models\Country;
use App\Models\Language;
use App\Models\vwBookingEngineSearch;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BookingEngineSearchReportService extends Command
{
    protected $signature = 'cron:bookingengine-search-report-mail';

    protected $description = '';

    private $propertyService;

    public function __construct(
        Mailer $mailer,
        PropertyService $propertyService
    )
    {
        parent::__construct();

        $this->mailer = $mailer;
        $this->propertyService = $propertyService;
    }

    public function handle()
    {

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

        $reportPropertyList = [506, 529, 1606];
        //506	Green Nature Diamond Hotel
        //529	Green Nature Resort & Spa Otel
        //1606	Green Nature Sarıgerme

        $propertyListCriteria = [
            'criteria' =>
                [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
            'with' => ['propertyBrand', 'propertyUser.user'],
            'orderBy' => [
                ['field' => 'id', 'value' => 'ASC']
            ],
            'whereIn' =>
                [
                    ['field' => 'id', 'value' => $reportPropertyList]
                ]
        ];

        $propertyListData = $this->propertyService->select($propertyListCriteria);

        $propertyList = [];
        if ($propertyListData['status'] == 'success' && !empty($propertyListData['data'])) {
            $propertyList = $propertyListData['data'];
        }


        $reportData = [];
        $reportDate = Carbon::now()->subDay()->toDateString();
        //$reportDate = '2023-02-28';
        $reportDateFormatted = Carbon::parse($reportDate)->format('d.m.Y');

        $countryList = Country::all()->toArray();
        $languageList = Language::all()->toArray();


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

        foreach ($propertyList as $property) {

            $reportData = [];

            $reportData['propertyId'] = $property['id'];
            $reportData['propertyName'] = $property['name'];
            $reportData['propertyCountry'] = $property['country'];
            $reportData['logo'] = $property['property_brand']['logoUrl'];
            $reportData['date'] = $reportDateFormatted;
            $reportData['propertyUserEmail'] = collect($property['property_user'])->where('user.email','<>', null)->pluck('user.email')->toArray();

            $searchData = vwBookingEngineSearch::where('property_id', $property['id'])
                ->where('date', $reportDate)
                ->get()->toArray();

            $this->info(date('Y-m-d H:i:s') . ' Property: ' . $reportData['propertyName']);

            if (!empty($searchData)) {

                $reportData['transaction']['search'] = collect($searchData)->count();
                $reportData['transaction']['roomFound'] = collect($searchData)->where('status', 1)->count();
                $reportData['transaction']['roomNotFound'] = collect($searchData)->where('status', 0)->count();
                $reportData['transaction']['preBooking'] = collect($searchData)->where('status', 2)->count();
                $reportData['transaction']['booking'] = collect($searchData)->where('status', 3)->count();


                $countryCodes = collect($searchData)->groupBy('country_code')->keys()->toArray();
                foreach ($countryCodes as $countryCode) {
                    $countryText = $countryCode;
                    $countryTextCheck = collect($countryList)->where('country_code', mb_strtoupper($countryCode))->first();
                    if (!empty($countryTextCheck)) {
                        $countryText = $countryTextCheck['name'];
                    }
                    $reportData['country'][$countryCode]['text'] = $countryText;
                    $reportData['country'][$countryCode]['search'] = collect($searchData)->where('country_code', $countryCode)->count();
                    $reportData['country'][$countryCode]['roomFound'] = collect($searchData)->where('country_code', $countryCode)->where('status', 1)->count();
                    $reportData['country'][$countryCode]['roomNotFound'] = collect($searchData)->where('country_code', $countryCode)->where('status', 0)->count();
                    $reportData['country'][$countryCode]['preBooking'] = collect($searchData)->where('country_code', $countryCode)->where('status', 2)->count();
                    $reportData['country'][$countryCode]['booking'] = collect($searchData)->where('country_code', $countryCode)->where('status', 3)->count();
                }

                $reportData['country'] = collect($reportData['country'])->sortByDesc('search')->toArray();

                $languageCodes = collect($searchData)->groupBy('language_code')->keys()->toArray();
                foreach ($languageCodes as $languageCode) {
                    $languageText = $languageCode;
                    $languageTextCheck = collect($languageList)->where('code', $languageCode)->first();
                    if (!empty($languageTextCheck)) {
                        $languageText = $languageTextCheck['name'];
                    }
                    $reportData['language'][$languageCode]['text'] = $languageText;
                    $reportData['language'][$languageCode]['search'] = collect($searchData)->where('language_code', $languageCode)->count();
                    $reportData['language'][$languageCode]['roomFound'] = collect($searchData)->where('language_code', $languageCode)->where('status', 1)->count();
                    $reportData['language'][$languageCode]['roomNotFound'] = collect($searchData)->where('language_code', $languageCode)->where('status', 0)->count();
                    $reportData['language'][$languageCode]['preBooking'] = collect($searchData)->where('language_code', $languageCode)->where('status', 2)->count();
                    $reportData['language'][$languageCode]['booking'] = collect($searchData)->where('language_code', $languageCode)->where('status', 3)->count();
                }

                $reportData['language'] = collect($reportData['language'])->sortByDesc('search')->toArray();


                $occupancyCodes = collect($searchData)->groupBy('pax')->keys()->toArray();
                foreach ($occupancyCodes as $occupancyCode) {
                    $reportData['occupancy'][$occupancyCode]['text'] = occupancyCodeFormatted($occupancyCode);
                    $reportData['occupancy'][$occupancyCode]['count'] = collect($searchData)->where('pax', $occupancyCode)->count();
                }

                $reportData['occupancy'] = collect($reportData['occupancy'])->sortByDesc('count')->toArray();

                //Daily Intensity
                $dailyIntensity = [];
                foreach ($searchData as $data) {
                    $checkInDate = $data['checkin_date'];
                    $checkOutDate = $data['checkout_date'];
                    $dateDiff = Carbon::parse($data['checkout_date'])->diffInDays(Carbon::parse($data['checkin_date']));

                    for ($i = 0; $i < $dateDiff; $i++) {
                        $date = Carbon::parse($checkInDate)->addDays($i)->toDateString();

                        if (!isset($dailyIntensity[$date])) {
                            $dailyIntensity[$date]['text'] = Carbon::parse($date)->format('d.m.Y');
                            $dailyIntensity[$date]['search'] = 0;
                            $dailyIntensity[$date]['roomFound'] = 0;
                            $dailyIntensity[$date]['roomNotFound'] = 0;
                            $dailyIntensity[$date]['preBooking'] = 0;
                            $dailyIntensity[$date]['booking'] = 0;
                        }

                        $dailyIntensity[$date]['search']++;
                        $dailyIntensity[$date]['roomFound'] += $data['status'] == 1 ? 1 : 0;
                        $dailyIntensity[$date]['roomNotFound'] += $data['status'] == 0 ? 1 : 0;
                        $dailyIntensity[$date]['preBooking'] += $data['status'] == 2 ? 1 : 0;
                        $dailyIntensity[$date]['booking'] += $data['status'] == 3 ? 1 : 0;

                    }
                }
                ksort($dailyIntensity);
                $reportData['dailyIntensity'] = $dailyIntensity;
                //Daily Intensity

            }

            if (!empty($searchData)) {
                $this->mailer->onQueue('bookingEngineSearchReportMail', new BookingEngineSearchReportMail($reportData));
                $this->info(date('Y-m-d H:i:s') . ' Property: ' . $reportData['propertyName'] . ' - SENT MAIL');
            }

        }

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


    }
}
