<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyWebRoomMapping\PropertyWebRoomMappingRepository;
use App\Core\Repository\PropertyRoom\PropertyRoomRepository;

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

class PropertyWebRoomMappingService
{

    private $propertyWebRoomMappingRepository;


    public function __construct(
        PropertyWebRoomMappingRepository $propertyWebRoomMappingRepository,
        PropertyRoomRepository  $propertyRoomRepository
    )
    {
        $this->propertyWebRoomMappingRepository = $propertyWebRoomMappingRepository;
        $this->propertyRoomRepository = $propertyRoomRepository;
    }

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

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

        try {
            $data = $this->propertyWebRoomMappingRepository->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 createPropertyWebRoomMapping($param = []){

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            // TODO validation yazılmalı!

            $propertyWebMenuMappingResult = $this->propertyWebRoomMappingRepository->insert($param);

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

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

        } 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 getPropertyWebRoomMapping($params, $select = ['*']){

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            $return = [];
            $searchCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'property_web_id', 'condition' => '=', 'value' => $params['property_web_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ]
            ];

            $searchResult = $this->select($searchCriteria, $select);

            if($searchResult['status'] != 'success'){
                throw new ApiErrorException($searchResult['message']);
            }

            $return = $searchResult['data'];

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

        return output($response);

    }

    public function updatePropertyWebRooomMapping($params = []){

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            $return  = [];

            $getDeletePropertyWebRoomRequest =  [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],
                    ['field' => 'property_web_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_web_id')]
                ]
            ];

            $status = null;
            if($params['action'] === "publish"){
                $status = 1;
            }else if($params['action'] === "preview"){

                $getDeletePropertyWebRoomRequest['criteria'][] = ['field' => 'status', 'condition' => '=', 'value' => 2];
                $status = 2;
            }

            $deleteWebRoomId = $this->propertyWebRoomMappingRepository->findByCriteria($getDeletePropertyWebRoomRequest, ['id']) ;
            $deleteWebRoomId = array_column($deleteWebRoomId, 'id') ;

            if (!empty($deleteWebRoomId)) {
                $destroyStatus = $this->propertyWebRoomMappingRepository->destroy($deleteWebRoomId);
                if ($destroyStatus['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $myWebRooms = !empty($params['rooms']) ? $params['rooms'] : [];


            $propertyRoomCheckCriteria =  [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'property_id')],
                ],
                'whereIn' => [
                    ['field' => 'id', 'value' => $myWebRooms]
                ]
            ];

            $propertyRoomCheck = $this->propertyRoomRepository->findByCriteria($propertyRoomCheckCriteria, ['id']) ;
            $myWebRooms = $params['rooms'];

            if(count($propertyRoomCheck) != count($params['rooms'])) {
                throw new Exception('Different room type count.');
            }

            $createPropertyWebRoomMappingData = [];
            foreach ($myWebRooms as $key => $myWebRoom){

                $createPropertyWebRoomMappingData[$key]['property_id'] = fillOnUndefined($params,'property_id');
                $createPropertyWebRoomMappingData[$key]['property_web_id'] = fillOnUndefined($params,'property_web_id');
                $createPropertyWebRoomMappingData[$key]['property_room_id'] = $myWebRoom;
                $createPropertyWebRoomMappingData[$key]['status'] = $status;
                $createPropertyWebRoomMappingData[$key]['created_by'] = fillOnUndefined($params, 'user_id');
                $createPropertyWebRoomMappingData[$key]['updated_by'] = fillOnUndefined($params, 'user_id');
                $createPropertyWebRoomMappingData[$key]['created_at'] = time();
                $createPropertyWebRoomMappingData[$key]['updated_at'] = time();
            }

            $propertyWebRoomMappingResult = $this->createPropertyWebRoomMapping($createPropertyWebRoomMappingData);
            if ($propertyWebRoomMappingResult['status'] != 'success'){
                throw new ApiErrorException($propertyWebRoomMappingResult['message']);
            }

            $response = ['statusCode' => 200, 'status' => true, 'message' => '', 'data' => ['property_web_room_mapping' => $return ] ];

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

        return output($response);
    }

}
