<?php

namespace App\Core\Service;

use App\Core\Repository\OfferRoomMapping\OfferRoomMappingRepository;
use App\Core\Validator\OfferRoomMapping\OfferRoomMappingCreateValidator;
use App\Core\Validator\OfferRoomMapping\OfferRoomMappingAddValidator;
use App\Core\Service\PropertyRoomService;

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

class OfferRoomMappingService
{

    private $offerRoomMappingRepository;
    private $offerRoomMappingCreateValidator;
    private $roomMappingAddValidator;
    private $propertyRoomService;


    public function __construct(

        OfferRoomMappingRepository $offerRoomMappingRepository,
        OfferRoomMappingCreateValidator $offerRoomMappingCreateValidator,
        OfferRoomMappingAddValidator $roomMappingAddValidator,
        PropertyRoomService $propertyRoomService
    )
    {
        $this->offerRoomMappingRepository = $offerRoomMappingRepository;
        $this->offerRoomMappingCreateValidator = $offerRoomMappingCreateValidator;
        $this->roomMappingAddValidator = $roomMappingAddValidator;
        $this->propertyRoomService = $propertyRoomService;
    }

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

            $validationResult = $this->offerRoomMappingCreateValidator->validate($param);

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

            $insertData =
                [


                    "offer_id" => fillOnUndefined($param, "offer_id"),
                    "property_room_id" => fillOnUndefined($param, "property_room_id"),

                    "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->offerRoomMappingRepository->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->offerRoomMappingRepository->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->offerRoomMappingRepository->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->offerRoomMappingRepository->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 insertRoomMapping($param = [])
    {

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

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

            $propertyRoomCheckParam = [
                'room_ids' => $param['room_mapping'],
                'property_id' => $param['property_id']
            ];
            $propertyRoomCheck  = $this->propertyRoomService->checkPropertyRoomMapping($propertyRoomCheckParam) ;
            if($propertyRoomCheck['status'] != 'success'){
                throw new ApiErrorException($propertyRoomCheck['message']);
            }

            $insertDataArray = [] ;
            foreach ($param['room_mapping'] as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_room_id" => $item,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $insertResult = $this->offerRoomMappingRepository->createAll($insertDataArray);
            if ($insertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $insertResult["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 updateRoomMapping($param = [], $offerRoomMapping)
    {

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

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

            $insertThisIds = array_diff($param['room_mapping'], $offerRoomMapping);
            $deleteThisIds = array_diff($offerRoomMapping, $param['room_mapping']);
            $responseDeleteIds = $deleteThisIds;

            $insertDataArray = [] ;
            foreach ($insertThisIds as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_room_id" => $item,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $insertResult = $this->offerRoomMappingRepository->createAll($insertDataArray);
            if ($insertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

            $requestData = [
                'criteria' => [
                    ['field' => 'offer_id', 'condition' => '=', 'value' => fillOnUndefined($param, "offer_id")],
                ],
                "whereIn" =>
                    [
                        ["field" => "property_room_id", "value" => $deleteThisIds]
                    ]
            ];
            $eraseMappingData = $this->offerRoomMappingRepository->findByCriteria($requestData,['id']);
            $eraseMappingData = $eraseMappingData ? $eraseMappingData : [] ;
            $deleteThisIds = collect($eraseMappingData)->keyBy('id')->keys()->all();

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


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

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

    }


}
