<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyRoomFactMapping\PropertyRoomFactMappingRepository;
use App\Core\Validator\PropertyRoom\PropertyRoomFactMappingAddValidator;
use App\Core\Service\LanguageService ;
use App\Core\Service\ApplicationCacheService ;

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

class PropertyRoomFactMappingService
{

    private $languageService;
    private $propertyRoomFactMappingRepository;
    private $applicationCacheService ;
    private $propertyRoomFactMappingAddValidator;


    public function __construct(
        PropertyRoomFactMappingRepository $propertyRoomFactMappingRepository,
        LanguageService $languageService,
        PropertyRoomFactMappingAddValidator $propertyRoomFactMappingAddValidator,
        ApplicationCacheService $applicationCacheService

    )
    {
        $this->languageService = $languageService;
        $this->propertyRoomFactMappingRepository = $propertyRoomFactMappingRepository;
        $this->applicationCacheService = $applicationCacheService;
        $this->propertyRoomFactMappingAddValidator = $propertyRoomFactMappingAddValidator;

    }

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

                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];


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

            $response['status'] = 1;
            $response['data'] = $userData;


        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $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];

        try {

            $data = $this->propertyRoomFactMappingRepository->findByCriteria($param, $column);
            $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->propertyRoomFactMappingRepository->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 deleteById($param){

        $userCreateResult = $this->propertyRoomFactMappingRepository->delete();

    }

    public function removePropertyRoomFactMapping($param = [])
    {

    //Todo: validations

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


            //Todo: cache datası yeni bir fonksiyon yapılıp herkes oradan geçekecek

            $cacheInfo = $this->applicationCacheService->getApplicationCache([]);
            if($cacheInfo['status'] != 'success'){
                throw new ApiErrorException(lang('Cache Required'));
            }
            $userData = $cacheInfo['data'] ;


            $factIds = [];
            foreach ($param["facts"] as $fact){
                $factIds[] = $fact["id"];
            }


            $findCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $userData['property_id']],
                ],
                "whereIn"=>
                    [
                        ["field"=>"fact_id","value"=>$factIds]
                    ]
            ];

            $factMappingDatas = $this->propertyRoomFactMappingRepository->findByCriteria($findCriteria);
            if (!$factMappingDatas) {
                throw new ApiErrorException(lang('Fact cannot loaded'));
            }


            // Todo: gönderilen idler ile veritabanında bulunan idler karşılaştırılacak. Uyumsuz data varsa hiç bir şey silinmeden error throw edilecek

            $deleteRowIds = [];
            foreach ($factMappingDatas as $factMappingData){
                $ids = [];
                $ids[] = $factMappingData["id"];
                $delete = $this->propertyRoomFactMappingRepository->deleteById($ids);
                if (!$delete) {
                    throw new ApiErrorException(lang('cannot delete fact'));
                }

            }
            $response['status'] = 1;
            $response['data'] = [];



            }
            catch (ApiErrorException $e) {
                $response['status'] = 0;
                $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 addPropertyRoomFactMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try
        {
            $propertyId       = $params['property_id'];
            $userId           = $params['user_id'];
            $propertyFactData = $params['data'];

            $addPropertyRoomFactMapping = [];
            foreach ($propertyFactData as $key => $param)
            {
                $addPropertyRoomFactMapping[] =
                    [
                        'property_id' => $propertyId,
                        'fact_id' => fillOnUndefined($param, 'id'),
                        'created_by' => $userId,
                        'updated_by' => $userId,
                    ];
            }

            //TODO : $addPropertyRoomFactMapping için validation işlemleri yapılacaktır.(property_id ve fact id inin unique doğrulamasına bakılması unutulmamalı )
            $response = $this->propertyRoomFactMappingRepository->createAll($addPropertyRoomFactMapping);

            if ($response['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

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

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

        return output($response);
    }

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

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

            $addPropertyRoomFactMapping = [];
            $addFactList = collect($params['property_room_fact'])
                ->where('is_selected' ,'=', true);
            $addFactIds = $addFactList->keyBy("id")->keys()->toArray();

            $removeFactList = collect($params['property_room_fact'])
                ->where('is_selected' ,'=', false);

            $removeFactIds = $removeFactList->keyBy("id")->keys()->toArray();

            $checkPropertyMappingRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'room_id', 'condition' => '=', 'value' => $params['room_id']],
                ],
                "whereIn" => [
                    ["field" => "fact_id", "value" => $addFactIds]
                ]
            ];
            $checkPropertyMappingResponse = $this->select($checkPropertyMappingRequest,['id', 'property_id', 'fact_id']);

            if($checkPropertyMappingResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Mapping data not loaded'));
            }
            $checkPropertyMappingCollect = collect($checkPropertyMappingResponse['data']);

            foreach ($addFactList->toArray() as $key => $param)
            {

                if(
                    !$checkPropertyMappingCollect->where('property_id', '=', $params['property_id'])
                        ->where('fact_id', '=', $param['id'])
                        ->first()
                ){

                    $addPropertyRoomFactMapping[] =
                        [
                            'property_id' => $params['property_id'],
                            'room_id' => $params['room_id'],
                            'fact_id' => fillOnUndefined($param, 'id'),
                            'created_by' => $params['user_id'],
                            'updated_by' => $params['user_id'],
                        ];
                }
            }

            $response = $this->propertyRoomFactMappingRepository->createAll($addPropertyRoomFactMapping);


            if($removeFactIds){

                $findCriteria = [
                    'criteria' => [
                        ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                        ['field' => 'room_id', 'condition' => '=', 'value' => $params['room_id']],
                    ],
                    "whereIn" =>
                        [
                            ["field" => "fact_id", "value" => $removeFactIds]
                        ]
                ];

                $deletePropertyRoomFactMapping = $this->propertyRoomFactMappingRepository->findByCriteria($findCriteria);

                $deleteThisIds = [];
                foreach ($deletePropertyRoomFactMapping as $deleteThisItem){
                    $deleteThisIds[] = $deleteThisItem['id'];
                }

                if($deleteThisIds){
                    $this->propertyRoomFactMappingRepository->deleteById($deleteThisIds);

                }
            }

            if ($response['status'] != 'success') {
                throw new ApiErrorException(lang('Data is not added')) ;
            }

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

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

        return output($response);
    }

    public function updatePropertyRoomFactIsFeature($params = []){

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

            /*$validationResult = $this->propertyRoomFactMappingAddValidator->validate($params);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }*/


            $checkPropertyMappingRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'room_id', 'condition' => '=', 'value' => $params['room_id']],
                    ['field' => 'fact_id', 'condition' => '=', 'value' => $params['fact_id']]
                ],
                'firstRow' => true
            ];

            $checkPropertyMappingResponse = $this->select($checkPropertyMappingRequest,['id', 'property_id', 'room_id', 'fact_id']);

            if($checkPropertyMappingResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Mapping data not loaded'));
            }

            if(empty($checkPropertyMappingResponse['data'])){
                throw new ApiErrorException(lang('Mapping data not found'));
            }

            $propertyFactMappingId = $checkPropertyMappingResponse['data']['id'];

            $updateData = [
                'is_feature' => $params['is_feature'],
                'updated_by' => $params['user_id']
            ];

            $updateResult = $this->update($propertyFactMappingId, $updateData);

            if ($updateResult['status'] != 'success') {
                throw new ApiErrorException(lang('Mapping Fact data is not updated.'));
            }


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

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

        return output($response);

    }


}
