<?php

namespace App\Http\Controllers\Owner\Provider;

use App\Http\Controllers\Controller;
use App\Http\Helpers\ResponseBuilder;
use App\Modules\Provider\Application\PassengerDistributionNationality\PassengerDistributionNationalityQuery;
use App\Modules\Provider\Application\PassengerDistributionNationality\PassengerDistributionNationalityQueryResponse;
use App\Modules\Provider\Infrastructure\ProviderValidators;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use Illuminate\Http\Request;

class ProviderListPassengerDistributionNationalityController extends Controller
{
    public function __construct(
        private QueryBus $queryBus,
    )
    {
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator)->validate($request->all(), 'Provider', ProviderValidators::listPassengerDistribution());
        /** @var PassengerDistributionNationalityQueryResponse $response */
        $response = $this->queryBus->ask(
            new PassengerDistributionNationalityQuery(
                $request->input('Date_Start'),
                $request->input('Date_End'),
                $request->input('Id_TypeProvider'),
                $request->input('Search', ''),
                $request->input('OrderCountryId', 0),
                $request->input('OrderType',''),
                $request->input('OrderOrientation','DESC'),
                $request->input('ProvidersWithData', false),
                $request->input('Page'),
                $request->input('Page_Size')));
        $dataGrouped = $this->groupByTypeProvider($response->data(), $request->input('OrderCountryId', 0));
        $dataCount = $response->totalCount();
        return ResponseBuilder::Response(ResponseBuilder::buildSelectResponse($dataGrouped, '', 'provider', $dataCount));
    }

    private function groupByTypeProvider($providers, $orderCountryId)
    {
        $grouped = [];

        foreach ($providers as $provider) {

            $type = $provider->TypeProvider_Name_Aux;
            $providerId = $provider->Id_Provider;

            if (!isset($grouped[$type])) {
                $grouped[$type] = [
                    "Id_TypeProvider" => $provider->Id_TypeProvider_Aux,
                    "TypeProvider_Name" => $provider->TypeProvider_Name_Aux,
                    "Providers" => [],
                    "CountriesWithData" => []
                ];
            }

            if (!isset($grouped[$type]["Providers"][$providerId])) {
                $grouped[$type]["Providers"][$providerId] = [
                    "Id_Provider" => $provider->Id_Provider,
                    "Provider_BusinessName" => $provider->Provider_BusinessName,
                    "Countries" => [],
                    "Total" => 0,
                ];
            }

            if ($provider->Id_UserCountry !== null) {
                $grouped[$type]["Providers"][$providerId]["Countries"][] = [
                    "Id_UserCountry" => $provider->Id_UserCountry,
                    "UserCountry_Code" => $provider->UserCountry_Code,
                    "UserCountry_Name" => $provider->UserCountry_Name,
                    "Count" => $provider->Total
                ];
                $grouped[$type]["Providers"][$providerId]["Total"] += $provider->Total;

                $grouped[$type]["CountriesWithData"][$provider->Id_UserCountry] = true;
            }
        }
        foreach ($grouped as &$type) {
            if ($orderCountryId) {
                $type["CountriesWithData"][$orderCountryId] = true;
            }

            $type["Providers"] = array_values($type["Providers"]);
            $type["CountriesWithData"] = array_keys($type["CountriesWithData"]);
        }

        return array_values($grouped);
    }
}
