<?php

namespace App\Http\Controllers\Owner\Provider;

use App\Http\Controllers\Controller;
use App\Http\Helpers\ParamsValidator;
use App\Http\Helpers\ResponseBuilder;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProviderListReviewScoreGroupDataController extends Controller
{
    private $oDomain;

    public function __construct()
    {
        $this->oDomain = "Provider";
    }

    public function __invoke(Request $Request, $Id)
    {
        $validations = [
            'DateStart' => 'required|string|date',
            'DateEnd' => 'required|string|date',
            'Page' => 'required|integer|min:1',
            'PageSize' => 'required|integer|min:1'
        ];
        (new LaravelValidator())->validate($Request->all(), $this->oDomain, $validations);

        $oResponse = ParamsValidator::Validate_Id($Id, $this->oDomain);

        if ($oResponse["Response_Code"] == 200) {
            $page = $Request->input('Page', 1);
            $pageSize = $Request->input('PageSize', 100);
            $dateStart = $Request->input('DateStart') . ' 00:00:00';
            $dateEnd = $Request->input('DateEnd') . ' 23:59:59';
            $search = $Request->input('Search', '');

            $providerList = DB::select('CALL sp_provider_list_review_score(?,?,?,?,?)', [$Id, 0, $page, $pageSize, $search]);

            if (empty($providerList)) {
                $oResponse["Response_Status"] = 200;
                $oResponse["Response_Code"] = 200;
                $oResponse["Response_Data"] = [];
                $oResponse["Response_Count"] = 0;
                return ResponseBuilder::Response($oResponse);
            }

            $providerIds = implode(',', array_map(fn($p) => $p->Id_Provider, $providerList));

            $groupData = DB::select('CALL sp_internal_provider_group_passenger_count_endose_canceled(?,?,?,@sts,@cod,@msg)', [
                $providerIds, $dateStart, $dateEnd
            ]);

            $oResponse["Response_Status"] = 200;
            $oResponse["Response_Code"] = 200;
            $oResponse["Response_Count"] = $providerListCount[0]->TotalProviders ?? 0;
            $oResponse["Response_Domain"] = $this->oDomain;
            $oResponse["Response_Message"] = $this->oDomain . " list " . $Id;
            $oResponse["Response_Data"] = $groupData;
            $oResponse["Response_Error_Message"] = "";
            $oResponse["Response_Error_Reason"] = "";
        }

        return ResponseBuilder::Response($oResponse);
    }
}
