<?php


namespace App\Core\Service;

use App\Core\Repository\UserPropertyMapping\UserPropertyMappingRepository;
use App\Core\Validator\UserPropertyMapping\UserPropertyMappingAddValidator;
use App\Core\Validator\UserPropertyMapping\UserPropertyMappingRemoveValidator;

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


class UserPropertyMappingService
{
    private $userPropertyMappingRepository;
    private $userPropertyMappingAddValidator;
    private $userPropertyMappingRemoveValidator;

    public function __construct
    (
        Request $request,
        UserPropertyMappingAddValidator $userPropertyMappingAddValidator,
        UserPropertyMappingRemoveValidator $userPropertyMappingRemoveValidator,
        UserPropertyMappingRepository $userPropertyMappingRepository
    )
    {
        $this->request = $request;
        $this->userPropertyMappingRepository = $userPropertyMappingRepository;
        $this->userPropertyMappingAddValidator = $userPropertyMappingAddValidator;
        $this->userPropertyMappingRemoveValidator = $userPropertyMappingRemoveValidator;
    }


    public function select($param = [], $column = ['*'])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $data = $this->userPropertyMappingRepository->findByCriteria($param, $column);
            if(!$data){
                throw new ApiErrorException(lang('An unknown error occurred'));
            }

            $response['status'] = 1;
            $response['data'] = $data;

        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $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 create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $userPropertyMappingData =
                [
                    "user_id" => fillOnUndefined($param, "user_id"),
                    "property_id" => fillOnUndefined($param, "property_id"),
                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "created_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];
            $propertyCreateResult = $this->userPropertyMappingRepository->create($userPropertyMappingData);

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

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

        try {

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

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $checkPropertyList = $this->isAllowedProperty(['user_id' => $params['user_id'], 'add_property_id' => $params['add_property_id'],]);

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

            $criteria =
                [
                    "criteria" =>
                        [
                            ["field" => "user_id", "condition" => "=", "value" => $params['add_user_id']]
                        ]
                ];
            $oldMappingList = $this->userPropertyMappingRepository->findByCriteria($criteria, ['id', 'user_id', 'property_id', 'status']);
            foreach ($params['add_property_id'] as $addProperty) {

                $checkData = collect($oldMappingList)
                    ->where('user_id' , '=', $params['add_user_id'])
                    ->where('property_id', '=', $addProperty)
                    ->first();

               if(!$checkData){
                   $addUserPropertyMappingData = [
                       "user_id" => $params['add_user_id'],
                       "property_id" => $addProperty,
                       "status" => 1,
                       "created_by" => $params['user_id'],
                   ];
                 $createStatus =   $this->create($addUserPropertyMappingData);
                 if($createStatus['status'] != 'success'){
                     throw new ApiErrorException($createStatus['message']);
                 }
               }else{


                   $updateUserPropertyMappingData = [
                       "status" => 1,
                       "updated_by" => $params['user_id'],
                       'updated_at' => time()
                   ];
                   $updateResult = $this->userPropertyMappingRepository->update($checkData['id'], $updateUserPropertyMappingData) ;
                   if($updateResult['status'] != 'success'){
                       throw new Exception('api-unknown_error');
                   }

               }
            }

            $response = ['status' => 1 , 'message' => '', 'data' => []];

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

        try {

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

            foreach ($params['remove_property_id'] as $addProperty) {


                $updatePropertyCriteria = [
                  'criteria' => [
                      ['field' => 'user_id', 'condition' => '=', 'value' => $params['remove_user_id'] ],
                      ['field' => 'property_id', 'condition' => '=', 'value' => $addProperty],
                  ]

                ];

                $updateUserPropertyMappingData = [
                    "status" => 0,
                    "updated_by" => $params['user_id'],
                    'updated_at' => time()
                ];

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

            $response = ['status' => 1 , 'message' => '', 'data' => []];

        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $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 isAllowedProperty($params)
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $criteria =
                [
                    "criteria" =>
                        [
                            ["field" => "user_id", "condition" => "=", "value" => $params['user_id']]
                        ]
                ];
            $mappingList = $this->userPropertyMappingRepository->findByCriteria($criteria, ['id', 'user_id', 'property_id']);

            $allowedProperties = collect($mappingList);
            foreach ($params['add_property_id'] as $requestProperty) {
                $checkProperty = $allowedProperties->where('property_id', '=', $requestProperty)->count();
                if (!$checkProperty) {
                    throw new ApiErrorException(lang('property {#1} not allowed', [$requestProperty]));
                }
            }
            $response = ['status' => 1, 'message' => '', 'data' => []];

        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $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);

    }
}
