<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyRoomBed\PropertyRoomBedRepository;
use App\Core\Validator\PropertyRoomBed\PropertyRoomBedAddValidator;



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

class PropertyRoomBedService
{

    private $propertyRoomBedRepository;
    private $propertyRoomBedAddValidator;


    public function __construct(

        PropertyRoomBedRepository $propertyRoomBedRepository,
        PropertyRoomBedAddValidator $propertyRoomBedAddValidator
    )
    {
        $this->propertyRoomBedRepository = $propertyRoomBedRepository;
        $this->propertyRoomBedAddValidator = $propertyRoomBedAddValidator;
    }

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

            $insertData =
                [
                    'room_id' => fillOnUndefined($params, 'room_id', 0),
                    'bed_group' => fillOnUndefined($params, 'bed_group', 0),
                    'count' => fillOnUndefined($params, 'count', 0),
                    'bed_type_id' => fillOnUndefined($params, 'bed_type_id', 0),
                    "status" => fillOnUndefined($params, "status", 1),
                    "created_by" => fillOnUndefined($params, "created_by"),
                    "updated_by" => fillOnUndefined($params, "updated_by"),
                ];

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

            $roomBedGroup = fillOnUndefined($params, 'room_bed_group', []);
            $bedGroupIndex = 1;

            foreach ($roomBedGroup as $bedGroup) {

                foreach ($bedGroup as $beds) {
                    $insertData =
                        [
                            'room_id' => fillOnUndefined($params, 'room_id', null),
                            'bed_group' => $bedGroupIndex,
                            'count' => fillOnUndefined($beds, 'bed_type_count', null),
                            'bed_type_id' => fillOnUndefined($beds, 'bed_type_id', null),
                            "status" => fillOnUndefined($params, "status", 1),
                            "created_by" => fillOnUndefined($params, "user_id", 0),
                            "updated_by" => fillOnUndefined($params, "user_id", 0)
                        ];
                    $validationResult = $this->propertyRoomBedAddValidator->validate($insertData);
                    if ($validationResult->errors()->first()) {
                        $errors = $validationResult->errors()->all();
                        throw new ApiErrorException($errors);
                    }

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

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

        }

        return output($response);

    }

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

            $dataValidation = $this->validate($params);
            if ($dataValidation['status'] != 'success') {
                throw new ApiErrorException($dataValidation['message']);
            }

            DB::beginTransaction();
            $deleteRoomBedsCriteria = [
                'criteria' => [
                    ['field' => 'room_id', 'condition' => '=', 'value' => $params['room_id']]
                ]
            ];
            $deleteRoomBeds = $this->propertyRoomBedRepository->delete($deleteRoomBedsCriteria);

            $roomBedGroup = fillOnUndefined($params, 'room_bed_group', []);
            $bedGroupIndex = 1;

            foreach ($roomBedGroup as $bedGroup) {

                foreach ($bedGroup as $beds) {

                    $insertData =
                        [
                            'room_id' => fillOnUndefined($params, 'room_id', null),
                            'bed_group' => $bedGroupIndex,
                            'count' => fillOnUndefined($beds, 'bed_type_count', null),
                            'bed_type_id' => fillOnUndefined($beds, 'bed_type_id', null),
                            "status" => fillOnUndefined($params, "status", 1),
                            "created_by" => fillOnUndefined($params, "user_id", 0),
                            "updated_by" => fillOnUndefined($params, "user_id", 0)
                        ];
                    $userCreateResult = $this->create($insertData);
                    if ($userCreateResult['status'] != 'success') {
                        throw new ApiErrorException($userCreateResult['message']);
                    }
                }
                $bedGroupIndex++;
            }
            $response = [
                'status' => true,

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

            if(fillOnUndefined($params, 'room_id', null) == null){
                throw new ApiErrorException(lang('room_id is required'));
            }

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

            ];

            $data = $this->propertyRoomBedRepository->findByCriteria($criteria, ['id', 'room_id', 'bed_group', 'count', 'bed_type_id']);
            $data = $data ? $data : [] ;
            $collection = collect($data) ;

            $bedGroup = $collection->unique('bed_group')->keyBy('bed_group')->keys()->all();

            $exportArray = [];
            foreach ($bedGroup as $group){
                $groupData = $collection->where('bed_group','=', $group);
                $subArray = [];
                foreach ($groupData as $data){
                    $subArray[] = [
                        'bed_type_id' => $data['bed_type_id'],
                        'bed_type_count' => $data['count'],
                    ];
                }
                $exportArray[] = $subArray;
            }

            $exportData = [
                'room_id' => $params['room_id'],
                'room_bed_group' => $exportArray

            ];

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

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


}
