<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyChannelGroup\PropertyChannelGroupRepository;
use App\Core\Service\PropertyChannelService;
use App\Core\Repository\PropertyChannelMapping\PropertyChannelMappingRepository;

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

class PropertyChannelGroupService
{

    private $propertyChannelGroupRepository;
    private $propertyChannelService;
    private $propertyChannelMappingRepository;


    public function __construct(

        PropertyChannelGroupRepository $propertyChannelGroupRepository,
        PropertyChannelService $propertyChannelService,
        PropertyChannelMappingRepository $propertyChannelMappingRepository

    )
    {

        $this->propertyChannelGroupRepository = $propertyChannelGroupRepository;
        $this->propertyChannelService = $propertyChannelService;
        $this->propertyChannelMappingRepository = $propertyChannelMappingRepository;
    }

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

            /* Todo: validator
            $validationResult = $this->propertyChannelAddValidator->validate($params);

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

            $insertData =
                [
                    'property_id' => fillOnUndefined($params, 'property_id'),
                    'name' => fillOnUndefined($params, 'name'),
                    "status" => fillOnUndefined($params, "status", 1),
                    "created_by" => fillOnUndefined($params, "created_by", 0),
                    "updated_by" => fillOnUndefined($params, "updated_by", 0),
                    "created_at"     => time(),
                    "updated_at"     => time(),
                ];

            $insertResponse = $this->propertyChannelGroupRepository->create($insertData);

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

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

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

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

            $criteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                ],
            ];

            if(isset($params['id'])){
                $criteria = [
                    'criteria' => [
                        ['field' => 'id', 'condition' => '=', 'value' => $params['id']],
                        ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ],
                    'with' => ['channelGroupActiveChannels'],
                    'firstRow' => true
                ];
            }


            $groups = $this->propertyChannelGroupRepository->findByCriteria($criteria, ['id', 'name','status']);
            $groups = $groups ? $groups : [] ;

            if(isset($params['id'])){

                $requestParams = [
                    'property_id' => fillOnUndefined($params, 'property_id')
                ];

                $propertyChannel = $this->propertyChannelService->getPropertyChannels($requestParams);
                if($propertyChannel['status'] != 'success'){
                    throw new ApiErrorException($propertyChannel['message']);
                }


                $propertyChannelCollection = collect($propertyChannel['data']);
                $filterPropertyChannels = $propertyChannelCollection->where('is_selected', true);
                $filterPropertyChannels = $filterPropertyChannels->where('is_pending', false);
                $selectedPropertyChannels = $filterPropertyChannels->all();

                $groupChannelCollection = collect($groups["channel_group_active_channels"]);


                foreach ($selectedPropertyChannels as $k=>$v){

                    $filtergroupChannel = $groupChannelCollection->where('channel_id', $v['id']);
                    $isChannelMatched = $filtergroupChannel->all();

                    $selectedPropertyChannels[$k]["in_group"] = false;
                    if(count($isChannelMatched)){
                        $selectedPropertyChannels[$k]["in_group"] = true;
                    }

                    $criteria = [
                        'criteria' => [
                            ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                            ['field' => 'channel_id', 'condition' => '=', 'value' => $v['id']],
                            ['field' => 'property_availability_type_id', 'condition' => '=', 'value' => 1],
                            ['field' => 'status', 'condition' => '=', 'value' => 1],
                        ],
                        'firstRow' => true
                    ];

                    $availabilityTypeCheck = $this->propertyChannelMappingRepository->findByCriteria($criteria);
                    if(!count($availabilityTypeCheck)){
                        unset($selectedPropertyChannels[$k]);
                    }

                }

                $groups["channel_group_active_channels"] = $selectedPropertyChannels;

            }


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

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

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

            $criteria = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => $params['channel_group_id']],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                ],
                'with' => ['channelGroupActiveChannels','channelGroupActiveChannels.channel'],
                'firstRow' => true
            ];


            $group = $this->propertyChannelGroupRepository->findByCriteria($criteria, ['id', 'name','status']);
            $group = $group ? $group : [] ;

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

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





}
