<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyRoomRateMapping\PropertyRoomRateMappingRepository;
use App\Core\Repository\PropertyRoomRateChannelMapping\PropertyRoomRateChannelMappingRepository;
use App\Core\Repository\PropertyRoomRateMappingSetup\PropertyRoomRateMappingSetupRepository;
use App\Core\Validator\PropertyRoomRateMapping\PropertyRoomRateMappingAddValidator;
use App\Core\Validator\PropertyRoomRateMapping\PropertyRoomRateMappingUpdateValidator;
use App\Core\Validator\PropertyRoomRateMapping\PropertyRoomRateMappingDeleteValidator;
use App\Core\Validator\PropertyRoomRateMapping\PropertyRoomRateMappingAddWithSetupValidator;
use App\Core\Validator\PropertyRoomRateMapping\PropertyRoomRateMappingSetStatusValidator;
use App\Core\Validator\PropertyRoomRateMapping\PropertyRoomRateMappingConnectedValidator;

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

class PropertyRoomRateMappingService
{

    private $propertyRoomRateMappingRepository;
    private $propertyRoomRateMappingSetupRepository;
    private $propertyRoomRateMappingAddValidator;
    private $propertyRoomRateMappingUpdateValidator;
    private $propertyRoomRateMappingDeleteValidator;
    private $propertyRoomRateMappingAddWithSetupValidator;
    private $propertyRoomRateMappingSetStatusValidator;
    private $propertyRoomRateChannelMappingRepository;


    public function __construct(

        PropertyRoomRateMappingRepository $propertyRoomRateMappingRepository,
        PropertyRoomRateMappingSetupRepository $propertyRoomRateMappingSetupRepository,
        PropertyRoomRateMappingUpdateValidator $propertyRoomRateMappingUpdateValidator,
        PropertyRoomRateMappingDeleteValidator $propertyRoomRateMappingDeleteValidator,
        PropertyRoomRateMappingAddWithSetupValidator $propertyRoomRateMappingAddWithSetupValidator,
        PropertyRoomRateMappingSetStatusValidator $propertyRoomRateMappingSetStatusValidator,
        PropertyRoomRateChannelMappingRepository $propertyRoomRateChannelMappingRepository,
        PropertyRoomRateMappingAddValidator $propertyRoomRateMappingAddValidator,
        PropertyRoomRateMappingConnectedValidator $propertyRoomRateMappingConnectedValidator
    )
    {

        $this->propertyRoomRateMappingRepository = $propertyRoomRateMappingRepository;
        $this->propertyRoomRateMappingSetupRepository = $propertyRoomRateMappingSetupRepository;
        $this->propertyRoomRateMappingAddValidator = $propertyRoomRateMappingAddValidator;
        $this->propertyRoomRateMappingUpdateValidator = $propertyRoomRateMappingUpdateValidator;
        $this->propertyRoomRateMappingDeleteValidator = $propertyRoomRateMappingDeleteValidator;
        $this->propertyRoomRateMappingAddWithSetupValidator = $propertyRoomRateMappingAddWithSetupValidator;
        $this->propertyRoomRateMappingSetStatusValidator = $propertyRoomRateMappingSetStatusValidator;
        $this->propertyRoomRateChannelMappingRepository = $propertyRoomRateChannelMappingRepository;
        $this->propertyRoomRateMappingConnectedValidator = $propertyRoomRateMappingConnectedValidator;


    }

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

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

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

            $insertData =
                [
                    'room_id' => fillOnUndefined($params, 'room_id', 0),
                    'room_rate_id' => fillOnUndefined($params, 'room_rate_id', 0),
                    'description' => fillOnUndefined($params, 'description', ''),
                    'rack_rate' => fillOnUndefined($params, 'rack_rate', 0),
                    'included_occupancy' => fillOnUndefined($params, 'included_occupancy', 0),
                    "status" => fillOnUndefined($params, "status", 1),
                    "created_by" => fillOnUndefined($params, "created_by", 0),
                    "updated_by" => fillOnUndefined($params, "updated_by", 0),
                ];

            $userCreateResult = $this->propertyRoomRateMappingRepository->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];

        try {

            $data = $this->propertyRoomRateMappingRepository->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->propertyRoomRateMappingRepository->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->propertyRoomRateMappingRepository->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 addPropertyRoomRateMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $checkRoomRateMappingRequest = [
                'criteria' => [
                    ['field' => 'room_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'room_id')],
                    ['field' => 'room_rate_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'room_rate_id')],
                ],
            ];

            $checkRoomRateMapping = $this->propertyRoomRateMappingRepository->findByCriteria($checkRoomRateMappingRequest);
            $checkRoomRateMapping = $checkRoomRateMapping ? $checkRoomRateMapping : null;

            if ($checkRoomRateMapping) {

                throw new ApiErrorException('This data was previously added');
            }
            $insertData =
                [
                    'room_id' => fillOnUndefined($params, 'room_id'),
                    'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
                    'description' => fillOnUndefined($params, 'description'),
                    'rack_rate' => fillOnUndefined($params, 'rack_rate'),
                    'included_occupancy' => fillOnUndefined($params, 'included_occupancy'),
                    "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 addPropertyRoomRateMappingWithSetup($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            DB::beginTransaction();

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

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

            $checkRoomRateMappingRequest = [
                'criteria' => [
                    ['field' => 'room_rate_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'room_rate_id')],
                ],
            ];

            $checkRoomRateMapping = $this->propertyRoomRateMappingRepository->findByCriteria($checkRoomRateMappingRequest);
            $checkRoomRateMapping = $checkRoomRateMapping ? $checkRoomRateMapping : [];
            $oldRoomRateRooms = collect($checkRoomRateMapping)->keyBy('room_id')->keys()->toArray();
            $insertRoomRateMappingSetupData = [];
            foreach ($params['room_id'] as $room) {

                if (in_array($room, $oldRoomRateRooms)) {
                    throw new ApiErrorException('This data was previously added');
                }
                $insertRoomRateMappingData =
                    [
                        'room_id' => $room,
                        'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
                        'rack_rate' => fillOnUndefined($params, 'rack_rate'),
                        'included_occupancy' => fillOnUndefined($params, 'included_occupancy'),
                        "status" => fillOnUndefined($params, "status", 1),
                        "created_by" => fillOnUndefined($params, "user_id"),
                        "updated_by" => fillOnUndefined($params, "user_id")
                    ];

                $insertRoomRateMappingResult = $this->propertyRoomRateMappingRepository->create($insertRoomRateMappingData);
                if ($insertRoomRateMappingResult['status'] != 'success') {
                    throw new ApiErrorException($insertRoomRateMappingResult['message']);
                }

                /* $insertRoomRateMapping = $insertRoomRateMappingResult['data'];

                 foreach ($params['room_rate_mapping_setup'] as $mappingSetup){
                     $insertRoomRateMappingSetupData[] = [
                         'room_rate_mapping_id' => $insertRoomRateMapping['id'] ,
                         'setup_type' => $mappingSetup['setup_type'],
                         'value_type' => $mappingSetup['value_type'],
                         'value' => $mappingSetup['value'],
                         'status' => 1,
                         "created_by" => fillOnUndefined($params, "user_id") ,
                         "updated_by" => fillOnUndefined($params, "user_id") ,
                         'created_at' => Carbon::now()->timestamp,
                         'updated_at' => Carbon::now()->timestamp,
                     ];
                 }*/


            }

            /*  $insertRoomRateMappingSetupResult = $this->propertyRoomRateMappingSetupRepository->insert($insertRoomRateMappingSetupData);
              if ($insertRoomRateMappingSetupResult['status'] != 'success') {
                 throw new Exception('api-unknown_error');
              }*/


            $response = [
                'status' => true,
                'data' => null,
            ];
            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 getPropertyRoomRateMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $criteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'room_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'room_id')],

                ],
                'with' => ['propertyRoomRate', 'propertyRoomRateChannel']
            ];

            $data = $this->propertyRoomRateMappingRepository->findByCriteria($criteria, ['id', 'room_id', 'room_rate_id', 'description', 'rack_rate', 'included_occupancy']);

            $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 getPropertyRoomRateMappingConnected($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $criteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'room_rate_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'room_rate_id')],

                ],
                'with' => ['propertyRoom']
            ];

            $relationalRoomsByRate = $this->propertyRoomRateMappingRepository->findByCriteria($criteria, ['id', 'room_id', 'room_rate_id']);
            $relationalRoomIds = pickItemFromArray('room_id', $relationalRoomsByRate);


            $criteriaRoomRate = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],
                'whereIn' =>
                    [
                        ['field' => 'room_id', "value" => $relationalRoomIds]
                    ],
                'with' => ['propertyRoom.propertyRoomType', 'propertyRoomRate']
            ];

            $roomRates = $this->propertyRoomRateMappingRepository->findByCriteria($criteriaRoomRate);


            $connectedValue = [];
            foreach ($roomRates as $roomRate) {
                if ($roomRate['room_rate_id'] == $params['room_rate_id'] && !empty($roomRate['connected_rate_id'])) {

                    $connectedValue[$roomRate['room_id']] = [
                        'connected_rate_id' => $roomRate['connected_rate_id'],
                        'is_affected_price' => $roomRate['is_affected_price'],
                        'affect_price_action_type' => $roomRate['affect_price_action_type'],
                        'affect_price_type' => $roomRate['affect_price_type'],
                        'affect_price_value' => $roomRate['affect_price_value'],
                    ];

                    continue;
                }
            }

            $roomRateList = [];
            foreach ($roomRates as $roomRate) {

                if ($roomRate['room_rate_id'] == $params['room_rate_id']) {
                    continue;
                }

                $roomRateList[$roomRate['room_id']]['room'] = [
                    'room_id' => $roomRate['room_id'],
                    'room_name' => $roomRate['property_room']['name'],
                    'room_type' => $roomRate['property_room']['property_room_type']['name'],
                    'status' => $roomRate['property_room']['status'],
                ];

                if (isset($connectedValue[$roomRate['room_id']]) && $connectedValue[$roomRate['room_id']]['connected_rate_id'] == $roomRate['room_rate_id']) {
                    $roomRateList[$roomRate['room_id']]['rates'][] = [
                        'id' => $roomRate['id'],
                        'room_rate_id' => $roomRate['room_rate_id'],
                        'room_rate_name' => $roomRate['property_room_rate']['name'],
                        'connected_rate_id' => $connectedValue[$roomRate['room_id']]['connected_rate_id'],
                        'is_affected_price' => $connectedValue[$roomRate['room_id']]['is_affected_price'],
                        'affect_price_action_type' => $connectedValue[$roomRate['room_id']]['affect_price_action_type'],
                        'affect_price_type' => $connectedValue[$roomRate['room_id']]['affect_price_type'],
                        'affect_price_value' => $connectedValue[$roomRate['room_id']]['affect_price_value'],
                    ];
                } else {
                    $roomRateList[$roomRate['room_id']]['rates'][] = [
                        'id' => $roomRate['id'],
                        'room_rate_id' => $roomRate['room_rate_id'],
                        'room_rate_name' => $roomRate['property_room_rate']['name'],
                        'connected_rate_id' => null,
                        'is_affected_price' => null,
                        'affect_price_action_type' => null,
                        'affect_price_type' => null,
                        'affect_price_value' => null,
                    ];
                }

            }

            $roomRateList = array_values($roomRateList);

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

        } 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 syncPropertyRoomRateMappingConnected($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];

        DB::beginTransaction();

        try {

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

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


            $criteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'room_rate_id', 'condition' => '=', 'value' => fillOnUndefined($params, 'room_rate_id')],

                ],
            ];

            $relationalRoomsByRate = $this->propertyRoomRateMappingRepository->findByCriteria($criteria);
            $relationalRoomIds = pickItemFromArray('room_id', $relationalRoomsByRate);

            //ResetRoomRateConnectParam
            foreach ($relationalRoomsByRate as $roomRate) {

                $resetRoomRateConnectParam = [
                    'connected_rate_id' => null,
                    'is_affected_price' => null,
                    'affect_price_action_type' => null,
                    'affect_price_type' => null,
                    'affect_price_value' => null,
                ];

                $this->propertyRoomRateMappingRepository->update($roomRate['id'], $resetRoomRateConnectParam);

                foreach ($params['connected_room_rate'] as $connectedRoomRate) {

                    if ($roomRate['room_id'] == $connectedRoomRate['room_id'] && $connectedRoomRate['room_rate_id']) {

                        $roomRateConnectParam = [
                            'connected_rate_id' => fillOnUndefined($connectedRoomRate, 'room_rate_id'),
                            'is_affected_price' => fillOnUndefined($connectedRoomRate, 'is_affected_price'),
                            'affect_price_action_type' => fillOnUndefined($connectedRoomRate, 'affect_price_action_type'),
                            'affect_price_type' => fillOnUndefined($connectedRoomRate, 'affect_price_type'),
                            'affect_price_value' => fillOnUndefined($connectedRoomRate, 'affect_price_value'),
                        ];

                        $roomRateConnect = $this->propertyRoomRateMappingRepository->update($roomRate['id'], $roomRateConnectParam);

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

                    }
                }

            }

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

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

        if ($response['status']) {
            DB::commit();
        } else {
            DB::rollBack();
        }

        return output($response);
    }

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

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

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $updateData =
                [
                    'room_id' => fillOnUndefined($params, 'room_id'),
                    'room_rate_id' => fillOnUndefined($params, 'room_rate_id'),
                    'description' => fillOnUndefined($params, 'description'),
                    'rack_rate' => fillOnUndefined($params, 'rack_rate'),
                    'included_occupancy' => fillOnUndefined($params, 'included_occupancy'),
                    "updated_by" => fillOnUndefined($params, "user_id"),
                ];

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


            $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 deletePropertyRoomRateMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->propertyRoomRateMappingDeleteValidator->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 setStatusPropertyRoomRateMapping($params = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            DB::beginTransaction();

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

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

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

            if ($params['is_selected'] == false) {
                $updateCriteria = [
                    'criteria' => [
                        ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                        ['field' => 'room_rate_mapping_id', 'condition' => '=', 'value' => $params['room_rate_mapping_id']],
                    ]
                ];

                $updateData = [
                    "status" => 0,
                    "updated_by" => $params['user_id']
                ];

                $updateResult = $this->propertyRoomRateChannelMappingRepository->updateWhere($updateCriteria, $updateData);
                if ($updateResult['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }


            $response = [
                'status' => true,
                'data' => null,
            ];
            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);
    }


}
