<?php

namespace App\Http\Controllers;

use App\Core\Service\PropertyService;
use App\Core\Service\TempPropertyService;
use App\Core\Service\UserPropertyMappingService;
use App\Core\Service\UserService;
use App\Notifications\NewUserNotification;
use Illuminate\Http\Request;
use App\Core\Service\JwtService;
use App\Core\Service\ApplicationCacheService;
use App\Core\Mail\UserCreateMail;
use App\Core\Mail\UserForgotPassword;
use Illuminate\Mail\Mailer;
use App\Core\Service\ApiAccessTokenService;
use App\Core\Service\LanguageService;
use App\Core\Service\ProductService;
use App\Core\Service\ThirdPartyServices\MondayService;


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

class UserController extends Controller
{
    private $request;

    private $userService;
    private $tempPropertyService;
    private $propertyService;
    private $userPropertyMappingService;
    private $jwtService;
    private $applicationCacheService;
    private $mailer;
    private $apiAccessTokenService;
    private $languageService;
    private $productService;


    public function __construct(
        Request                    $request,
        Mailer                     $mailer,
        ApplicationCacheService    $applicationCacheService,
        TempPropertyService        $tempPropertyService,
        PropertyService            $propertyService,
        JwtService                 $jwtService,
        UserPropertyMappingService $userPropertyMappingService,
        ApiAccessTokenService      $apiAccessTokenService,
        UserService                $userService,
        LanguageService            $languageService,
        ProductService             $productService,
        MondayService              $mondayService
    )
    {
        $this->request = $request;
        $this->userService = $userService;
        $this->tempPropertyService = $tempPropertyService;
        $this->propertyService = $propertyService;
        $this->userPropertyMappingService = $userPropertyMappingService;
        $this->jwtService = $jwtService;
        $this->applicationCacheService = $applicationCacheService;
        $this->mailer = $mailer;
        $this->apiAccessTokenService = $apiAccessTokenService;
        $this->languageService = $languageService;
        $this->productService = $productService;
        $this->mondayService = $mondayService;
    }

    public function getUserList()
    {


        /*$userListCriteria['criteria'] = [];
        $userListCriteria['criteria'][] = ['field' => 'idate', 'condition' => '=', 'value' => 0];
        //$userListCriteria['firstRow'] = true;
        $userListCriteria['skip'] = 0; //take *2
        $userListCriteria['take'] = 3;
        $userListCriteria['orderBy'][] = ['field' => 'id', 'value' => 'DESC'];*/

        if (is_null($this->request->params)) {
            return apiResponse(0, 'Parameter Error.', null, 400);
        }

        $userListCriteria = $this->request->params;
        $userList = $this->userService->select($userListCriteria, fillOnUndefined($userListCriteria, 'select', ['*']));

        if ($userList['status'] == 'success') {
            return apiResponse(1, null, $userList['data'], 200);
        } else {
            return apiResponse(0, $userList['message'], null, 400);
        }
    }

    public function userCreate(Request $request)
    {


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


            $params = $this->request->params;
            $userId = $request->credentials->user_id;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $userCreateParams = $params;
            $userCreateParams['user_id'] = $userId;
            $return = [];
            $userCreate = $this->userService->create($userCreateParams);

            if ($userCreate['status'] != 'success') {
                throw new ApiErrorException($userCreate['message']);
            }
            $return['user'] = $userCreate['data'];

            $mailParams = [
                'name_surname' => $return['user']['name'] . ' ' . $return['user']['surname'],
                'email' => $return['user']['email'],
                'hash_key' => $return['user']['hash_key'],
                'activation_link' => Config::get('app.client_server') . '/activate-user?email=' . $return['user']['email'] . '&key=' . $return['user']['hash_key'],

            ];

            $this->mailer->onQueue(
                'userCreateMail',
                new UserCreateMail($mailParams)
            );

            $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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function checkUserKey(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {
            $params = $this->request->params;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $checkUserParams = $params;
            $return = [];
            $checkUserKey = $this->userService->checkUserKey($checkUserParams);

            if ($checkUserKey['status'] != 'success') {
                throw new ApiErrorException($checkUserKey['message']);
            }
            $return['user'] = $checkUserKey['data'];
            unset($return['user']['id']);
            $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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function newPassword(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {
            $params = $this->request->params;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $checkUserParams = $params;
            $return = [];
            $checkUserKey = $this->userService->checkUserKey($checkUserParams);

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

            $checkUserKey = $checkUserKey['data'];
            $newPasswordParams = [
                'email' => fillOnUndefined($params, 'email'),
                'hash_key' => fillOnUndefined($params, 'key'),
                'password' => fillOnUndefined($params, 'password'),
                'password_confirmation' => fillOnUndefined($params, 'password_confirmation'),
                'user_id' => $checkUserKey['id'],

            ];

            $newPassword = $this->userService->newPassword($newPasswordParams);
            if ($newPassword['status'] != 'success') {
                throw new Exception($newPassword['message']);
            }


            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function changePassword(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {
            $params = $this->request->params;
            $userId = $request->credentials->user_id;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $return = [];

            $changePasswordParams = [
                'user_id' => $userId,
                'old_password' => fillOnUndefined($params, 'old_password'),
                'password' => fillOnUndefined($params, 'password'),
                'password_confirmation' => fillOnUndefined($params, 'password_confirmation'),
            ];

            $changePassword = $this->userService->changePassword($changePasswordParams);
            if ($changePassword['status'] != 'success') {
                throw new Exception($changePassword['message']);
            }


            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function forgotPassword(Request $request)
    {


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

            $params = $this->request->params;

            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }


            $language = "en";
            if ($request->headers->get('language')) {
                $language = $request->headers->get('language');
            }

            $userUpdateParams = [
                'email' => fillOnUndefined($params, 'email'),
            ];
            $return = [];

            $userUpdate = $this->userService->forgotPassword($userUpdateParams);
            if ($userUpdate['status'] != 'success') {
                throw new Exception($userUpdate['message']);
            }
            $userUpdate = $userUpdate['data'];
            $mailParams = [
                'name_surname' => $userUpdate['name'] . ' ' . $userUpdate['surname'],
                'email' => $userUpdate['email'],
                'hash_key' => $userUpdate['hash_key'],
                'activation_link' => Config::get('app.client_server') . '/reset-password?email=' . $userUpdate['email'] . '&key=' . $userUpdate['hash_key'],
                'language' => $language,

            ];

            $this->mailer->onQueue(
                'UserForgotPassword',
                new UserForgotPassword($mailParams)
            );


            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function resetPassword(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {

            $params = $this->request->params;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $userUpdateParams = [
                'email' => fillOnUndefined($params, 'email'),
                'hash_key' => fillOnUndefined($params, 'key'),
                'password' => fillOnUndefined($params, 'password'),
                'password_confirmation' => fillOnUndefined($params, 'password_confirmation'),
            ];
            $return = [];

            $userUpdate = $this->userService->resetPassword($userUpdateParams);
            if ($userUpdate['status'] != 'success') {
                throw new Exception($userUpdate['message']);
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => 'Your password updated successfuly', '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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function userUpdate(Request $request)
    {


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

            $params = $this->request->params;

            $userId = $request->credentials->user_id;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $userUpdateParams = [
                'user_update_data' => fillOnUndefined($params, 'user_update_data'),
                'update_user_id' => fillOnUndefined($params, 'update_user_id'),
                'user_id' => $userId


            ];

            $return = [];
            $userCreate = $this->userService->update($userUpdateParams);
            if ($userCreate['status'] != 'success') {
                throw new Exception($userCreate['message']);
            }
            $return['user'] = $userCreate['data'];


            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function addUserProperty(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {


            $params = $this->request->params;

            $userId = $request->credentials->user_id;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }

            $userPropertyParams = [
                'add_user_id' => fillOnUndefined($params, 'add_user_id'),
                'add_property_id' => fillOnUndefined($params, 'add_property_id'),
                'user_id' => $userId
            ];
            $return = [];

            $addUserProperty = $this->userPropertyMappingService->addUserProperty($userPropertyParams);

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

            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function removeUserProperty(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {


            $params = $this->request->params;

            $userId = $request->credentials->user_id;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }

            $userPropertyParams = [
                'remove_user_id' => fillOnUndefined($params, 'remove_user_id'),
                'remove_property_id' => fillOnUndefined($params, 'remove_property_id'),
                'user_id' => $userId
            ];
            $return = [];

            $addUserProperty = $this->userPropertyMappingService->removeUserProperty($userPropertyParams);
            if ($addUserProperty['status'] != 'success') {
                throw new Exception($addUserProperty['message']);
            }

            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function userRegister()
    {

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

            $params = $this->request->params;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $userCreateParams = $params;
            $return = [];
            $userCreate = $this->userService->create($userCreateParams);
            if ($userCreate['status'] != 'success') {
                throw new Exception($userCreate['message']);
            }
            $return['user'] = $userCreate['data'];

            $jwtData = $this->jwtService->jwtCreate(['user_id' => $return['user']['id']]);

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

            $return['token'] = $jwtData['data'];

            if ($params['temp_hotel_id']) {
                $propertySearchCriteria = [
                    'criteria' => [
                        ["field" => "id", "condition" => "=", "value" => $params['temp_hotel_id']]
                    ],
                    'firstRow' => true
                ];
                $tempPropertyData = $this->tempPropertyService->select($propertySearchCriteria, ['id', 'name', 'giata_id', 'destination_id']);
                if ($tempPropertyData['status'] == 'success') {
                    $tempProperty = $tempPropertyData['data'];
                    $propertyInsertData = [
                        'name' => $tempProperty['name'],
                        'destination_id' => $tempProperty['destination_id'],
                        'giata_id' => $tempProperty['destination_id'],
                        'currency_type' => 'TRY',
                        'created_at' => time(),
                        'updated_at' => time(),
                    ];
                    $propertyCreate = $this->propertyService->create($propertyInsertData);
                    if ($propertyCreate['status'] == 'success') {
                        $return['property'] = $propertyCreate['data'];
                        $userPropertyMappingData = [
                            'user_id' => $userCreate['data']['id'],
                            'property_id' => $propertyCreate['data']['id'],
                        ];
                        $userPropertyMappingCreate = $this->userPropertyMappingService->create($userPropertyMappingData);
                        if ($userPropertyMappingCreate['status'] == 'success') {
                            // $return['user_property_mapping'] = $userPropertyMappingCreate['data'] ;
                        }
                    }
                }
            }
            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function setProperty()
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 400];
        try {


            $request = $this->request->params;
            $checkUserPropertyCriteria = [
                'criteria' => [
                    ['field' => 'user_id', 'condition' => '=', 'value' => $this->request->credentials->user_id],
                    ['field' => 'property_id', 'condition' => '=', 'value' => fillOnUndefined($request, 'property_id')],
                ],
                'with' => ['property'],
                'firstRow' => true,
            ];
            $checkUserProperty = $this->userPropertyMappingService->select($checkUserPropertyCriteria);

            if ($checkUserProperty['status'] != 'success') {
                throw new Exception(lang('An unknown error occurred'));
            }

            if (!$checkUserProperty['data']) {
                throw new ApiErrorException(lang('Mapping data not found'));
            }
            $cacheParams = [

                'token' => $this->request->header('authToken'),
                'property_id' => $checkUserProperty['data']['property_id']

            ];
            $applicationCache = $this->applicationCacheService->applicationCacheCreate($cacheParams);
            $return['hotel_user_mapping'] = $checkUserProperty['data'];
            $return['application_cache'] = $applicationCache['data'];

            $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'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function userRegisterWithProperty()
    {

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

            DB::beginTransaction();

            $params = $this->request->params;
            if (is_null($params)) {
                return apiResponse(0, 'Parameter Error.', null, 400);
            }
            $language = "en";
            if ($this->request->headers->get('language')) {
                $language = $this->request->headers->get('language');
            }
            $userCreateParams = $params;
            $return = [];
            $userCreateParams['status'] = 1;
            $userCreateParams['user_type'] = 1;

            $userCreate = $this->userService->create($userCreateParams);
            if ($userCreate['status'] != 'success') {
                throw new ApiErrorException($userCreate['message']);
            }
            $return['user'] = $userCreate['data'];

            $propertyInsertData = [
                'name' => $userCreateParams['property_name'],
                'status' => 1,
                'created_by' => $return['user']['id'],
                'updated_by' => $return['user']['id'],
                'created_at' => time(),
                'updated_at' => time(),
            ];
            $propertyCreate = $this->propertyService->create($propertyInsertData);
            if ($propertyCreate['status'] != 'success') {
                throw new ApiErrorException($propertyCreate['message']);
            }
            $return['property_list'] = [
                [
                    'id' => $propertyCreate['data']['id'],
                    'name' => $propertyCreate['data']['name'],
                    'default_photo' => "/assets/img/placeholder.png",
                ]
            ];
            $userPropertyMappingData = [
                'user_id' => $userCreate['data']['id'],
                'status' => 1,
                'property_id' => $propertyCreate['data']['id'],
                'created_by' => $return['user']['id'],
                'updated_by' => $return['user']['id'],
                'created_at' => time(),
                'updated_at' => time(),
            ];
            $userPropertyMappingCreate = $this->userPropertyMappingService->create($userPropertyMappingData);
            if ($userPropertyMappingCreate['status'] != 'success') {
                throw new ApiErrorException($userPropertyMappingCreate['message']);
            }

            $propertyProducts = $this->productService->setDefaultPropertyProducts($userPropertyMappingData);
            if ($propertyProducts['status'] != 'success') {
                throw new ApiErrorException($propertyProducts['message']);
            }

            $jwtToken = $this->jwtService->jwtCreate(['user_id' => $return['user']['id']]);
            if ($jwtToken['status'] != 'success') {
                throw new ApiErrorException(lang('An unknown error occurred.'));
            }
            $jwtToken = $jwtToken['data'];
            $saveToken = [
                "token" => md5(fillOnUndefined($jwtToken, "token")),
                "expire_date" => fillOnUndefined($jwtToken, "exp"),
                "user_id" => fillOnUndefined($return['user'], "id"),
                "invalidate" => fillOnUndefined($jwtToken, "invalidate", 0),
            ];

            $saveTokenTo = $this->apiAccessTokenService->create($saveToken);
            if ($saveTokenTo['status'] != 'success') {
                throw new ApiErrorException(lang('General error'));
            }


            $return['token'] = $jwtToken['token'];
            $return['expire_time'] = $saveTokenTo['data']['expire_time'];
            $return['locale'] = null;


            $mailParams = [
                'name_surname' => $return['user']['name'] . ' ' . $return['user']['surname'],
                'email' => $return['user']['email'],
                "password" => $return['user']['userPassword'],
                'language' => $language,
            ];

            $this->mailer->onQueue(
                'userCreateMail',
                new UserCreateMail($mailParams)
            );

            $return['user'] = [
                'name' => $userCreate['data']['name'],
                'surname' => $userCreate['data']['surname'],

            ];


            $notificationParam = $userCreateParams;
            Notification::route('mail', ['sales@extranetwork.com' => 'Extranetwork Sales'])->notify(new NewUserNotification($notificationParam));

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $return];
            DB::commit();

            //Monday.com contact items
            //$createBoardItems = $this->mondayService->createBoardItems($userCreateParams);

            //Kommo integration
            $kommoPropertyParam = [
                'name_surname' => $notificationParam['name'] . ' ' . $notificationParam['surname'],
                'phone_number' => $notificationParam['phone'],
                'email' => $notificationParam['email'],
                'property' => $notificationParam['property_name'],
                'web' => fillOnUndefined($notificationParam, 'web', 'www.extranetwork.com')
            ];

            $this->propertyService->kommoCreateLead($kommoPropertyParam);

        } catch (ApiErrorException $e) {
            DB::rollBack();
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            DB::rollBack();
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 400;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function getProfile(Request $request)
    {

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

            $return = [];
            if (is_null($request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $requestParams = [
                'user_id' => $request->credentials->user_id,
                'status' => 1
            ];

            $profileFields = ['id', 'email', 'name', 'surname', 'gender', 'language', 'phone'];

            $profile = $this->userService->getProfile($requestParams, $profileFields);

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

            $languageCriteria = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_application', 'condition' => '=', 'value' => 1],
                    ['field' => 'is_published', 'condition' => '=', 'value' => 1]
                ],
                "orderBy" => [
                    ["field" => "name", "value" => "ASC"]
                ]
            ];

            $languages = $this->languageService->getAllLanguages($languageCriteria, ['id', 'code', 'name', 'status', 'language_key']);

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

            $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 apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function updateProfile(Request $request)
    {

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

            if (is_null($request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $params = $request->params;

            $requestParams = [
                'name' => fillOnUndefined($params, 'name'),
                'surname' => fillOnUndefined($params, 'surname'),
                'gender' => fillOnUndefined($params, 'gender'),
                'language' => fillOnUndefined($params, 'language'),
                'phone' => fillOnUndefined($params, 'phone'),
                'user_id' => $request->credentials->user_id,
            ];

            $profile = $this->userService->profileUpdate($requestParams);

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

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

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