<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyModuleMapping\PropertyModuleMappingRepository;
use App\Core\Service\PropertyConfigService;
use Illuminate\Http\Request;



use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;

use Exception;
use App\Exceptions\ApiErrorException;

class PropertyModuleMappingService
{

    private $propertyModuleMappingRepository;
    private $configKey;
    private $propertyConfigService;
    private $currentRoute;
    private $request;

    public function __construct(
        PropertyModuleMappingRepository $propertyModuleMappingRepository,
        PropertyConfigService $propertyConfigService,
        Request $request
    )
    {
        $this->propertyModuleMappingRepository = $propertyModuleMappingRepository;
        $this->propertyConfigService = $propertyConfigService;
        $this->configKey = 'data_rate';
        $this->request = $request;
        $this->currentRoute = $this->request->route();

    }

    public function create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $insertData =
                [
                    "property_id" => fillOnUndefined($param, "property_id"),
                    "property_module_id" => fillOnUndefined($param, "property_module_id"),
                    "status" => fillOnUndefined($param, "status", 1),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];

            $userCreateResult = $this->propertyModuleMappingRepository->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->propertyModuleMappingRepository->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->propertyModuleMappingRepository->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 getPropertyModuleMapping($params)
    {

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


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

                ],
                'with' => ['propertyModule']
            ];
            $propertyModuleResponse = $this->select($propertyModuleRequest);

            if ($propertyModuleResponse['status'] != 'success') {
                throw new ApiErrorException(lang('ModuleMapping Data Not Loaded'));
            }

            $propertyMappedModules = array_column($propertyModuleResponse['data'], 'property_module');

            $totalPoint = collect($propertyMappedModules)->sum('point');

            $return['property_modules'] = $propertyMappedModules ;
            $return['data_point'] = $totalPoint ;

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $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 propertyModuleMappingUpdate($params)
    {

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

            $propertyModuleRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'property_module_id', 'condition' => '=', 'value' => $params['property_module_id']],
                ]
            ];
            $propertyModuleResponse = $this->select($propertyModuleRequest);

            if ($propertyModuleResponse['status'] != 'success') {
                throw new ApiErrorException(lang('ModuleMapping Data Not Loaded'));
            }

            if (!$propertyModuleResponse['data']) {
                $createData = [
                    'property_id' => $params['property_id'],
                    'property_module_id' => $params['property_module_id'],
                    'status' => 1,
                    'updated_by' => $params['user_id'],
                    'created_by' => $params['user_id'],
                ];
                $createStatus = $this->create($createData);
                if ($createStatus['status'] != 'success') {
                    throw new Exception($createStatus['message']);
                }

            }


            $propertyModuleMapping = $this->getPropertyModuleMapping($params);

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

            $configParams = [
                'config_keys' => [
                    [
                        'config_key' => $this->configKey,
                        'config_value_json' => json_encode(['point' => $propertyModuleMapping['data']['data_point']])
                    ]
                ],
                'property_id' => fillOnUndefined($params, 'property_id'),
                'user_id' => $params['user_id'],
            ];

            $propertyConfig = $this->propertyConfigService->propertyConfigUpdate($configParams);

            if ($propertyConfig['status'] != 'success') {

                throw new ApiErrorException($propertyConfig['message']);
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => ['property_module_mapping' => $propertyModuleMapping['data']]];


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


}
