<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyRoomRate\PropertyRoomRateRepository;
use App\Core\Repository\PropertyRoomRateInclusionMapping\PropertyRoomRateInclusionMappingRepository;
use App\Core\Validator\PropertyRoomRate\PropertyRoomRateAddValidator;
use App\Core\Validator\PropertyRoomRate\PropertyRoomRateAddWithInclusionValidator;
use App\Core\Validator\PropertyRoomRate\PropertyRoomRateUpdateValidator;
use App\Core\Validator\PropertyRoomRate\PropertyRoomRateDeleteValidator;
use App\Core\Service\PropertyFactService;


use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class PropertyRoomRateService
{

    private $propertyRoomRateRepository;
    private $propertyRoomRateAddValidator;
    private $propertyRoomRateAddWithInclusionValidator;
    private $propertyRoomRateUpdateValidator;
    private $propertyRoomRateDeleteValidator;
    private $propertyRoomRateInclusionMappingRepository;
    private $propertyFactService;


    public function __construct(

        PropertyRoomRateRepository $propertyRoomRateRepository,
        PropertyFactService $propertyFactService,
        PropertyRoomRateUpdateValidator $propertyRoomRateUpdateValidator,
        PropertyRoomRateDeleteValidator $propertyRoomRateDeleteValidator,
        PropertyRoomRateAddWithInclusionValidator $propertyRoomRateAddWithInclusionValidator,
        PropertyRoomRateInclusionMappingRepository $propertyRoomRateInclusionMappingRepository,
        PropertyRoomRateAddValidator $propertyRoomRateAddValidator,
        LanguageService $languageService
    )
    {

        $this->propertyRoomRateRepository = $propertyRoomRateRepository;
        $this->propertyRoomRateAddValidator = $propertyRoomRateAddValidator;
        $this->propertyRoomRateUpdateValidator = $propertyRoomRateUpdateValidator;
        $this->propertyRoomRateDeleteValidator = $propertyRoomRateDeleteValidator;
        $this->propertyRoomRateAddWithInclusionValidator = $propertyRoomRateAddWithInclusionValidator;
        $this->propertyRoomRateInclusionMappingRepository = $propertyRoomRateInclusionMappingRepository;
        $this->propertyFactService = $propertyFactService;
        $this->languageService = $languageService;

    }

    public function create($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->propertyRoomRateAddValidator->validate($params);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $insertData =
                [
                    'property_id' => fillOnUndefined($params, 'property_id'),
                    'name' => fillOnUndefined($params, 'name'),
                    'description' => fillOnUndefined($params, 'description'),
                    'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
                    'min_stay' => fillOnUndefined($params, 'min_stay'),
                    'max_stay' => fillOnUndefined($params, 'max_stay'),
                    "status" => fillOnUndefined($params, "status", 1),
                    "created_by" => fillOnUndefined($params, "created_by"),
                    "updated_by" => fillOnUndefined($params, "updated_by"),
                ];

            $userCreateResult = $this->propertyRoomRateRepository->create($insertData);

            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $userCreateResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function select($param = [], $column = ['*'])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];

        $getApplicationLanguages = $this->languageService->getApplicationLanguages();
        if ($getApplicationLanguages['status'] != 'success') {
            throw new ApiErrorException($getApplicationLanguages['message']);
        }
        $applicationLanguages = $getApplicationLanguages['data'];

        try {

            $data = $this->propertyRoomRateRepository->findByCriteria($param, $column);

            if ($data) {
                $descriptionLangContents = json_decode($data['description'], 1);
                $responseLangDescription = [];
                foreach ($applicationLanguages as $applicationLanguage) {
                    $langKey = $applicationLanguage['code'];
                    $responseLangDescription[] = [
                        'language_code' => $langKey,
                        'description' => isset($descriptionLangContents[$langKey]) ? $descriptionLangContents[$langKey] : null
                    ];
                }

                $data['description'] = $responseLangDescription;
            }

            $response = [
                'status' => true,
                'data' => $data,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function update($id, $param = [])
    {


        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {


            $updateResult = $this->propertyRoomRateRepository->update($id, $param);
            if ($updateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $updateData = $updateResult["data"];
            $response = [
                'status' => true,
                'data' => $updateData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function updateOrCreate($criteria = [], $saveData = [])
    {


        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->propertyRoomRateRepository->updateOrCreate($criteria, $saveData);
            if ($data['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $response = [
                'status' => true,
                'data' => $data,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);


    }

    public function addPropertyRoomRate($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $description = [];
            foreach (fillOnUndefined($params, "description", []) as $desc) {
                $description[$desc['language_code']] = $desc['description'];
            }

            $insertData = [
                'property_id' => fillOnUndefined($params, 'property_id'),
                'name' => fillOnUndefined($params, 'name'),
                'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
                'min_stay' => fillOnUndefined($params, 'min_stay'),
                'max_stay' => fillOnUndefined($params, 'max_stay'),
                "description" => !empty($description) ? json_encode($description) : null,
                "status" => fillOnUndefined($params, "status", 1),
                "created_by" => fillOnUndefined($params, "user_id"),
                "updated_by" => fillOnUndefined($params, "user_id")
            ];


            $userCreateResult = $this->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new ApiErrorException($userCreateResult['message']);
            }
            $userData = $userCreateResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function addPropertyRoomRateWithInclusion($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            DB::beginTransaction();

            $validateData = [
                'property_id' => fillOnUndefined($params, 'property_id'),
                'name' => trim(fillOnUndefined($params, 'name')),
                'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
                /*'min_stay' => fillOnUndefined($params, 'min_stay'),
                'max_stay' => fillOnUndefined($params, 'max_stay'),*/
                'facts' => fillOnUndefined($params, 'facts'),

            ];
            $validationResult = $this->propertyRoomRateAddWithInclusionValidator->validate($validateData);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }


            $description = [];
            foreach (fillOnUndefined($params, "description", []) as $desc) {
                $description[$desc['language_code']] = $desc['description'];
            }


            $insertData = [
                'property_id' => fillOnUndefined($validateData, 'property_id'),
                'name' => fillOnUndefined($validateData, 'name'),
                'accommodation_type' => fillOnUndefined($validateData, 'accommodation_type'),
                "description" => !empty($description) ? json_encode($description) : null,
                /*'min_stay' => fillOnUndefined($validateData, 'min_stay'),
                'max_stay' => fillOnUndefined($validateData, 'max_stay'),*/
                "status" => fillOnUndefined($validateData, "status", 1),
                "created_by" => fillOnUndefined($params, "user_id"),
                "updated_by" => fillOnUndefined($params, "user_id")
            ];


            $userCreateResult = $this->propertyRoomRateRepository->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

            $roomRateData = $userCreateResult['data'];
            $insertData = [];
            foreach ($params["facts"] as $fact) {
                $insertData[] = [
                    'room_rate_id' => $roomRateData['id'],
                    'fact_id' => $fact,
                    'status' => 1,
                    "created_by" => fillOnUndefined($params, "user_id"),
                    "updated_by" => fillOnUndefined($params, "user_id"),
                    'created_at' => Carbon::now()->timestamp,
                    'updated_at' => Carbon::now()->timestamp,
                ];
            }


            $userCreateResult = $this->propertyRoomRateInclusionMappingRepository->insert($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

            $userData = $userCreateResult["data"];
            $response = [
                'status' => true,
                'data' => $roomRateData,
            ];

            DB::commit();
        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            DB::rollBack();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            DB::rollBack();
        }

        return output($response);
    }

    public function getPropertyRoomRates($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $getApplicationLanguages = $this->languageService->getApplicationLanguages();
            if ($getApplicationLanguages['status'] != 'success') {
                throw new ApiErrorException($getApplicationLanguages['message']);
            }
            $applicationLanguages = $getApplicationLanguages['data'];

            $criteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']]
                ],
                'with' => ['propertyRoomRateInclusionMapping.propertyFact', 'propertyRoomRateAccommodation']
            ];

            $data = $this->propertyRoomRateRepository->findByCriteria($criteria, ['id', 'property_id', 'name', 'description', 'accommodation_type', 'min_stay', 'max_stay']);

            $return = [];
            foreach ($data as $item) {
                $dataRow = $item;
                if ($item['property_room_rate_inclusion_mapping']) {
                    $factList = collect($item['property_room_rate_inclusion_mapping'])->map(function ($value) {
                        return $value['property'] = [
                            'room_rate_id' => $value['room_rate_id'],
                            'fact_id' => $value['fact_id'],
                            'name' => $value['property_fact']['name'],
                            'icon' => $value['property_fact']['icon'],
                            'language_key' => $value['property_fact']['language_key']
                        ];

                    })->toArray();
                    $dataRow['property_room_rate_inclusion_mapping'] = $factList;
                }


                $descriptionLangContents = json_decode($dataRow['description'], 1);
                $responseLangDescription = [];
                foreach ($applicationLanguages as $applicationLanguage) {
                    $langKey = $applicationLanguage['code'];
                    $responseLangDescription[] = [
                        'language_code' => $langKey,
                        'description' => isset($descriptionLangContents[$langKey]) ? $descriptionLangContents[$langKey] : null
                    ];
                }

                $dataRow['description'] = $responseLangDescription;

                $return[] = $dataRow;
            }
            $response = [
                'status' => true,
                'data' => $return,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function updatePropertyRoomRate($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            DB::beginTransaction();
            $validationResult = $this->propertyRoomRateUpdateValidator->validate($params);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $description = [];
            foreach (fillOnUndefined($params, "description", []) as $desc) {
                $description[$desc['language_code']] = $desc['description'];
            }

            $updateData =
                [
                    'property_id' => fillOnUndefined($params, 'property_id'),
                    'name' => fillOnUndefined($params, 'name'),
                    'accommodation_type' => fillOnUndefined($params, 'accommodation_type'),
                    'min_stay' => fillOnUndefined($params, 'min_stay'),
                    "description" => !empty($description) ? json_encode($description) : null,
                    "updated_by" => fillOnUndefined($params, "user_id"),
                ];

            if (isset($params['status'])) {
                $updateData['status'] = fillOnUndefined($params, "status", 0);
            }

            $criteria = [
                'criteria' => [
                    ['field' => 'room_rate_id', 'condition' => '=', 'value' => $params['id']]
                ]
            ];

            $data = $this->propertyRoomRateInclusionMappingRepository->findByCriteria($criteria, ['id']);
            $deleteThis = collect($data)->keyBy('id')->keys()->toArray();

            if ($deleteThis) {
                $deleteThisArray = $this->propertyRoomRateInclusionMappingRepository->destroy($deleteThis);
                if ($deleteThisArray['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $updateResult = $this->update($params['id'], $updateData);
            if ($updateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $updateResult["data"];

            if (!empty($params["facts"])) {
                $insertData = [];
                foreach ($params["facts"] as $fact) {
                    if ($fact) {
                        $insertData[] = [
                            'room_rate_id' => $params['id'],
                            'fact_id' => $fact,
                            'status' => 1,
                            "created_by" => fillOnUndefined($params, "user_id"),
                            "updated_by" => fillOnUndefined($params, "user_id"),
                            'created_at' => Carbon::now()->timestamp,
                            'updated_at' => Carbon::now()->timestamp,
                        ];
                    }
                }
                $userCreateResult = $this->propertyRoomRateInclusionMappingRepository->insert($insertData);
                if ($userCreateResult['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $response = [
                'status' => true,
                'data' => $userData,
            ];

            DB::commit();
        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            DB::rollBack();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            DB::rollBack();
        }

        return output($response);
    }

    public function deletePropertyRoomRate($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->propertyRoomRateDeleteValidator->validate($params);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $updateData =
                [
                    'status' => 0,
                    "updated_by" => fillOnUndefined($params, "user_id")
                ];

            $updateResult = $this->update($params['id'], $updateData);
            if ($updateResult['status'] != 'success') {
                throw new ApiErrorException($updateResult['message']);
            }
            $userData = $updateResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function getPropertyAccommodationTypes($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $requestFact = [
                'property_id' => fillOnUndefined($params, 'property_id'),
                'sub_category_id' => 9,
            ];
            $subCategoryFacts = $this->propertyFactService->getSubCategoryFacts($requestFact);
            if ($subCategoryFacts['status'] != 'success') {
                throw new ApiErrorException($subCategoryFacts['message']);
            }
            // todo burada propertnin sahip olduğu tüm accommodation geliyordu
            // $propertyAccommodationList = collect($subCategoryFacts['data'])->where('is_selected', '=', true)->values()->toArray();
            $propertyAccommodationList = $subCategoryFacts['data'];
            $response = [
                'status' => true,
                'data' => $propertyAccommodationList,
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

}
