<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyExecutive\PropertyExecutiveRepository;
use App\Core\Service\PropertyExecutiveTypeService;
use App\Core\Validator\PropertyExecutive\PropertyExecutiveCreateValidator;
use App\Core\Validator\PropertyExecutive\PropertyExecutiveUpdateValidator;
use App\Core\Repository\OfferContactMapping\OfferContactMappingRepository;

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

class PropertyExecutiveService
{

   private $propertyExecutiveRepository;
   private $propertyExecutiveTypeService;
   private $propertyExecutiveCreateValidator ;
   private $propertyExecutiveUpdateValidator ;
   private $offerContactMappingRepository;



    public function __construct(
        PropertyExecutiveRepository $propertyExecutiveRepository,
        PropertyExecutiveCreateValidator $propertyExecutiveCreateValidator,
        PropertyExecutiveUpdateValidator $propertyExecutiveUpdateValidator,
        OfferContactMappingRepository $offerContactMappingRepository,

        PropertyExecutiveTypeService $propertyExecutiveTypeService
    )
    {
        $this->propertyExecutiveRepository = $propertyExecutiveRepository;
        $this->propertyExecutiveTypeService = $propertyExecutiveTypeService;
        $this->propertyExecutiveCreateValidator = $propertyExecutiveCreateValidator;
        $this->propertyExecutiveUpdateValidator = $propertyExecutiveUpdateValidator;
        $this->offerContactMappingRepository = $offerContactMappingRepository;
    }

    public function create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $insertData =
                [
                    "property_id" => fillOnUndefined($param, "property_id"),
                    "executive_type_id" => fillOnUndefined($param, "executive_type_id"),
                    "name_surname" => fillOnUndefined($param, "name_surname"),
                    "email" => fillOnUndefined($param, "email"),
                    "phone_code" => fillOnUndefined($param, "phone_code"),
                    "phone" => fillOnUndefined($param, "phone"),
                    'extension' => fillOnUndefined($param, 'extension'),
                    "mobile_code" => fillOnUndefined($param, "mobile_code"),
                    "mobile" => fillOnUndefined($param, "mobile"),
                    "fax_code" => fillOnUndefined($param, "fax_code"),
                    "fax" => fillOnUndefined($param, "fax"),
                    "status" => fillOnUndefined($param, "status", 1),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];


            $executiveTypeRequest = [
                'criteria' => [
                    ['field' => 'name_surname', 'condition' => '=', 'value' => $insertData['name_surname']],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $insertData['property_id']],
                    ['field' => 'status', 'condition' => '=', 'value' => 1]
                ],
                'firstRow' => true
            ];
            $propertyExecutiveExist = $this->propertyExecutiveRepository->findByCriteria($executiveTypeRequest);
            if(!empty($propertyExecutiveExist)){
                throw new ApiErrorException(lang('Registered user in the system'));
            }

            $validationResult = $this->propertyExecutiveCreateValidator->validate($insertData);

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

            $userCreateResult = $this->propertyExecutiveRepository->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->propertyExecutiveRepository->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 {

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

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

            $updateResult = $this->propertyExecutiveRepository->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->propertyExecutiveRepository->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 getPropertyExecutive($params){

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

            // get all executive types
            $executiveTypeRequest = [
              'criteria' => [
                  ['field' => 'status', 'condition' => '=', 'value' => 1],
              ],
            ];
            $executiveTypeResponse = $this->propertyExecutiveTypeService->select($executiveTypeRequest);
            if($executiveTypeResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Executive Data Not Loaded'));
            }

            $executiveTypeCollection = collect($executiveTypeResponse['data']);

            // get all property executive types
            $propertyExecutiveTypeRequest = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                ]
            ];

            $propertyExecutiveTypeResponse = $this->select($propertyExecutiveTypeRequest);

            if($propertyExecutiveTypeResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Executive Data Not Loaded'));
            }
            $propertyExecutiveTypeCollection = collect($propertyExecutiveTypeResponse['data']);

            foreach ($executiveTypeCollection as $executiveType){


                // get property_executive data
                $propertyExecutiveItem = [];
                $executiveTypeCheck = $propertyExecutiveTypeCollection->where('executive_type_id', '=', $executiveType['id'])
                    ->toArray();
                foreach ($executiveTypeCheck  as $propertyExecutive){
                    $propertyExecutiveItem['name_surname'] = $propertyExecutive['name_surname'] ;
                    $propertyExecutiveItem['email'] = $propertyExecutive['email'] ;
                    $propertyExecutiveItem['phone_code'] = $propertyExecutive['phone_code'] ;
                    $propertyExecutiveItem['phone'] = $propertyExecutive['phone'] ;
                    $propertyExecutiveItem['mobile_code'] = $propertyExecutive['mobile_code'] ;
                    $propertyExecutiveItem['mobile'] = $propertyExecutive['mobile'] ;
                    $propertyExecutiveItem['fax_code'] = $propertyExecutive['fax_code'] ;
                    $propertyExecutiveItem['fax'] = $propertyExecutive['fax'] ;
                    $propertyExecutiveItem['view_full_phone'] = $propertyExecutive['view_full_phone'] ;
                    $propertyExecutiveItem['view_full_mobile'] = $propertyExecutive['view_full_mobile'] ;
                    $propertyExecutiveItem['view_full_fax'] = $propertyExecutive['view_full_fax'] ;

                }


                $executiveTypeItem['executive_type_id'] = $executiveType['id'] ;
                $executiveTypeItem['name'] = $executiveType['name'];
                $executiveTypeItem['data'] = $propertyExecutiveItem ;
                $return[] = $executiveTypeItem ;
            }

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

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

            // get all executive types
            $executiveTypeRequest = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                ],

            ];


            $executiveTypeResponse = $this->propertyExecutiveTypeService->select($executiveTypeRequest);
            if($executiveTypeResponse['status'] != 'success'){
                throw new ApiErrorException(lang('Executive Data Not Loaded'));
            }

            $executiveTypeCollection = collect($executiveTypeResponse['data']);

            // get all property executive types
            $propertyExecutiveTypeRequest = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                ],
                'orderBy' =>  [['field' => 'updated_at', 'value' => 'DESC']],
                'with' => ['executiveType']
            ];

            $propertyExecutiveResponse = $this->select($propertyExecutiveTypeRequest);

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

            $propertyExecutiveResponse = $propertyExecutiveResponse['data'] ;

            $return['executive_type'] = [];
            foreach ($executiveTypeCollection as $executiveType){



                // Get Locale data

                $executiveTypeItem['executive_type_id'] = $executiveType['id'] ;
                $executiveTypeItem['name'] =  $executiveType['name'];
                $executiveTypeItem['language_key'] =  $executiveType['language_key'];
                $return['executive_type'][] = $executiveTypeItem ;
            }

            $return['executives'] = [] ;
            foreach ($propertyExecutiveResponse as $executive){
                $executiveItem = [
                  'id' =>  $executive['id'],
                  'property_id' =>  $executive['property_id'],
                  'executive_type_id' =>  $executive['executive_type_id'],
                  'executive_type_name' =>  $executive['executive_type']['name'],
                  'name_surname' =>  $executive['name_surname'],
                  'email' =>  $executive['email'],
                  'phone_code' =>  $executive['phone_code'],
                  'phone' =>  $executive['phone'],
                  'extension' =>  $executive['extension'],
                  'mobile_code' =>  $executive['mobile_code'],
                  'mobile' =>  $executive['mobile'],
                  'fax_code' =>  $executive['fax_code'],
                  'fax' =>  $executive['fax'],
                  'view_full_phone' =>  $executive['view_full_phone'],
                  'view_full_mobile' =>  $executive['view_full_mobile'],
                  'view_full_fax' =>  $executive['view_full_fax'],
                ];
                $return['executives'][] = $executiveItem ;
            }

            $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 propertyExecutiveAdd($params){

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


            foreach ($params['executive_type'] as $executive_type){

                $createData = [
                    'property_id' => $params['property_id'],
                    'executive_type_id' => $executive_type['executive_type_id'],
                    'name_surname' => fillOnUndefined($executive_type, 'name_surname'),
                    'email' => fillOnUndefined($executive_type, 'email'),
                    'phone_code' => fillOnUndefined($executive_type, 'phone_code'),
                    'phone' => fillOnUndefined($executive_type, 'phone'),
                    'extension' => fillOnUndefined($executive_type, 'extension'),
                    'mobile_code' => fillOnUndefined($executive_type, 'mobile_code'),
                    'mobile' => fillOnUndefined($executive_type, 'mobile'),
                    'fax_code' => fillOnUndefined($executive_type, 'fax_code'),
                    'fax' => fillOnUndefined($executive_type, 'fax'),
                    'updated_by' => $params['user_id'],
                    'created_by' => $params['user_id'],
                ];
                $createStatus = $this->create($createData);

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

            }
            $requestParams = [
                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),

            ];

            $propertyExecutive = $this->listPropertyExecutive($requestParams);

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

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['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);
    }

    public function propertyExecutiveUpdate($params){

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {
            $return = [];
            foreach ($params['executive_type'] as $executive_type){
                    $updateData = [
                        'executive_type_id' => fillOnUndefined($executive_type, 'executive_type_id'),
                        'name_surname' => fillOnUndefined($executive_type, 'name_surname'),
                        'email' => fillOnUndefined($executive_type, 'email') ,
                        'phone_code' => fillOnUndefined($executive_type, 'phone_code'),
                        'phone' => fillOnUndefined($executive_type, 'phone'),
                        'extension' => fillOnUndefined($executive_type, 'extension'),
                        'mobile_code' => fillOnUndefined($executive_type, 'mobile_code'),
                        'mobile' => fillOnUndefined($executive_type, 'mobile') ,
                        'fax_code' => fillOnUndefined($executive_type, 'fax_code'),
                        'fax' =>  fillOnUndefined($executive_type, 'fax'),
                        'updated_by' => $params['user_id'],
                        'status' => 1,
                    ];

                    $propertyExecutiveExistRequest = [
                        'criteria' => [
                            ['field' => 'name_surname', 'condition' => '=', 'value' => $executive_type['name_surname']],
                            ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                            ['field' => 'id', 'condition' => '!=', 'value' =>  $executive_type['id'] ],
                            ['field' => 'status', 'condition' => '=', 'value' => 1]

                        ],
                        'firstRow' => true
                    ];

                    $propertyExecutiveExist = $this->propertyExecutiveRepository->findByCriteria($propertyExecutiveExistRequest);
                    if (isset($propertyExecutiveExist['id'])) {
                        throw new ApiErrorException(lang('Registered user in the system'));
                    }


                    $updateStatus = $this->update($executive_type['id'], $updateData) ;

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

            $requestParams = [

                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),

            ];

            $propertyExecutive = $this->listPropertyExecutive($requestParams);

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

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['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);
    }

    public function propertyExecutiveDelete($params){

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


            if(!isset($params['property_executive_id']) || !is_numeric($params['property_executive_id']) ){
                throw new ApiErrorException('property_executive_id field require');
            }
            $propertyExecutiveDeleteRequest = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['property_id']],
                    ['field' => 'id', 'condition' => '=', 'value' => $params['property_executive_id']],
                ]
            ];


            $propertyExecutiveTypeResponse = $this->propertyExecutiveRepository->delete($propertyExecutiveDeleteRequest);
            if(!$propertyExecutiveTypeResponse){
                throw new ApiErrorException('No record to delete');

            }




            $requestParams = [

                'locale' => fillOnUndefined($params, 'locale'),
                'property_id' => fillOnUndefined($params, 'property_id'),

            ];

            $propertyExecutive = $this->getPropertyExecutive($requestParams);

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

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['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);
    }

    public function propertyExecutivePassive($params){

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

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

            $updateResult = $this->propertyExecutiveRepository->update($params['property_executive_id'], $updateParams);

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

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

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



            $offerUpdateResult = $this->offerContactMappingRepository->findByCriteria($updateCriteria , ['id']);
            $updateIds = collect($offerUpdateResult)->keyBy('id')->keys()->toArray();
            $offerUpdateResult = $this->offerContactMappingRepository->updateWhereIn($updateIds , $updateParams);

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

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

            $propertyExecutive = $this->listPropertyExecutive($requestParams);

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

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $propertyExecutive['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);
    }


}
