<?php

namespace App\Console\Commands\Jobs;

use App\Core\Mail\DailyReportMail;
use App\Core\Mail\TrialFirstMail;
use App\Core\Mail\TrialSecondMail;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyService;
use App\Exceptions\ApiErrorException;
use App\Models\PropertyInvoice;
use App\Models\vwActiveProperty;
use App\Models\vwBookingSummary;
use App\Models\vwBookingSummaryAll;
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 SummaryReportMail extends Command
{
    protected $signature = 'cron:summary-report-mail';

    protected $description = '';

    private $propertyService;

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

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

    public function handle()
    {

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

        $today = Carbon::now()->subDay()->toDateString();

        $report['daily']['data'] = [];
        $report['daily']['title'] = 'Daily Report';
        $report['daily']['period'] = Carbon::parse($today)->format('d.m.Y');
        $daily = vwBookingSummaryAll::where('time', '>', Carbon::parse($today)->toDateString())
            ->where('time', '<', Carbon::parse($today)->addDay()->toDateString())
            ->where('commission', '>', 0)
            ->get()->toArray();

        if ($daily) {
            $dataCollect = collect($daily);
            $dataCollect = $dataCollect->filter(function ($item) {
                if ($item['property_id'] == 362) {
                    //Exclude Commission - Barın Hotel, 34 Hotelbeds, 103 World2Meet
                    if (!in_array($item['channel_id'], [34, 103])) {
                        return $item;
                    }
                } else if ($item['property_id'] == 712) {
                    //Exclude Commission - G Hotels Skopje
                    if (!in_array($item['id'], [18122, 18091, 18090, 18089, 18088, 18087, 18086])) {
                        return $item;
                    }
                } else {
                    return $item;
                }
            });

            $dataCollectGroup = $dataCollect->groupBy('currency_code')->toArray();
            foreach ($dataCollectGroup as $currencyCode => $currencyGroup) {
                $report['daily']['data'][$currencyCode]['count'] = count($currencyGroup);
                $report['daily']['data'][$currencyCode]['total'] = array_sum(pickItemFromArray('total', $currencyGroup));
                $report['daily']['data'][$currencyCode]['commission'] = array_sum(pickItemFromArray('commission', $currencyGroup));
            }

            $report['daily']['summary'] = ['count' => 0, 'total' => 0, 'commission' => 0];
            foreach ($report['daily']['data'] as $currentCurrency => $dailyData) {
                $lastExchangeRate = $this->currencyService->lastExchangeRate($currentCurrency, 'EUR');
                $report['daily']['summary']['count'] += $dailyData['count'];
                $report['daily']['summary']['total'] += $dailyData['total'] * $lastExchangeRate['data'];
                $report['daily']['summary']['commission'] += $dailyData['commission'] * $lastExchangeRate['data'];
            }
        }


        $report['monthly']['data'] = [];
        $report['monthly']['title'] = 'Monthly Report';
        $report['monthly']['period'] = Carbon::parse($today)->firstOfMonth()->format('m.Y');
        $monthly = vwBookingSummaryAll::where('time', '>', Carbon::parse($today)->firstOfMonth()->toDateString())
            ->where('time', '<', Carbon::parse($today)->addMonth()->firstOfMonth()->toDateString())
            ->where('commission', '>', 0)
            ->get()->toArray();

        if ($monthly) {
            $dataCollect = collect($monthly);
            $dataCollect = $dataCollect->filter(function ($item) {
                if ($item['property_id'] == 362) {
                    //Exclude Commission - Barın Hotel, 34 Hotelbeds, 103 World2Meet
                    if (!in_array($item['channel_id'], [34, 103])) {
                        return $item;
                    }
                } else if ($item['property_id'] == 712) {
                    //Exclude Commission - G Hotels Skopje
                    if (!in_array($item['id'], [18122, 18091, 18090, 18089, 18088, 18087, 18086])) {
                        return $item;
                    }
                } else {
                    return $item;
                }
            });

            $dataCollectGroup = $dataCollect->groupBy('currency_code')->toArray();
            foreach ($dataCollectGroup as $currencyCode => $currencyGroup) {
                $report['monthly']['data'][$currencyCode]['count'] = count($currencyGroup);
                $report['monthly']['data'][$currencyCode]['total'] = array_sum(pickItemFromArray('total', $currencyGroup));
                $report['monthly']['data'][$currencyCode]['commission'] = array_sum(pickItemFromArray('commission', $currencyGroup));
            }

            $report['monthly']['summary'] = ['count' => 0, 'total' => 0, 'commission' => 0];
            foreach ($report['monthly']['data'] as $currentCurrency => $dailyData) {
                $lastExchangeRate = $this->currencyService->lastExchangeRate($currentCurrency, 'EUR');
                $report['monthly']['summary']['count'] += $dailyData['count'];
                $report['monthly']['summary']['total'] += $dailyData['total'] * $lastExchangeRate['data'];
                $report['monthly']['summary']['commission'] += $dailyData['commission'] * $lastExchangeRate['data'];
            }


            //summaryCheckout
            $monthlyCheckout = vwBookingSummaryAll::where('checkout_period', Carbon::parse($today)->firstOfMonth()->format('Y-m'))
                ->where('commission', '>', 0)
                ->get()->toArray();

            $dataCollect = collect($monthlyCheckout);
            $dataCollect = $dataCollect->filter(function ($item) {
                if ($item['property_id'] == 362) {
                    //Exclude Commission - Barın Hotel, 34 Hotelbeds, 103 World2Meet
                    if (!in_array($item['channel_id'], [34, 103])) {
                        return $item;
                    }
                } else if ($item['property_id'] == 712) {
                    //Exclude Commission - G Hotels Skopje
                    if (!in_array($item['id'], [18122, 18091, 18090, 18089, 18088, 18087, 18086])) {
                        return $item;
                    }
                } else {
                    return $item;
                }
            });

            $dataCollectGroup = $dataCollect->groupBy('currency_code')->toArray();
            foreach ($dataCollectGroup as $currencyCode => $currencyGroup) {
                $report['monthly']['summaryCheckoutData'][$currencyCode]['count'] = count($currencyGroup);
                $report['monthly']['summaryCheckoutData'][$currencyCode]['total'] = array_sum(pickItemFromArray('total', $currencyGroup));
                $report['monthly']['summaryCheckoutData'][$currencyCode]['commission'] = array_sum(pickItemFromArray('commission', $currencyGroup));
            }

            $report['monthly']['summaryCheckout'] = ['count' => 0, 'total' => 0, 'commission' => 0];
            foreach ($report['monthly']['summaryCheckoutData'] as $currentCurrency => $dailyData) {
                $lastExchangeRate = $this->currencyService->lastExchangeRate($currentCurrency, 'EUR');
                $report['monthly']['summaryCheckout']['count'] += $dailyData['count'];
                $report['monthly']['summaryCheckout']['total'] += $dailyData['total'] * $lastExchangeRate['data'];
                $report['monthly']['summaryCheckout']['commission'] += $dailyData['commission'] * $lastExchangeRate['data'];
            }

            $monthlySummary = [];
            $annuallyMonths = [];
            for ($i = 0; $i < 12; $i++) {
                $annuallyMonths[] = Carbon::parse($today)->firstOfYear()->addMonths($i)->format('Y-m');
            }

            $vwBookingSummaryTransaction = vwBookingSummaryAll::whereIn('transaction_period',$annuallyMonths)
                ->where('commission', '>', 0)
                ->get()->toArray();

            $vwBookingSummaryCheckout = vwBookingSummaryAll::whereIn('checkout_period',$annuallyMonths)
                ->where('commission', '>', 0)
                ->get()->toArray();


            $vwBookingSummaryTransactionGrouped = collect($vwBookingSummaryTransaction)->groupBy('transaction_period')->toArray();
            $vwBookingSummaryCheckoutGrouped = collect($vwBookingSummaryCheckout)->groupBy('checkout_period')->toArray();


            $monthlySummary['month'] = [];
            foreach ($annuallyMonths as $annuallyMonth) {
                //$annuallyMonth = Carbon::parse($annuallyMonth)->format('Y-m');

                $monthlySummary['month'][$annuallyMonth] = $annuallyMonth;

                $monthlySummary['transaction'][$annuallyMonth]['count'] = 0;
                $monthlySummary['transaction'][$annuallyMonth]['total'] = 0;
                $monthlySummary['transaction'][$annuallyMonth]['commission'] = 0;
                if(isset($vwBookingSummaryTransactionGrouped[$annuallyMonth])) {
                    $dataCollectGroupCurrency = collect($vwBookingSummaryTransactionGrouped[$annuallyMonth])->groupBy('currency_code')->toArray();
                    foreach ($dataCollectGroupCurrency as $currencyCode => $currencyGroup) {

                        $lastExchangeRate = $this->currencyService->lastExchangeRate($currencyCode, 'EUR');
                        $monthlySummary['transaction'][$annuallyMonth]['count'] += collect($currencyGroup)->count();
                        $monthlySummary['transaction'][$annuallyMonth]['total'] += collect($currencyGroup)->sum('total') * $lastExchangeRate['data'];
                        $monthlySummary['transaction'][$annuallyMonth]['commission'] += collect($currencyGroup)->sum('commission') * $lastExchangeRate['data'];

                    }
                }

                $monthlySummary['checkout'][$annuallyMonth]['count'] = 0;
                $monthlySummary['checkout'][$annuallyMonth]['total'] = 0;
                $monthlySummary['checkout'][$annuallyMonth]['commission'] = 0;
                if(isset($vwBookingSummaryCheckoutGrouped[$annuallyMonth])) {
                    $dataCollectGroupCurrency = collect($vwBookingSummaryCheckoutGrouped[$annuallyMonth])->groupBy('currency_code')->toArray();
                    foreach ($dataCollectGroupCurrency as $currencyCode => $currencyGroup) {

                        $lastExchangeRate = $this->currencyService->lastExchangeRate($currencyCode, 'EUR');
                        $monthlySummary['checkout'][$annuallyMonth]['count'] += collect($currencyGroup)->count();
                        $monthlySummary['checkout'][$annuallyMonth]['total'] += collect($currencyGroup)->sum('total') * $lastExchangeRate['data'];
                        $monthlySummary['checkout'][$annuallyMonth]['commission'] += collect($currencyGroup)->sum('commission') * $lastExchangeRate['data'];

                    }
                }

            }

            $report['monthlySummary'] = $monthlySummary;

        }

        $report['annually']['data'] = [];
        $report['annually']['title'] = 'Annually Report';
        $report['annually']['period'] = Carbon::parse($today)->firstOfYear()->format('Y');
        $annually = vwBookingSummaryAll::where('time', '>', Carbon::parse($today)->firstOfYear()->toDateString())
            ->where('time', '<', Carbon::parse($today)->addYear()->firstOfYear()->toDateString())
            ->where('commission', '>', 0)
            ->get()->toArray();

        if ($annually) {
            $dataCollect = collect($annually);
            $dataCollect = $dataCollect->filter(function ($item) {
                if ($item['property_id'] == 362) {
                    //Exclude Commission - Barın Hotel, 34 Hotelbeds, 103 World2Meet
                    if (!in_array($item['channel_id'], [34, 103])) {
                        return $item;
                    }
                } else if ($item['property_id'] == 712) {
                    //Exclude Commission - G Hotels Skopje
                    if (!in_array($item['id'], [18122, 18091, 18090, 18089, 18088, 18087, 18086])) {
                        return $item;
                    }
                } else {
                    return $item;
                }
            });

            $dataCollectGroup = $dataCollect->groupBy('currency_code')->toArray();
            foreach ($dataCollectGroup as $currencyCode => $currencyGroup) {
                $report['annually']['data'][$currencyCode]['count'] = count($currencyGroup);
                $report['annually']['data'][$currencyCode]['total'] = array_sum(pickItemFromArray('total', $currencyGroup));
                $report['annually']['data'][$currencyCode]['commission'] = array_sum(pickItemFromArray('commission', $currencyGroup));
            }

            $report['annually']['summary'] = ['count' => 0, 'total' => 0, 'commission' => 0];
            foreach ($report['annually']['data'] as $currentCurrency => $dailyData) {
                $lastExchangeRate = $this->currencyService->lastExchangeRate($currentCurrency, 'EUR');
                $report['annually']['summary']['count'] += $dailyData['count'];
                $report['annually']['summary']['total'] += $dailyData['total'] * $lastExchangeRate['data'];
                $report['annually']['summary']['commission'] += $dailyData['commission'] * $lastExchangeRate['data'];
            }


            //summaryCheckout Annually

            $annuallyCheckout = vwBookingSummaryAll::where('checkout_date', '>=', Carbon::parse($today)->firstOfYear()->format('Y-m-d'))
                ->where('checkout_date', '<=', Carbon::parse($today)->endOfYear()->format('Y-m-d'))
                ->where('commission', '>', 0)
                ->get()->toArray();

            $dataCollect = collect($annuallyCheckout);
            $dataCollect = $dataCollect->filter(function ($item) {
                if ($item['property_id'] == 362) {
                    //Exclude Commission - Barın Hotel, 34 Hotelbeds, 103 World2Meet
                    if (!in_array($item['channel_id'], [34, 103])) {
                        return $item;
                    }
                } else if ($item['property_id'] == 712) {
                    //Exclude Commission - G Hotels Skopje
                    if (!in_array($item['id'], [18122, 18091, 18090, 18089, 18088, 18087, 18086])) {
                        return $item;
                    }
                } else {
                    return $item;
                }
            });

            $dataCollectGroup = $dataCollect->groupBy('currency_code')->toArray();
            foreach ($dataCollectGroup as $currencyCode => $currencyGroup) {
                $report['annually']['summaryCheckoutData'][$currencyCode]['count'] = count($currencyGroup);
                $report['annually']['summaryCheckoutData'][$currencyCode]['total'] = array_sum(pickItemFromArray('total', $currencyGroup));
                $report['annually']['summaryCheckoutData'][$currencyCode]['commission'] = array_sum(pickItemFromArray('commission', $currencyGroup));
            }

            $report['annually']['summaryCheckout'] = ['count' => 0, 'total' => 0, 'commission' => 0];
            foreach ($report['annually']['summaryCheckoutData'] as $currentCurrency => $dailyData) {
                $lastExchangeRate = $this->currencyService->lastExchangeRate($currentCurrency, 'EUR');
                $report['annually']['summaryCheckout']['count'] += $dailyData['count'];
                $report['annually']['summaryCheckout']['total'] += $dailyData['total'] * $lastExchangeRate['data'];
                $report['annually']['summaryCheckout']['commission'] += $dailyData['commission'] * $lastExchangeRate['data'];
            }

        }

        //Hotel LIST
        $vwActivePropertySummary = [];
        $vwActiveProperty = vwActiveProperty::where('commission', '>', 1)->orderByDesc('id')->get()->toArray();
        $vwActivePropertySummary['count'] = count($vwActiveProperty);
        $vwActivePropertySummary['groupByMonth'] = collect($vwActiveProperty)->sortByDesc('month')->groupBy('month')->toArray();
        $vwActivePropertySummary['lastMonth'] = collect($vwActivePropertySummary['groupByMonth'])->take(12)->toArray();

        if ($vwActivePropertySummary['lastMonth']) {
            foreach ($vwActivePropertySummary['lastMonth'] as $lastMonthKey => $lastMonth) {
                $vwActivePropertySummary['lastMonth'][$lastMonthKey] = collect($vwActivePropertySummary['lastMonth'][$lastMonthKey])->sortByDesc('id')->toArray();
                if ($vwActivePropertySummary['lastMonth'][$lastMonthKey]) {
                    $vwActivePropertySummary['lastMonth'][$lastMonthKey] = array_values($vwActivePropertySummary['lastMonth'][$lastMonthKey]);
                }
            }
        }

        //Hotel LIST

        $report['activeProperty'] = $vwActivePropertySummary;

        //Comparative Summary Data
        //Carbon::setLocale('tr');
        for ($month = 1; $month <= 12; $month++) {
            $months[$month] = Carbon::create(null, $month, 1)->translatedFormat('F');
        }
        $report['comparative']['monthList'] = $months;

        $currentYear = Carbon::parse($today)->firstOfYear()->format('Y');
        $lastYear = Carbon::parse($today)->subYear()->firstOfYear()->format('Y');

        $report['comparative']['yearList'][] = $lastYear;
        $report['comparative']['yearList'][] = $currentYear;

        $periodList = [];
        foreach ([$currentYear,$lastYear] as $periodYear) {
            for ($month = 1; $month <= 12; $month++) {
                $periodList[] = $periodYear . '-' . str_pad((integer)$month, 2, '0', STR_PAD_LEFT);
            }
        }

        $propertyInvoice = PropertyInvoice::where('status',1)->whereIn('period', $periodList);
        $propertyInvoice = $propertyInvoice ? $propertyInvoice->get()->toArray() : [];

        foreach ($propertyInvoice as $invoice) {
            $periodYear = Carbon::parse($invoice['period'])->format('Y');
            $periodMonth = (int)Carbon::parse($invoice['period'])->format('m');
            if(!isset($report['comparative']['data'][$periodYear][$periodMonth])) {
                $report['comparative']['data'][$periodYear][$periodMonth] = 0;
            }
            $report['comparative']['data'][$periodYear][$periodMonth]+=$invoice['total'];
        }

        $comparativeDiff = [];
        foreach ($months as $monthKey => $month) {
            $comparativeDiff[$monthKey]['amount'] = $report['comparative']['data'][$currentYear][$monthKey] - $report['comparative']['data'][$lastYear][$monthKey];
        }
        $report['comparative']['diff'] = $comparativeDiff;
        //Comparative Summary Data


        //$json = json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        //file_put_contents(resource_path('data/data.json'), $json);
        //die();

        $this->mailer->onQueue('dailyReportMail', new DailyReportMail($report));

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


    }
}
