<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyRoomPhotoMapping\PropertyRoomPhotoMappingRepository;
use App\Core\Validator\PropertyRoom\PropertyRoomPhotoMappingAddValidator;
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 PropertyRoomPhotoMappingService
{

    private $languageService;
    private $propertyRoomPhotoMappingRepository;
    private $applicationCacheService ;
    private $propertyRoomPhotoMappingAddValidator;


    public function __construct(
        PropertyRoomPhotoMappingRepository $propertyRoomPhotoMappingRepository,
        LanguageService $languageService,
        PropertyRoomPhotoMappingAddValidator $propertyRoomPhotoMappingAddValidator,
        ApplicationCacheService $applicationCacheService

    )
    {
        $this->languageService = $languageService;
        $this->propertyRoomPhotoMappingRepository = $propertyRoomPhotoMappingRepository;
        $this->applicationCacheService = $applicationCacheService;
        $this->propertyRoomPhotoMappingAddValidator = $propertyRoomPhotoMappingAddValidator;

    }

    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->propertyRoomPhotoMappingRepository->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->propertyRoomPhotoMappingRepository->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 deleteById($param){

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

    }

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

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

            $addPropertyRoomPhotoMapping = [];
            $addPhotoList = collect($params['property_room_photo'])
                ->where('is_selected' ,'=', true);
            $addPhotoIds = $addPhotoList->keyBy("id")->keys()->toArray();

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

            $removePhotoIds = $removePhotoList->keyBy("id")->keys()->toArray();

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

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

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

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

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

            $response = $this->propertyRoomPhotoMappingRepository->createAll($addPropertyRoomPhotoMapping);

            if($removePhotoIds){

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

                $deletePropertyRoomPhotoMapping = $this->propertyRoomPhotoMappingRepository->findByCriteria($findCriteria);

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

                if($deleteThisIds){
                    $this->propertyRoomPhotoMappingRepository->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 destroy($params){

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

        try {
            $deleteCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'photo_id', 'condition' => '=', 'value' => $params['photo_id']],
                ]
            ];

            $deleteData = $this->propertyRoomPhotoMappingRepository->findByCriteria($deleteCriteria, ['id']);
            $deleteData = $deleteData ? $deleteData : [] ;
            if($deleteData){
                $deleteIds = array_column($deleteData, 'id') ;
                $destroyResult = $this->propertyRoomPhotoMappingRepository->destroy($deleteIds);
                if ($destroyResult['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

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

        } 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);


    }

}
