<?php

namespace App\Console\Commands\Jobs;

use App\Core\Mail\DailyReportMail;
use App\Core\Mail\DailyReportMailSales;
use App\Core\Mail\TrialFirstMail;
use App\Core\Mail\TrialSecondMail;
use App\Core\Service\CurrencyService;
use App\Core\Service\PropertyService;
use App\Core\Service\UserService;
use App\Exceptions\ApiErrorException;
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 SummaryReportMailSales extends Command
{
    protected $signature = 'cron:summary-report-mail-sales';

    protected $description = '';

    private $propertyService;

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

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

    public function reportCalculate($userId, $contractUserProperty, $type)
    {

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

        $report = ['data' => null, 'summary' => null];


        switch ($type) {

            case 'daily':
                $vwBookingSummaryAll = vwBookingSummaryAll::where('time', '>', Carbon::parse($today)->toDateString())
                    ->where('time', '<', Carbon::parse($today)->addDay()->toDateString())
                    ->where('commission', '>', 0)
                    ->where('contract_user_id', $userId)
                    ->whereIn('property_id', $contractUserProperty)
                    ->get()->toArray();
                break;

            case 'monthly':

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

                $vwBookingSummaryAll = vwBookingSummaryAll::whereIn('transaction_period', [Carbon::parse($today)->firstOfMonth()->format('Y-m')])
                    ->where('commission', '>', 0)
                    ->where('contract_user_id', $userId)
                    ->whereIn('property_id', $contractUserProperty)
                    ->get()->toArray();

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

                $vwBookingSummaryCheckout = vwBookingSummaryAll::whereIn('checkout_period', $annuallyMonths)
                    ->where('commission', '>', 0)
                    ->where('contract_user_id', $userId)
                    ->whereIn('property_id', $contractUserProperty)
                    ->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;

                break;

            case 'annually':
                $vwBookingSummaryAll = vwBookingSummaryAll::where('time', '>', Carbon::parse($today)->firstOfYear()->toDateString())
                    ->where('time', '<', Carbon::parse($today)->addYear()->firstOfYear()->toDateString())
                    ->where('commission', '>', 0)
                    ->where('contract_user_id', $userId)
                    ->whereIn('property_id', $contractUserProperty)
                    ->get()->toArray();
                break;
        }


        if ($vwBookingSummaryAll) {
            $dataCollect = collect($vwBookingSummaryAll);

            $dataCollectGroup = $dataCollect->groupBy('property_id')->toArray();
            foreach ($dataCollectGroup as $propertyId => $propertyList) {

                $property = reset($propertyList);
                $report['data'][$propertyId]['id'] = $property['property_id'];
                $report['data'][$propertyId]['name'] = $property['property_name'];

                $report['data'][$propertyId]['count'] = 0;
                $report['data'][$propertyId]['total'] = 0;
                $report['data'][$propertyId]['commission'] = 0;

                $dataCollectGroupCurrency = collect($propertyList)->groupBy('currency_code')->toArray();

                foreach ($dataCollectGroupCurrency as $currencyCode => $currencyGroup) {

                    $lastExchangeRate = $this->currencyService->lastExchangeRate($currencyCode, 'EUR');

                    $count = collect($currencyGroup)->count();
                    $total = collect($currencyGroup)->sum('total');
                    $commission = collect($currencyGroup)->sum('commission');

                    $report['data'][$propertyId]['count'] += $count;
                    $report['data'][$propertyId]['total'] += $total * $lastExchangeRate['data'];
                    $report['data'][$propertyId]['commission'] += $commission * $lastExchangeRate['data'];

                }
            }

            $report['data'] = collect($report['data'])->sortByDesc('commission')->toArray();

            $report['summary']['count'] = collect($report['data'])->sum('count');
            $report['summary']['total'] = collect($report['data'])->sum('total');
            $report['summary']['commission'] = collect($report['data'])->sum('commission');

        }


        return $report;

    }

    public function handle()
    {

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

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

        $userListIds = [904, 941, 1485];//41, 22, 883

        $userListCriteria = [
            'criteria' => [
                ['field' => 'status', 'condition' => '=', 'value' => 1],
            ],
            'whereIn' => [
                ['field' => 'id', 'value' => $userListIds]
            ],
            'orderBy' => [
                ['field' => 'id', 'value' => 'ASC']
            ]
        ];
        $userList = $this->userService->select($userListCriteria);

        foreach ($userList['data'] as $user) {

            $contractUserProperty = vwActiveProperty::where('contract_user_id', $user['id'])
                //->where('month', '>', '2024-10')
                ->get()->toArray();

            $contractUserProperty = $contractUserProperty ? pickItemFromArray('id',$contractUserProperty) : [];

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

            $report['name'] = $user['nameSurname'];
            $report['email'] = $user['email'];


            //DAILY
            $report['daily']['data'] = [];
            $report['daily']['title'] = 'Daily Report';
            $report['daily']['type'] = 'daily';
            $report['daily']['period'] = Carbon::parse($today)->format('d.m.Y');

            $reportCalculate = $this->reportCalculate($user['id'], $contractUserProperty, $report['daily']['type']);

            $report['daily']['data'] = $reportCalculate['data'];
            $report['daily']['summary'] = $reportCalculate['summary'];




            //MONTHLY
            $report['monthly']['data'] = [];
            $report['monthly']['title'] = 'Monthly Report';
            $report['monthly']['type'] = 'monthly';
            $report['monthly']['period'] = Carbon::parse($today)->firstOfMonth()->format('m.Y');

            $reportCalculate = $this->reportCalculate($user['id'], $contractUserProperty, $report['monthly']['type']);

            $report['monthly']['data'] = $reportCalculate['data'];
            $report['monthly']['summary'] = $reportCalculate['summary'];
            $report['monthlySummary'] = $reportCalculate['monthlySummary'];


            //ANNUALLY
            $report['annually']['data'] = [];
            $report['annually']['title'] = 'Annually Report';
            $report['annually']['type'] = 'annually';
            $report['annually']['period'] = Carbon::parse($today)->firstOfYear()->format('Y');

            $reportCalculate = $this->reportCalculate($user['id'], $contractUserProperty, $report['annually']['type']);

            $report['annually']['data'] = $reportCalculate['data'];
            $report['annually']['summary'] = $reportCalculate['summary'];

            $report['activeProperty'] = vwActiveProperty::where('commission', '>', 1)
                ->where('contract_user_id', $user['id'])
                ->whereIn('id', $contractUserProperty)
                ->orderByDesc('id')
                ->get()->toArray();


            //Property Price Comparison
            $priceComparisonLink = null;
            $todayComparison = Carbon::now()->toDateString();
            $firstDayOfWeek = Carbon::parse($todayComparison)->startOfWeek(Carbon::MONDAY);
            //$firstDayOfWeek = Carbon::parse($today)->startOfWeek(Carbon::MONDAY)->toDateString();

            //if(Carbon::now()->toDateString() == $firstDayOfWeek) {
                $year = Carbon::parse($firstDayOfWeek)->format('Y');
                $week = Carbon::parse($firstDayOfWeek)->isoWeek();
                $queryKeyHash = md5($year . '-' . $week);
                $priceComparisonLink = config('app.url').'/property-comparison/'.$queryKeyHash.'/'.$user['id'];
            //}
            $report['priceComparisonLink'] = $priceComparisonLink;
            //Property Price Comparison


            $this->mailer->onQueue('dailyReportSalesMail', new DailyReportMailSales($report));


        }

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

        $report['activeProperty'] = $vwActivePropertySummary;*/



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


    }
}
