src/Model/UserModel.php line 3819

Open in your IDE?
  1. <?php
  2. namespace App\Model;
  3. use Pimcore\Db;
  4. use Carbon\Carbon;
  5. use App\Lib\Utility;
  6. use App\Lib\ExcelGenerator;
  7. use App\Service\EmailService;
  8. use Pimcore\Model\DataObject;
  9. use App\Service\UserPermission;
  10. use Pimcore\Model\DataObject\Customer;
  11. use Pimcore\Model\DataObject\Location;
  12. use Pimcore\Model\DataObject\Tags;
  13. use Pimcore\Model\DataObject\UserGroup;
  14. use Pimcore\Model\DataObject\UserSMSGroup;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use App\C2IntegrationBundle\Service\C2Service;
  17. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use DateTime;
  20. use Pimcore\Model\Asset\MetaData\ClassDefinition\Data\DataObject as DataDataObject;
  21. use Pimcore\Model\DataObject\Subscription;
  22. use Pimcore\Model\DataObject\UserTag;
  23. use App\Model\ReportingPortalModel;
  24. use App\Model\EwsPortalModel;
  25. use Pimcore\Model\DataObject\PermissionGroup;
  26. class UserModel
  27. {
  28.     public $emailService;
  29.     public $userPermission;
  30.     private $locationModel;
  31.     private $c2Service;
  32.     private $reportingPortalModel;
  33.     private $ewsPortalModel;
  34.     function __construct()
  35.     {
  36.         $this->emailService  = new EmailService();
  37.         $this->userPermission  = new UserPermission();
  38.         $this->locationModel = new LocationModel();
  39.         $this->c2Service = new C2Service();
  40.         $this->reportingPortalModel = new ReportingPortalModel();
  41.         $this->ewsPortalModel = new EwsPortalModel();
  42.     }
  43.     public function register($request$params$translator): array
  44.     {
  45.         $result = [];
  46.         try {
  47.             Utility::validateEmail($params['email']);
  48.             Utility::validateName($params['name']);
  49.             if (!$params['organization'] instanceof \Pimcore\Model\DataObject\Organization) {
  50.                 return ["success" => false"message" => $translator->trans("invalid_organization_passed")];
  51.             }
  52.             if (!$params['role'] instanceof \Pimcore\Model\DataObject\UserRole) {
  53.                 return ["success" => false"message" => $translator->trans("invalid_user_role")];
  54.             }
  55.             $user DataObject\Customer::getByEmail($params['email'], true);
  56.             if ($user instanceof \Pimcore\Model\DataObject\Customer) {
  57.                 return ["success" => false"message" => $translator->trans("user_already_exists")];
  58.             }
  59.             $userGroup DataObject\UserGroup::getById($params['groupId'], true);
  60.             $registerUser = new DataObject\Customer();
  61.             $registerUser->setParent(DataObject\Service::createFolderByPath('/UserManagement/Users'));
  62.             $registerUser->setKey(trim(strip_tags($params['email'])));
  63.             $registerUser->setName(strip_tags($params['name']));
  64.             $registerUser->setEmail(trim(strip_tags($params['email'])));
  65.             if ((isset($params['published'])) && ($params['published'] == false)) {
  66.                 # code...
  67.                 $registerUser->setToken((isset($params['token'])) ? $params['token'] : '');
  68.             }
  69.             $registerUser->setRole($params['role']);
  70.             if ($userGroup instanceof \Pimcore\Model\DataObject\UserGroup) {
  71.                 $registerUser->setUserGroup($userGroup);
  72.             }
  73.             // assign user permissions to user
  74.             if (isset($params['permissionUserGroupIds']) && !empty($params['permissionUserGroupIds']) && is_array($params['permissionUserGroupIds'])) {
  75.                 $permissionGroups = [];
  76.                 foreach ($params['permissionUserGroupIds'] as $groupId) {
  77.                     $permissionGroup PermissionGroup::getById($groupId);
  78.                     if ($permissionGroup) {
  79.                         $permissionGroups[] = $permissionGroup;
  80.                     }
  81.                 }
  82.                 $registerUser->setPermissionGroups($permissionGroups);
  83.             }
  84.             $registerUser->setOrganization($params['organization']);
  85.             $registerUser->setPassword($params['password']);
  86.             $registerUser->setTitle((isset($params['title'])) ? $params['title'] : '');
  87.             $registerUser->setDepartment((isset($params['department'])) ? $params['department'] : '');
  88.             $registerUser->setCreatedBy($params['createdBy']);
  89.             // Set created-by snapshot fields for future reference even if relation is removed
  90.             if (isset($params['createdBy']) && $params['createdBy'] instanceof DataObject\Customer) {
  91.                 $creator $params['createdBy'];
  92.                 $registerUser->setCreatedByUserName($creator->getName());
  93.                 $registerUser->setCreatedByUserEmail($creator->getEmail());
  94.                 $registerUser->setCreatedByUserStatus($creator->getIsDeleted() ? 'deleted' 'active');
  95.             } else {
  96.                 $registerUser->setCreatedByUserStatus('deleted');
  97.             }
  98.             $registerUser->setPublished((isset($params['published'])) ? $params['published'] : true);
  99.             $registerUser->setIsActive(true);
  100.             $registerUser->setphoneNo(isset($params['phone']) ? $params['phone'] : '');
  101.             if ($params['role']->getName() == USER_ROLES['CLIENT_ADMIN'] || $params['role']->getName() == USER_ROLES['CLIENT_USER']) {
  102.                 $registerUser->setTwoFactorAuth(true);
  103.             }
  104.             $registerUser->save();
  105.             // assign default subscription based on role
  106.             if ($params['role']->getName() !== USER_ROLES['NCM_IT'] && $params['role']->getName() !== USER_ROLES['NCM_OPERATOR']) {
  107.                 # code...
  108.                 $this->createSubscription($translator$registerUser$params['role'], isset($params['isNoExpiry']) ? $params['isNoExpiry'] : false);
  109.             }
  110.             return ["success" => true"message" => $translator->trans("user_registered_success"), 'data' => $registerUser];
  111.         } catch (\Exception $ex) {
  112.             throw new \Exception($ex->getMessage());
  113.         }
  114.         return $result;
  115.     }
  116.     /**
  117.      * Create Subscritpion 
  118.      */
  119.     public function createSubscription($translator$user$role$isNoExpiry false): array
  120.     {
  121.         $result = [];
  122.         try {
  123.             $subscriptionsArray = [];
  124.             if ($role instanceof DataObject\UserRole) {
  125.                 $packages $role->getDefaultPackages();
  126.                 if ($packages) {
  127.                     foreach ($packages as $key => $package) {
  128.                         if ($package instanceof DataObject\Package) {
  129.                             if ($user instanceof DataObject\Customer) {
  130.                                 $subscription $this->setSubscription($package$usernull"default"true);
  131.                                 if ($subscription instanceof DataObject\Subscription) {
  132.                                     $subscriptionsArray[] = [
  133.                                         "id" => $subscription->getId(),
  134.                                         "key" => $subscription->getKey(),
  135.                                     ];
  136.                                 }
  137.                             }
  138.                         }
  139.                     }
  140.                     return ["success" => true"data" => $subscriptionsArray];
  141.                 }
  142.             }
  143.         } catch (\Exception $ex) {
  144.             throw new \Exception($ex->getMessage());
  145.         }
  146.         return $result;
  147.     }
  148.     public function editUser($params$translator): array
  149.     {
  150.         $updateUser DataObject\Customer::getById($params['id'], true);
  151.         if ($updateUser instanceof DataObject\Customer && !$updateUser->getIsDeleted()) {
  152.             $loggedInUserRole $params['loggedInUser']->getRole() ? $params['loggedInUser']->getRole()->getName() : null;
  153.             $updateOrganization $updateUser->getOrganization();
  154.             // Update client type for NCM_IT role
  155.             if (!empty($params['client_type'])) {
  156.                 if ($loggedInUserRole == USER_ROLES['NCM_IT']  || $loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && $updateOrganization) {
  157.                     $updateOrganization->setCilent_type($params['client_type']);
  158.                     $updateOrganization->setClientType($params['client_type']);
  159.                     $updateOrganization->save();
  160.                 } else {
  161.                     return [
  162.                         "success" => false,
  163.                         "message" => $translator->trans("access_denied_to_update_organization_client_type")
  164.                     ];
  165.                 }
  166.             }
  167.             // Update entity status with validation
  168.             if (!empty($params['entity_status'])) {
  169.                 $allowedStatuses = ['paid''trial''expired'];
  170.                 if (in_array($params['entity_status'], $allowedStatuses)) {
  171.                     if (in_array($loggedInUserRole, [USER_ROLES['NCM_IT'], USER_ROLES['NCM_OPERATOR']]) && $updateOrganization) {
  172.                         if ($params['client_type'] == "government") {
  173.                             $updateOrganization->setStatus("paid");
  174.                         } else {
  175.                             $updateOrganization->setStatus($params['entity_status']);
  176.                         }
  177.                         if ($params['entity_status'] == "trial") {
  178.                             if (empty($params['trialLimit'])) {
  179.                                 return [
  180.                                     "success" => false,
  181.                                     "message" => $translator->trans("trial_limit_is_required")
  182.                                 ];
  183.                             }
  184.                             if ($updateOrganization->getStatus() == "expired") {
  185.                                 $updateOrganization->setPackageActivationDate(Carbon::now());
  186.                             }
  187.                             $updateOrganization->setTrialLimit($params['trialLimit']);
  188.                         }
  189.                         $updateOrganization->save();
  190.                     }
  191.                 }
  192.             }
  193.             // Update company name in English
  194.             if (!empty($params['company_name_en'])) {
  195.                 if ($loggedInUserRole == USER_ROLES['NCM_IT'] || $loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && $updateOrganization) {
  196.                     // Check if the name already exists for another organization
  197.                     $existingOrganization DataObject\Organization::getByName($params['company_name_en'], 'en', ['limit' => 1'unpublished' => true]);
  198.                     if ($existingOrganization && $existingOrganization->getId() !== $updateOrganization->getId()) {
  199.                         return [
  200.                             "success" => false,
  201.                             "message" => $translator->trans("organization_already_exists") . " : " $params['company_name_en']
  202.                         ];
  203.                     }
  204.                     $updateOrganization->setName($params['company_name_en'], 'en');
  205.                     $updateOrganization->setKey(trim(strip_tags($params['company_name_en']))); // Update key to match new name
  206.                     $updateOrganization->save();
  207.                 } else {
  208.                     return [
  209.                         "success" => false,
  210.                         "message" => $translator->trans("access_denied_to_update_organization_company_name_en")
  211.                     ];
  212.                 }
  213.             }
  214.             // Update company name in Arabic
  215.             if (!empty($params['company_name_ar'])) {
  216.                 if ($loggedInUserRole == USER_ROLES['NCM_IT'] || $loggedInUserRole == USER_ROLES['NCM_OPERATOR'] && $updateOrganization) {
  217.                     $updateOrganization->setName($params['company_name_ar'], 'ar');
  218.                     $updateOrganization->save();
  219.                 } else {
  220.                     return [
  221.                         "success" => false,
  222.                         "message" => $translator->trans("access_denied_to_update_organization_company_name_ar")
  223.                     ];
  224.                 }
  225.             }
  226.             // Update user details (name, password, phone, etc.)
  227.             if (!empty($params['name'])) {
  228.                 $updateUser->setName(strip_tags($params['name']));
  229.             }
  230.             if (!empty($params['password'])) {
  231.                 $updateUser->setPassword(strip_tags($params['password']));
  232.             }
  233.             // update phone number
  234.             if (!empty($params['phone'])) {
  235.                 $phone trim($params['phone']);
  236.                 if (strlen($phone) !== 9) {
  237.                     return ["success" => false"message" => $translator->trans("phone_no_must_be_9_digits")];
  238.                 } elseif (!ctype_digit($phone)) {
  239.                     return ["success" => false"message" => $translator->trans("phone_no_must_be_numeric")];
  240.                 } else {
  241.                     $updateUser->setPhoneNo($phone);
  242.                 }
  243.             } else if (empty($params['phone']) && isset($params['phone'])) {
  244.                 $updateUser->setPhoneNo("");
  245.             }
  246.             // Set user role if provided
  247.             if (!empty($params['role'])) {
  248.                 $userRole DataObject\UserRole::getByName(USER_ROLES[$params['role']], true);
  249.                 if ($userRole instanceof DataObject\UserRole) {
  250.                     // Prevent role update if it would leave no admin in the organization
  251.                     if ($params['role'] == USER_ROLES['CLIENT_USER'] && $updateUser->getRole()->getName() == USER_ROLES['CLIENT_ADMIN']) {
  252.                         $adminRole DataObject\UserRole::getByName(USER_ROLES['CLIENT_ADMIN'], true);
  253.                         $adminCount = new DataObject\Customer\Listing();
  254.                         $adminCount->filterByOrganization($updateUser->getOrganization());
  255.                         $adminCount->filterByRole($adminRole);
  256.                         $adminCount->filterByIsActive(true);
  257.                         if ($adminCount->getCount() <= 1) {
  258.                             return [
  259.                                 "success" => false,
  260.                                 "message" => $translator->trans('atleast_one_admin_required')
  261.                             ];
  262.                         }
  263.                     }
  264.                     $updateUser->setRole($userRole);
  265.                     // Update default Package according to role
  266.                     $rolePackage $userRole->getDefaultPackages();
  267.                     if ($rolePackage) {
  268.                         foreach ($rolePackage as $package) {
  269.                             if ($package instanceof DataObject\Package) {
  270.                                 $this->updateSubscription($package$updateUsernull"default");
  271.                             }
  272.                         }
  273.                     }
  274.                 }
  275.             }
  276.             // Set department and title if provided
  277.             if (!empty($params['department'])) {
  278.                 $updateUser->setDepartment(strip_tags($params['department']));
  279.             }
  280.             if (!empty($params['title'])) {
  281.                 $updateUser->setTitle(strip_tags($params['title']));
  282.             }
  283.             // Assign location by location tag id to user
  284.             if (!empty($params['location_tag_ids'])) {
  285.                 $this->assignLocationToUser($params['loggedInUser'], null$params['location_tag_ids'], [$updateUser->getId()], nullfalsefalse$translator);
  286.             }
  287.             $updateUser->save();
  288.             // Add updated user to updated permissions
  289.             $params['user'] = $updateUser;
  290.             // Package subscription update
  291.             if (!empty($params['package_id'])) {
  292.                 $package DataObject\Package::getById($params['package_id'], true);
  293.                 if ($package instanceof DataObject\Package) {
  294.                     $this->updateSubscription($package$params['user'], null"custom");
  295.                 }
  296.             }
  297.             if (isset($params['disallowedApiGroups'])) {
  298.                 $this->disallowApiGroups($params['user'], $params['disallowedApiGroups'], "custom");
  299.             }
  300.             // Handle location assignment for CLIENT_ADMIN or CLIENT_USER roles
  301.             if (in_array($params['role'], [USER_ROLES['CLIENT_ADMIN'], USER_ROLES['CLIENT_USER']])) {
  302.                 if (isset($params['location'])) {
  303.                     foreach ($params['location'] as $value) {
  304.                         $location DataObject\Location::getById($valuetrue);
  305.                         if ($location) {
  306.                             $this->locationModel->locationMetaData($location$updateUser);
  307.                         }
  308.                     }
  309.                 }
  310.             }
  311.             return [
  312.                 "success" => true,
  313.                 "message" => $translator->trans("user_updated_successfully")
  314.             ];
  315.         }
  316.         return [
  317.             "success" => false,
  318.             "message" => $translator->trans("user_does_not_exist")
  319.         ];
  320.     }
  321.     public function editNCMUser($params$translator): array
  322.     {
  323.         $result = [];
  324.         // try {
  325.         $updateUser DataObject\Customer::getById($params['id'], true);
  326.         if ($updateUser instanceof DataObject\Customer && $updateUser->getIsDeleted() != true) {
  327.             $loggedInUserRole $params['loggedInUser']->getRole() ? $params['loggedInUser']->getRole()->getName() : null;
  328.             if (isset($params['name']) && !empty($params['name'])) {
  329.                 $updateUser->setName(strip_tags($params['name']));
  330.             }
  331.             // Set Role if $UserRole is provided
  332.             if (isset($params['role']) && !empty($params['role'])) {
  333.                 $UserRole DataObject\UserRole::getByName(USER_ROLES[$params['role']], true);
  334.                 if ($UserRole instanceof DataObject\UserRole) {
  335.                     $updateUser->setRole($UserRole);
  336.                     // Update default Package according to role
  337.                     $rolePackage $UserRole->getDefaultPackages();
  338.                     if ($rolePackage) {
  339.                         foreach ($rolePackage as $key => $package) {
  340.                             if ($package instanceof DataObject\Package) {
  341.                                 $this->updateSubscription($package$updateUsernull"default");
  342.                             }
  343.                         }
  344.                     }
  345.                 }
  346.             }
  347.             // update password
  348.             if (isset($params['password']) && !empty($params['password'])) {
  349.                 $updateUser->setPassword(strip_tags($params['password']));
  350.             }
  351.             // updated permissions 
  352.             if (isset($params['allowedApiGrpups']) && !empty($params['allowedApiGrpups'])) {
  353.                 $this->updateNCMUserSubscription($updateUser$params['allowedApiGrpups']);
  354.             }
  355.             // update permission user groups
  356.             if (isset($params['permissionUserGroupIds']) && !empty($params['permissionUserGroupIds'])) {
  357.                 // Validate and prepare permission groups
  358.                 $permissionGroups = [];
  359.                 foreach ($params['permissionUserGroupIds'] as $groupId) {
  360.                     $permissionGroup PermissionGroup::getById($groupId);
  361.                     if ($permissionGroup) {
  362.                         $permissionGroups[] = $permissionGroup;
  363.                     }
  364.                 }
  365.                 $updateUser->setPermissionGroups($permissionGroups);
  366.             }
  367.             // assign user tag to user
  368.             if (isset($params['tagId']) && !empty($params['tagId'])) {
  369.                 $tage  UserTag::getById($params['tagId']);
  370.                 if ($tage instanceof UserTag) {
  371.                     $updateUser->setTag($tage);
  372.                 }
  373.             }
  374.             if (isset($params['phone']) && !empty($params['phone'])) {
  375.                 $updateUser->setPhoneNo(strip_tags($params['phone']));
  376.             }
  377.             $updateUser->save();
  378.             // unset($params["Authorization"]);
  379.             // $params["loggedInUserEmail"] = $loggedInUserRole = $params['loggedInUser']->getEmail();
  380.             // $ncmReportingUser = $this->reportingPortalModel->updateNcmUser($params);
  381.             // $ewsPortalUser = $this->ewsPortalModel->updateNcmUser($params);
  382.             return ["success" => true"message" => $translator->trans("user_updated_successifully")];
  383.         }
  384.         return ["success" => false"message" => $translator->trans("user_does_not_exists")];
  385.         // } catch (\Exception $ex) {
  386.         //     throw new \Exception($ex->getMessage());
  387.         // }
  388.         return $result;
  389.     }
  390.     public function disallowApiGroups($user$disallowedApiGroups$type)
  391.     {
  392.         $result = [];
  393.         if (!$user instanceof DataObject\Customer) {
  394.             return ["success" => false"message" => "User is not available"];
  395.         }
  396.         $customSubscriptions = new DataObject\Subscription\Listing();
  397.         $customSubscriptions->filterBySubscribedUser($user);
  398.         $customSubscriptions->filterBySubscriptionType("custom");
  399.         $customSubscriptions->filterByIsActive(true);
  400.         $updateSubscription $customSubscriptions->current();
  401.         if ($updateSubscription instanceof  DataObject\Subscription) {
  402.             //Set Disallowed ApiGroups
  403.             if ($disallowedApiGroups != null) {
  404.                 $disallowedApiGroupsArr = [];
  405.                 foreach ($disallowedApiGroups as $disallowedApiGroupsId) {
  406.                     $apiGroup =  DataObject\APIGroup::getById($disallowedApiGroupsIdtrue);
  407.                     $disallowedApiGroupsArr[] = $apiGroup;
  408.                 }
  409.                 $updateSubscription->setDisallowedApiGroups($disallowedApiGroupsArr);
  410.             } else {
  411.                 $updateSubscription->setDisallowedApiGroups(null);
  412.             }
  413.             $updateSubscription->save();
  414.         }
  415.         return  $updateSubscription;
  416.     }
  417.     public function updateUserGroupData(
  418.         $loggedInUser,
  419.         $locations,
  420.         $locationTagIds,
  421.         $userGroupId,
  422.         $userIds,
  423.         $request,
  424.         $lang,
  425.         $translator
  426.     ): array {
  427.         $result = [];
  428.         try {
  429.             $userGroup DataObject\UserGroup::getById($userGroupIdtrue);
  430.             if (!$userGroup instanceof DataObject\UserGroup) {
  431.                 return ["success" => false"message" => $translator->trans("user_group_is_not_available")];
  432.             }
  433.             if (count($userIds) > 0) {
  434.                 foreach ($userIds as $key => $userId) {
  435.                     $user DataObject\Customer::getById($userIdtrue);
  436.                     $userGroupArr[] =  $userGroup;
  437.                     foreach ($user->getUserGroup() as $group) {
  438.                         $userGroupArr[] = $group;
  439.                     }
  440.                     $userGroupArr array_unique($userGroupArr);
  441.                     if ($user instanceof DataObject\Customer) {
  442.                         $user->setUserGroup($userGroupArr);
  443.                         $user->save();
  444.                     }
  445.                 }
  446.                 // Assign location by location tag id to user
  447.                 if (isset($locationTagIds) && !empty($locationTagIds)) {
  448.                     $assignLocationByLocationTagId $this->assignLocationToUser($loggedInUser$locations$locationTagIds$userIdsnullfalsefalse$translator);
  449.                     if (isset($assignLocationByLocationTagId['success']) && $assignLocationByLocationTagId['success'] == false) {
  450.                         return $assignLocationByLocationTagId;
  451.                     }
  452.                 }
  453.                 return ["success" => true"message" => $translator->trans("user_group_are_updated_successfully ")];
  454.             }
  455.             return ["success" => false"message" => $translator->trans("user_group_not_available")];
  456.         } catch (\Exception $ex) {
  457.             throw new \Exception($ex->getMessage());
  458.         }
  459.         return $result;
  460.     }
  461.     public function createUserGroupData($user$groupNameEn$groupNameAr$detailEn$detailAr$groupId$request$lang$translator): array
  462.     {
  463.         $result = [];
  464.         try {
  465.             $organization $user->getOrganization();
  466.             if (!$organization instanceof DataObject\Organization) {
  467.                 return ["success" => false"message" => $translator->trans("user_does_not_belongs_to_organization ")];
  468.             }
  469.             $userGroup = new DataObject\UserGroup\Listing();
  470.             $userGroup->setLocale($lang);
  471.             $userGroup->setCondition("groupName = ? ", [$groupNameEn]);
  472.             $userGroup->filterByOrganization($organization);
  473.             $userGroup $userGroup->current();
  474.             if ($userGroup instanceof DataObject\UserGroup) {
  475.                 return ["success" => false"message" => $translator->trans("user_group_name_already_available")];
  476.             }
  477.             if (!empty($groupId)) {
  478.                 $userGroup DataObject\UserGroup::getById($groupIdtrue);
  479.                 if (!$userGroup instanceof DataObject\UserGroup) {
  480.                     return ["success" => false"message" => $translator->trans("user_group_is_not_available")];
  481.                 }
  482.                 $userGroup->setKey(trim(strip_tags($groupNameEn)));
  483.                 $userGroup->setGroupName($groupNameEn'en');
  484.                 $userGroup->setGroupName($groupNameAr'ar');
  485.                 $userGroup->setDetail($detailEn'en');
  486.                 $userGroup->setDetail($detailAr'ar');
  487.                 $userGroup->save();
  488.                 if ($userGroup) {
  489.                     return ["success" => true"message" => $translator->trans("user_group_updated_successfully")];
  490.                 }
  491.             }
  492.             $userGroup = new DataObject\UserGroup();
  493.             $userGroup->setParent(DataObject\Service::createFolderByPath('/UserManagement/UserGroups/' $organization->getName()));
  494.             $userGroup->setKey(trim(strip_tags($groupNameEn)));
  495.             $userGroup->setGroupName($groupNameEn'en');
  496.             $userGroup->setGroupName($groupNameAr'ar');
  497.             $userGroup->setDetail($detailEn'en');
  498.             $userGroup->setDetail($detailAr'ar');
  499.             $userGroup->setOrganization($organization);
  500.             $userGroup->setPublished(true);
  501.             $userGroup->save();
  502.             if ($userGroup) {
  503.                 return ["success" => true"message" => $translator->trans("user_group_created_successfully"), "user_group_id" => $userGroup->getId()];
  504.             }
  505.         } catch (\Exception $ex) {
  506.             throw new \Exception($ex->getMessage());
  507.         }
  508.         return $result;
  509.     }
  510.     public function editUserGroupData($id$groupNameEn$groupNameAr$detailEn$detailAr$request$lang$translator): array
  511.     {
  512.         $result = [];
  513.         try {
  514.             $userGroup DataObject\UserGroup::getById($idtrue);
  515.             if (!$userGroup instanceof DataObject\UserGroup) {
  516.                 return ["success" => false"message" => $translator->trans("user_group_is_not_available")];
  517.             }
  518.             if (isset($groupNameEn) && !empty($groupNameEn)) {
  519.                 $userGroup->setGroupName($groupNameEn'en');
  520.             }
  521.             if (isset($groupNameAr) && !empty($groupNameAr)) {
  522.                 $userGroup->setGroupName($groupNameAr'ar');
  523.             }
  524.             if (isset($detailEn) && !empty($detailEn)) {
  525.                 $userGroup->setDetail($detailEn'en');
  526.             }
  527.             if (isset($detailAr) && !empty($detailAr)) {
  528.                 $userGroup->setDetail($detailAr'ar');
  529.             }
  530.             $userGroup->save();
  531.             if ($userGroup) {
  532.                 return ["success" => true"message" => $translator->trans("user_group_updated_successfully")];
  533.             }
  534.         } catch (\Exception $ex) {
  535.             throw new \Exception($ex->getMessage());
  536.         }
  537.         return $result;
  538.     }
  539.     public function deleteUserGroup($user$id$request$translator): array
  540.     {
  541.         $result = [];
  542.         try {
  543.             $userGroup DataObject\UserGroup::getById($idtrue);
  544.             if (!$userGroup instanceof DataObject\UserGroup) {
  545.                 return ["success" => false"message" => $translator->trans("user_group_is_not_available")];
  546.             }
  547.             if (!$userGroup->getOrganization()) {
  548.                 return ["success" => false"message" => $translator->trans("no_organization_is_assigned_to_this_user_group")];
  549.             }
  550.             $loggedInUserOrganizationName $user->getOrganization() ? $user->getOrganization()->getName() : '';
  551.             if ($userGroup->getOrganization()->getName("en") != $loggedInUserOrganizationName) {
  552.                 return ["success" => false"message" => $translator->trans("user_group_is_not_assigned_to_your_organization")];
  553.             }
  554.             $userGroup->delete();
  555.             return ["success" => true"message" => $translator->trans("user_group_deleted_successifully")];
  556.         } catch (\Exception $ex) {
  557.             throw new \Exception($ex->getMessage());
  558.         }
  559.         return $result;
  560.     }
  561.     public function userGroupListing($user$translator$paginator$params): array
  562.     {
  563.         $result = [];
  564.         try {
  565.             $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  566.             $page = isset($params['page']) ? $params['page'] : 1;
  567.             $lang = isset($params['lang']) ? $params['lang'] : 'en';
  568.             $organization $user->getOrganization();
  569.             if (!$organization instanceof DataObject\Organization) {
  570.                 return ["success" => false"message" => $translator->trans("user_does_not_belongs_to_organization ")];
  571.             }
  572.             // Load LocationGroup listing
  573.             $userGroupList = new DataObject\UserGroup\Listing();
  574.             $userGroupList->filterByOrganization($organization);
  575.             $userGroupList->setLocale($lang);
  576.             if (isset($params['search']) && !empty($params['search'])) {
  577.                 $userGroupList->addConditionParam('(groupName LIKE ? OR detail LIKE ?)', ['%' $params['search'] . '%''%' $params['search'] . '%']);
  578.             }
  579.             $userGroupList->setOrderKey("oo_id");
  580.             $userGroupList->setOrder("desc");
  581.             $paginator $paginator->paginate(
  582.                 $userGroupList,
  583.                 $page,
  584.                 $pageSize
  585.             );
  586.             if ($paginator->getTotalItemCount() > 0) {
  587.                 $userGroupListData = [];
  588.                 foreach ($paginator as $key => $userGroup) {
  589.                     $userListData = [];
  590.                     $usersList = new DataObject\Customer\Listing();
  591.                     $usersList->filterByUserGroup($userGroup);
  592.                     $usersList->setOrderKey("oo_id");
  593.                     $usersList->setOrder("desc");
  594.                     if ($usersList) {
  595.                         foreach ($usersList as $user) {
  596.                             $userListData[] = [
  597.                                 'id' => $user->getId(),
  598.                                 'name' => $user->getName(),
  599.                                 'email' => $user->getEmail(),
  600.                                 'role' => $user->getRole() ? $user->getRole()->getName() : '',
  601.                                 'organization' => $user->getOrganization() ?  $user->getOrganization()->getName() : '',
  602.                             ];
  603.                         }
  604.                     }
  605.                     $userGroupListData[] = [
  606.                         'id' => $userGroup->getId(),
  607.                         'groupName_en' => $userGroup->getGroupName("en"),
  608.                         'detail_en' => $userGroup->getDetail("en"),
  609.                         'groupName_ar' => $userGroup->getGroupName("ar"),
  610.                         'detail_ar' => $userGroup->getDetail("ar"),
  611.                         'usersData' => $userListData
  612.                     ];
  613.                 }
  614.                 if (!empty($userGroupListData) && count($userGroupListData) > 0) {
  615.                     return ["success" => true"data" => $userGroupListData"paginationVariables" => $paginator->getPaginationData()];
  616.                 }
  617.             }
  618.             return ["success" => false"message" => $translator->trans("user_groups_are_not_available")];
  619.         } catch (\Exception $ex) {
  620.             throw new \Exception($ex->getMessage());
  621.         }
  622.         return $result;
  623.     }
  624.     public function userGroupDetail($user$userGroupId$translator): array
  625.     {
  626.         $result = [];
  627.         try {
  628.             $organization $user->getOrganization();
  629.             if (!$organization instanceof DataObject\Organization) {
  630.                 return ["success" => false"message" => $translator->trans("user_does_not_belongs_to_organization")];
  631.             }
  632.             $userGroupData = [];
  633.             $userListData = [];
  634.             $data = [];
  635.             $totalUsers  0;
  636.             //load user group
  637.             $userGroup = new DataObject\UserGroup\Listing();
  638.             $userGroup->setCondition("oo_id = ? ", [$userGroupId]);
  639.             $userGroup->filterByOrganization($organization);
  640.             $userGroup $userGroup->current();
  641.             if ($userGroup instanceof DataObject\UserGroup) {
  642.                 //get user group data   
  643.                 $userGroupData[] = [
  644.                     'id' => $userGroup->getId(),
  645.                     'groupName_en' => $userGroup->getGroupName("en"),
  646.                     'detail_en' => $userGroup->getDetail("en"),
  647.                     'groupName_ar' => $userGroup->getGroupName("ar"),
  648.                     'detail_ar' => $userGroup->getDetail("ar"),
  649.                 ];
  650.                 //get all users available in above user group
  651.                 $customers = new DataObject\Customer\Listing();
  652.                 $customers->filterByOrganization($organization);
  653.                 $customers->filterByUserGroup($userGroup);
  654.                 $customers->filterByIsActive(true);
  655.                 if ($customers->getCount() > 0) {
  656.                     $totalUsers $customers->getCount();
  657.                     foreach ($customers as $key => $customer) {
  658.                         if ($customer instanceof DataObject\Customer) {
  659.                             //get user  data   
  660.                             $userListData[] = [
  661.                                 'id' => $customer->getId(),
  662.                                 'name' => $customer->getName(),
  663.                                 'email' => $customer->getEmail(),
  664.                                 'role' => $customer->getRole() ? $customer->getRole()->getName() : null,
  665.                                 'department' => $customer->getDepartment(),
  666.                                 'titile' => $customer->getTitle()
  667.                             ];
  668.                         }
  669.                     }
  670.                     // store all data in data array
  671.                     $data[] = [
  672.                         "userGroupData" => $userGroupData,
  673.                         "totalUsers" => $totalUsers,
  674.                         "users" => $userListData
  675.                     ];
  676.                     if (!empty($data) && count($data) > 0) {
  677.                         return ["success" => true"data" => $data];
  678.                     }
  679.                 }
  680.             }
  681.             return ["success" => false"message" => $translator->trans("user_group_is_not_available")];
  682.         } catch (\Exception $ex) {
  683.             throw new \Exception($ex->getMessage());
  684.         }
  685.         return $result;
  686.     }
  687.     public function updateProfile($params$translator): array
  688.     {
  689.         $result = [];
  690.         try {
  691.             $updateUser DataObject\Customer::getById($params['id'], true);
  692.             if ($updateUser) {
  693.                 try {
  694.                     $updateUser->setName(strip_tags($params['name']));
  695.                     $updateUser->setDepartment(strip_tags($params['department']));
  696.                     $updateUser->setTitle(strip_tags($params['title']));
  697.                     if (isset($params['isTwoFactorAuth'])) {
  698.                         if ($params['isTwoFactorAuth'] == true) {
  699.                             $updateUser->setTwoFactorAuth(true);
  700.                         } else {
  701.                             $updateUser->setTwoFactorAuth(false);
  702.                         }
  703.                     }
  704.                     if (isset($params['iqamaId']) && !empty($params['iqamaId'])) {
  705.                         if (\App\Lib\Utility::validateIqamaId($params['iqamaId'])) {
  706.                             $updateUser->setIqamaId($params['iqamaId']);
  707.                         } else {
  708.                             return ["success" => false"message" => $translator->trans("iqama_id_is_invalid")];
  709.                         }
  710.                     }
  711.                     if (!empty($params['phoneno'])) {
  712.                         $phoneNo trim($params['phoneno']);
  713.                         if (strlen($phoneNo) !== 9) {
  714.                             return ["success" => false"message" => $translator->trans("phone_no_must_be_9_digits")];
  715.                         } elseif (!ctype_digit($phoneNo)) {
  716.                             return ["success" => false"message" => $translator->trans("phone_no_must_be_numeric")];
  717.                         } else {
  718.                             $updateUser->setPhoneNo($phoneNo);
  719.                         }
  720.                     }
  721.                     $updateUser->save();
  722.                     if (!isset($params['from_ews']) && !isset($params['from_reporting'])) {
  723.                         unset($params["Authorization"]);
  724.                         $params["userEmail"] = $updateUser->getEmail();
  725.                         $params["from_portal"] = true;
  726.                         // Inform other systems
  727.                         // $this->ewsPortalModel->updateProfile($params);
  728.                         // $this->reportingPortalModel->updateProfile($params);
  729.                     }
  730.                     return ["success" => true"message" => $translator->trans("user_updated_successfully")];
  731.                 } catch (\Exception $ex) {
  732.                     return ["success" => false"message" => $translator->trans("user_not_updated_successfully")];
  733.                 }
  734.             }
  735.             return ["success" => false"message" => $translator->trans("user_does_not_exists")];
  736.         } catch (\Exception $ex) {
  737.             throw new \Exception($ex->getMessage());
  738.         }
  739.         return $result;
  740.     }
  741.     /**
  742.      * forget user password
  743.      */
  744.     public function forgotPassword($request$email$httpOrigin$translator$templating)
  745.     {
  746.         $result = [];
  747.         try {
  748.             $lang $translator->getLocale();
  749.             $user DataObject\Customer::getByEmail($emailtrue);
  750.             if ($user instanceof \Pimcore\Model\DataObject\Customer) {
  751.                 //generate token
  752.                 $token md5($user->getId() . time() . uniqid());
  753.                 $user->setResetPasswordToken($token);
  754.                 //$user->setPasswordRecoveryTokenDate(Carbon::now());
  755.                 $user->save();
  756.                 $role = ($user->getRole()) ? $user->getRole()->getName() : null;
  757.                 $hostName $httpOrigin "/auth/reset-password?token=";
  758.                 if ($role == 'CLIENT_ADMIN' || $role == 'CLIENT_USER') {
  759.                     $subject $translator->trans("Reset Password to Join NCM Business Portal");
  760.                     $title $translator->trans("Meteo KSA");
  761.                 } else {
  762.                     $subject $translator->trans("Reset Password to Join NCM Admin Portal");
  763.                     $title $translator->trans("Meteo KSA Admin");
  764.                 }
  765.                 $param = [
  766.                     'userName' => $user->getName(),
  767.                     'tokenLink' => $hostName $token,
  768.                     'title' => $title,
  769.                 ];
  770.                 $html $templating->render('web2print/generic_mail.html.twig'$param);
  771.                 $templateId $_ENV['RESET_PASSWORD_TEMPLATE'];
  772.                 $purpose RESET_PASSWORD_MESSAGE;
  773.                 $result $this->c2Service->sendNotificationEmail($templateId$user->getId(), $user->getId(), $html$subject$purpose);
  774.                 //$result = $this->emailService->sendMail($param, $user->getEmail(), PASSWORD_RECOVERY_EMAIL_DOCUMENT_PATH, $subject);
  775.                 $translator->setLocale($lang);
  776.                 if ($result) {
  777.                     return ["success" => true"message" => $translator->trans("account_reset_mail_sent_when_possible")];
  778.                 }
  779.                 return ["success" => false"message" => $translator->trans("an_error_occured_while_sending_mail")];
  780.             } else {
  781.                 return ["success" => false"message" => $translator->trans("user_not_found")];
  782.             }
  783.         } catch (\Exception $ex) {
  784.             throw new \Exception($ex->getMessage());
  785.         }
  786.         return $result;
  787.     }
  788.     /**
  789.      * Reset user password
  790.      */
  791.     public function resetPassword($request$token$newPassword$conformNewPassword$translator): array
  792.     {
  793.         $result = [];
  794.         try {
  795.             //check if the token is valid
  796.             $user DataObject\Customer::getByResetPasswordToken($tokentrue);
  797.             if ($user instanceof \Pimcore\Model\DataObject\Customer) {
  798.                 if ($newPassword != $conformNewPassword) {
  799.                     return ["success" => false"message" => $translator->trans("new_password_and_conformNewPassword_not_matching")];
  800.                 }
  801.                 $user->setPassword($newPassword);
  802.                 $user->setResetPasswordToken(null);
  803.                 $user->save();
  804.                 if ($user) {
  805.                     return ["success" => true"message" => $translator->trans("password_updated_successifully")];
  806.                 }
  807.             } else {
  808.                 return ["success" => false"message" => $translator->trans("user_not_found_token_is_not_valid")];
  809.             }
  810.         } catch (\Exception $ex) {
  811.             throw new \Exception($ex->getMessage());
  812.         }
  813.         return $result;
  814.     }
  815.     /**
  816.      * Reset user password
  817.      */
  818.     public function changePassword($user$params$translator): array
  819.     {
  820.         $result = [];
  821.         try {
  822.             if ($params['newPassword'] != $params['confirmNewPassword']) {
  823.                 return ["success" => false"message" => $translator->trans("new_password_and_conformNewPassword_not_matching")];
  824.             }
  825.             if ($user) {
  826.                 if (password_verify(trim($params['oldPassword']), $user->getPassword())) {
  827.                     $user->setPassword($params['newPassword']);
  828.                     $user->save();
  829.                     if (!isset($params['from_ews']) && !isset($params['from_reporting'])) {
  830.                         unset($params["Authorization"]);
  831.                         $params["userEmail"] = $user->getEmail();
  832.                         $params["from_portal"] = true;
  833.                         // Inform other systems
  834.                         // $this->ewsPortalModel->changePassword($params);
  835.                         // $this->reportingPortalModel->changePassword($params);
  836.                     }
  837.                     return ["success" => true"message" => $translator->trans("password_updated_successifully")];
  838.                 } else {
  839.                     return ["success" => false"message" => $translator->trans("old_password_is_not_correct")];
  840.                 }
  841.             }
  842.             return ["success" => false"message" => $translator->trans("user_does_not_exists")];
  843.         } catch (\Exception $ex) {
  844.             throw new \Exception($ex->getMessage());
  845.         }
  846.         return $result;
  847.     }
  848.     /**
  849.      * Get Public User Premissions
  850.      */
  851.     public function publicUserPermissions($translator): array
  852.     {
  853.         $result = [];
  854.         try {
  855.             $db Db::get();
  856.             $permissions $db->fetchAll("SELECT * FROM `policy`");
  857.             return ["success" => true"data" => $permissions];
  858.         } catch (\Exception $ex) {
  859.             throw new \Exception($ex->getMessage());
  860.         }
  861.         return $result;
  862.     }
  863.     /**
  864.      * Create Public User
  865.      */
  866.     public function addPublicUser($request$params$translator): array
  867.     {
  868.         $result = [];
  869.         try {
  870.             $user DataObject\PublicUser::getByName($params['name'], true);
  871.             if ($user instanceof DataObject\PublicUser) {
  872.                 return ["success" => false"message" => $translator->trans("This public user already exists.")];
  873.             }
  874.             $addPublicUser = new DataObject\PublicUser();
  875.             $addPublicUser->setParent(DataObject\Service::createFolderByPath('/UserManagement/PublicUsers/'));
  876.             $addPublicUser->setKey($params['name']);
  877.             $addPublicUser->setName($params['name']);
  878.             $addPublicUser->setStartDate(Carbon::parse($params['startDate']));
  879.             $addPublicUser->setEndDate(Carbon::parse($params['endDate']));
  880.             $addPublicUser->setPublished(true);
  881.             $addPublicUser->save();
  882.             if (!$addPublicUser->getId()) {
  883.                 throw new \Exception("Failed to create public user.");
  884.             }
  885.             $db Db::get();
  886.             foreach ($params['permissions'] as $parameter) {
  887.                 $permission $db->fetchOne("SELECT id FROM policy WHERE parameter = ?"$parameter);
  888.                 if ($permission) {
  889.                     $data = array(
  890.                         'user_id' => $addPublicUser->getId(),
  891.                         'policy_id' => $permission,
  892.                         'is_allowed' => 1
  893.                     );
  894.                     $insertResult $db->insert("user_policy"$data);
  895.                     if (!$insertResult) {
  896.                         throw new \Exception($translator->trans("Failed to associate permissions with the public user."));
  897.                     }
  898.                 } else {
  899.                     throw new \Exception($translator->trans("Permission not found for parameter: " $parameter));
  900.                 }
  901.             }
  902.             return ["success" => true"message" => $translator->trans("Public user created successfully.")];
  903.         } catch (\Exception $ex) {
  904.             return ["success" => false"message" => $ex->getMessage()];
  905.         }
  906.         return $result;
  907.     }
  908.     // public function deleteUser($request, $params, $translator): array
  909.     // {
  910.     //     $result = [];
  911.     //     // try {
  912.     //     $user = DataObject\Customer::getById($params['id'], true);
  913.     //     if ($user) {
  914.     //         // Deleting user location              
  915.     //         $locations = $this->locationModel->getLocationsByUserId($user->getId());
  916.     //         if ($locations) {
  917.     //             foreach ($locations as $location) {
  918.     //                 if ($location instanceof \Pimcore\Model\DataObject\Location) {
  919.     //                     $this->locationModel->deAssociateUserLocation($location, $user, $translator);
  920.     //                 }
  921.     //             }
  922.     //         }
  923.     //         // Deleting user custom notification
  924.     //         $customNotification = new \Pimcore\Model\DataObject\CustomNotification\Listing();
  925.     //         $customNotification->filterByUser($user);
  926.     //         foreach ($customNotification as $notification) {
  927.     //             $notification->delete();
  928.     //         }
  929.     //         $user->delete();
  930.     //         return ["success" => true, "message" => $translator->trans("user_deleted_successifully")];
  931.     //     }
  932.     //     return ["success" => false, "message" => $translator->trans("user_does_not_exists")];
  933.     //     // } catch (\Exception $ex) {
  934.     //     //     throw new \Exception($ex->getMessage());
  935.     //     // }
  936.     //     return $result;
  937.     // }
  938.     public function deleteUser($request$params$loggedInUser$translator): array
  939.     {
  940.         $result = [];
  941.         // Check if the user is already deleted
  942.         $deletedUsers = new DataObject\DeletedUsersData\Listing();
  943.         $deletedUsers->filterByPimId($params['id']);
  944.         $deletedUsers->filterByIsDeleted(false);
  945.         $check $deletedUsers->current();
  946.         if ($check instanceof DataObject\DeletedUsersData) {
  947.             return ["success" => false"message" => $translator->trans("user_already_deleted")];
  948.         }
  949.         // Fetch the user by ID
  950.         $user DataObject\Customer::getById($params['id'], true);
  951.         if (!$user) {
  952.             return ["success" => false"message" => $translator->trans("user_does_not_exists")];
  953.         }
  954.         // Deactivate and save the user
  955.         $user->setToken(null);
  956.         $user->setIsDeleted(true);
  957.         $user->setPublished(false);
  958.         $user->save();
  959.         // Update created-by references: mark status as deleted and clear relation
  960.         $createdUsers = new DataObject\Customer\Listing();
  961.         $createdUsers->filterByCreatedBy($user);
  962.         foreach ($createdUsers as $createdUser) {
  963.             if ($createdUser instanceof DataObject\Customer) {
  964.                 $createdUser->setCreatedBy(null);
  965.                 $createdUser->setCreatedByUserStatus('deleted');
  966.                 $createdUser->save();
  967.             }
  968.         }
  969.         // Create a deleted user record
  970.         $deleteUserRecord = new DataObject\DeletedUsersData();
  971.         $deleteUserRecord->setParent(DataObject\Service::createFolderByPath('/UserManagement/DeletedUsers/'));
  972.         $deleteUserRecord->setKey($user->getName() . strtotime("now") . rand(0100));
  973.         $deleteUserRecord->setName($user->getName());
  974.         $deleteUserRecord->setEmail($user->getEmail());
  975.         $deleteUserRecord->setPimId($user->getId());
  976.         $deleteUserRecord->setOrganizationName($user->getOrganization() ? $user->getOrganization()->getName() : '');
  977.         $deleteUserRecord->setRole($user->getRole() ? $user->getRole()->getName() : '');
  978.         $deleteUserRecord->setIsDeleted(false);
  979.         $deleteUserRecord->setDeletedBy($loggedInUser->getEmail());
  980.         $deleteUserRecord->setPublished(true);
  981.         $deleteUserRecord->save();
  982.         // Delete user dependencies (locations)
  983.         $locations $this->locationModel->getLocationsByUserId($user->getId());
  984.         if ($locations) {
  985.             foreach ($locations as $location) {
  986.                 if ($location instanceof \Pimcore\Model\DataObject\Location) {
  987.                     $this->locationModel->deAssociateUserLocation($location$user$translator);
  988.                 }
  989.             }
  990.         }
  991.         // Delete user custom notifications
  992.         $customNotification = new \Pimcore\Model\DataObject\CustomNotification\Listing();
  993.         $customNotification->filterByUser($user);
  994.         foreach ($customNotification as $notification) {
  995.             $notification->delete();
  996.         }
  997.         // Delete user dashboard
  998.         $dashboard = new DataObject\Dashboard\Listing();
  999.         $dashboard->setCondition('user__id = ?', [$user->getId()]);
  1000.         if ($dashboard->current() instanceof DataObject\Dashboard) {
  1001.             $dashboard->current()->delete();
  1002.         }
  1003.         // Delete user subscriptions
  1004.         $subscriptions = new DataObject\Subscription\Listing();
  1005.         $subscriptions->setCondition('subscribedUser__id = ?', [$user->getId()]);
  1006.         foreach ($subscriptions as $subscription) {
  1007.             if ($subscription instanceof DataObject\Subscription) {
  1008.                 $subscription->delete();
  1009.             }
  1010.         }
  1011.         // Finalize user deletion
  1012.         $user->delete();
  1013.         // Mark the deleted user record as deleted
  1014.         $deleteUserRecord->setIsDeleted(true);
  1015.         $deleteUserRecord->save();
  1016.         return ["success" => true"message" => $translator->trans("user_deleted_successfully")];
  1017.     }
  1018.     /**
  1019.      * Get Client User Organization List
  1020.      */
  1021.     public function getClientUsers($request$user$params$paginator$translator)
  1022.     {
  1023.         $result = [];
  1024.         $userData = [];
  1025.         // try {
  1026.         // Get All the Classes
  1027.         $class = new \Pimcore\Model\DataObject\ClassDefinition();
  1028.         $customer $class->getDao()->getIdByName('Customer');
  1029.         $subscription $class->getDao()->getIdByName('Subscription');
  1030.         $userRole $class->getDao()->getIdByName('UserRole');
  1031.         $organization $class->getDao()->getIdByName('Organization');
  1032.         $package $class->getDao()->getIdByName('Package');
  1033.         $db Db::get();
  1034.         $select $db->createQueryBuilder();
  1035.         $select->select('customer.oo_id');
  1036.         $select->from('object_' $customer'customer');
  1037.         // Use LEFT JOIN for subscriptions to handle suspended users (users without subscriptions)
  1038.         $select->leftJoin('customer''object_' $subscription'subscription''customer.oo_id = subscription.subscribedUser__id');
  1039.         $select->leftJoin('subscription''object_' $package'package''package.oo_id = subscription.subscribedPackage__id');
  1040.         $select->innerJoin('customer''object_' $organization'organization''organization.oo_id = customer.organization__id');
  1041.         $select->innerJoin('customer''object_' $userRole'userRole''userRole.oo_id = customer.role__id');
  1042.         // Use placeholders to prevent SQL injection
  1043.         if (isset($params['clientType']) && !empty($params['clientType'])) {
  1044.             $select->Where("organization.clientType = " $db->quote($params['clientType']));
  1045.         }
  1046.         if (isset($params['organization_id']) && !empty($params['organization_id'])) {
  1047.             $select->andWhere("organization.oo_id = " $db->quote($params['organization_id']));
  1048.         }
  1049.         if (isset($params['package_id']) && !empty($params['package_id'])) {
  1050.             $select->andWhere("package.oo_id = " $db->quote($params['package_id']));
  1051.         }
  1052.         if (isset($params['search']) && !empty($params['search'])) {
  1053.             $select->andWhere("customer.name LIKE " $db->quote("%" $params['search'] . "%") . " OR customer.email LIKE " $db->quote("%" $params['search'] . "%"));
  1054.         }
  1055.         if (isset($params['userStatus']) && !empty($params['userStatus'])) {
  1056.             $filterStatus strtolower(trim($params['userStatus']));
  1057.             // Validate that the filter status is one of the allowed values
  1058.             $allowedStatuses = ['pending''active''suspended''activepending'];
  1059.             if (in_array($filterStatus$allowedStatuses)) {
  1060.                 switch ($filterStatus) {
  1061.                     case 'pending':
  1062.                         // Pending: user is unpublished, no custom subscription, has default subscription
  1063.                         $select->andWhere("customer.o_published = 0");
  1064.                         $select->andWhere("subscription.subscriptionType != 'custom'");
  1065.                         $select->andWhere("subscription.subscribedUser__id IS NOT NULL");
  1066.                         $select->andWhere("subscription.isWso IS NULL OR subscription.isWso = 0");
  1067.                         $select->andWhere("userRole.name IN ('CLIENT_USER', 'CLIENT_ADMIN')");
  1068.                         break;
  1069.                     case 'active':
  1070.                         // Active: user is published, has custom subscription, isActive = true
  1071.                         $select->andWhere("customer.o_published = 1");
  1072.                         $select->andWhere("subscription.subscriptionType = 'custom'");
  1073.                         $select->andWhere("subscription.subscribedUser__id IS NOT NULL");
  1074.                         $select->andWhere("subscription.isActive = 1");
  1075.                         $select->andWhere("subscription.isWso IS NULL OR subscription.isWso = 0");
  1076.                         $select->andWhere("userRole.name IN ('CLIENT_USER', 'CLIENT_ADMIN')");
  1077.                         break;
  1078.                     case 'suspended':
  1079.                         // Suspended: user is published, has custom subscription, isActive = false
  1080.                         $select->andWhere("customer.o_published = 1");
  1081.                         $select->andWhere("subscription.subscriptionType = 'custom'");
  1082.                         $select->andWhere("subscription.subscribedUser__id IS NOT NULL");
  1083.                         $select->andWhere("subscription.isActive = 0");
  1084.                         break;
  1085.                     
  1086.                     case 'activepending':
  1087.                         // Active OR Pending
  1088.                         $select->andWhere("((customer.o_published = 0 AND subscription.subscriptionType != 'custom' AND subscription.subscribedUser__id IS NOT NULL) OR (customer.o_published = 1 AND subscription.subscriptionType = 'custom' AND subscription.subscribedUser__id IS NOT NULL AND subscription.isActive = 1))");
  1089.                         $select->andWhere("subscription.isWso IS NULL OR subscription.isWso = 0");
  1090.                         $select->andWhere("userRole.name IN ('CLIENT_USER', 'CLIENT_ADMIN')");
  1091.                         break;
  1092.                 }
  1093.             }
  1094.         }
  1095.         $select->andWhere("userRole.name = " $db->quote(USER_ROLES['CLIENT_ADMIN']) . " OR userRole.name = " $db->quote(USER_ROLES['CLIENT_USER']));
  1096.         $select->andWhere("customer.oo_id != " $db->quote($user->getId()));
  1097.         $select->andWhere("customer.isDeleted != 1 OR customer.isDeleted IS NULL");
  1098.         $select->andWhere("customer.organization__id IS NOT NULL");
  1099.         $groupByFields = ['customer.oo_id'];
  1100.         $hasSorting false;
  1101.         // Dynamic sorting logic with orderKey and order
  1102.         $orderKey $params['orderKey'] ?? null;
  1103.         $order $params['order'] ?? 'asc';
  1104.         // Validate order parameter
  1105.         if (!in_array(strtolower($order), ['asc''desc'])) {
  1106.             $order 'asc';
  1107.         }
  1108.         // Map orderKey to database fields
  1109.         $sortingMap = [
  1110.             'created' => 'customer.o_creationDate',
  1111.             'username' => 'customer.name',
  1112.             'email' => 'customer.email',
  1113.             'role' => 'userRole.name',
  1114.             'entityType' => 'organization.clientType',
  1115.             'packageExpiry' => 'subscription.endDate',
  1116.             'packageName' => 'localized_package.packageName',
  1117.             'entityName' => 'localized_organization.name'
  1118.         ];
  1119.         if ($orderKey && isset($sortingMap[$orderKey])) {
  1120.             $field $sortingMap[$orderKey];
  1121.             // Handle special cases that require joins
  1122.             if ($orderKey === 'packageName') {
  1123.                 $localizedPackageTable 'object_localized_packages_' . ($params['lang'] ?? 'en');
  1124.                 $select->leftJoin('package'$localizedPackageTable'localized_package''localized_package.ooo_id = package.oo_id');
  1125.                 $groupByFields[] = 'localized_package.packageName';
  1126.             } elseif ($orderKey === 'entityName') {
  1127.                 $localizedOrgTable 'object_localized_organization_' . ($params['lang'] ?? 'en');
  1128.                 $select->leftJoin('organization'$localizedOrgTable'localized_organization''localized_organization.ooo_id = organization.oo_id');
  1129.                 $groupByFields[] = 'localized_organization.name';
  1130.             } else {
  1131.                 $groupByFields[] = $field;
  1132.             }
  1133.             $select->orderBy($fieldstrtoupper($order));
  1134.             $hasSorting true;
  1135.         }
  1136.         // If no sort param given, apply default sort and group
  1137.         if (!$hasSorting) {
  1138.             $select->orderBy('customer.oo_id''DESC');
  1139.             $groupByFields = ['customer.oo_id'];
  1140.         }
  1141.         // Final groupBy
  1142.         $select->groupBy(array_unique($groupByFields));
  1143.         // dd( $select->getSQL());
  1144.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  1145.         $page = isset($params['page']) ? $params['page'] : 1;
  1146.         $paginator $paginator->paginate(
  1147.             $select,
  1148.             $page,
  1149.             $pageSize
  1150.         );
  1151.         foreach ($paginator as $usersId) {
  1152.             $usersData DataObject\Customer::getById($usersId['oo_id'], true);
  1153.             if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
  1154.                 // Get Custom Subscription of the organization and package
  1155.                 $customSubscriptions = new DataObject\Subscription\Listing();
  1156.                 $customSubscriptions->filterBySubscribedUser($usersData);
  1157.                 $customSubscriptions->filterByIsActive(true);
  1158.                 $status "Pending";
  1159.                 if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
  1160.                     if ($customSubscriptions->count() > 0) {
  1161.                         $status "Active";
  1162.                     } else {
  1163.                         $status "Suspended";
  1164.                     }
  1165.                 } elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
  1166.                     if ($customSubscriptions->count() > 0) {
  1167.                         $status "Pending";
  1168.                     } else {
  1169.                         $status "Suspended";
  1170.                     }
  1171.                 }
  1172.                 $customSubscriptions->filterBySubscriptionType("custom");
  1173.                 $customSubscriptions->setOrderKey("o_modificationDate");
  1174.                 $customSubscriptions->setOrder("desc");
  1175.                 $packageData = [];
  1176.                 $userPackage null;
  1177.                 if ($customSubscriptions->count() > 0) {
  1178.                     foreach ($customSubscriptions as $key => $customSubscription) {
  1179.                         if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
  1180.                             $package $customSubscription->getSubscribedPackage();
  1181.                             $userPackage $package;
  1182.                             if ($package) {
  1183.                                 $packageData[] = [
  1184.                                     "id" => $package->getId(),
  1185.                                     "name" => $package->getPackageName('en'),
  1186.                                     "name_ar" => $package->getPackageName('ar'),
  1187.                                     "package_expiry" => $customSubscription->getEndDate(date("M d, Y"))
  1188.                                 ];
  1189.                             }
  1190.                         }
  1191.                     }
  1192.                 }
  1193.                 $permissionObj $this->getUserPermissionInfo($usersData$translator);
  1194.                 $userPermissions $permissionObj['success'] ? $permissionObj['grants'] : null;
  1195.                 $organization $usersData->getOrganization();
  1196.                 $clientType $organization $organization->getClientType() : '';
  1197.                 $clientTypeArray = [
  1198.                     "key" => $clientType,
  1199.                     'name_en' => $clientType === 'organization' 'Entity' : ($clientType $translator->trans($clientType, [], null'en') : ''),
  1200.                     'name_ar' => $clientType === 'organization' 'الجهة' : ($clientType $translator->trans($clientType, [], null'ar') : ''),
  1201.                 ];
  1202.                 $roleArray = [
  1203.                     "key" => ($usersData->getRole()) ? $usersData->getRole()->getName() : null,
  1204.                     'name_en' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'en') : null,
  1205.                     'name_ar' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'ar') : null,
  1206.                 ];
  1207.                 // If user is pending, get invitation duration from MannedAlertLog
  1208.                 if ($status === "Pending") {
  1209.                     $invitationDuration $this->getInvitationDate($usersData);
  1210.                     $statusArray = [
  1211.                         "key" => $status,
  1212.                         'name_en' => $translator->trans($status, [], null'en'),
  1213.                         'name_ar' => $translator->trans($status, [], null'ar'),
  1214.                         'pendingDuration' => $invitationDuration // Add this field
  1215.                     ];
  1216.                 } else {
  1217.                     $statusArray = [
  1218.                         "key" => $status,
  1219.                         'name_en' => $translator->trans($status, [], null'en'),
  1220.                         'name_ar' => $translator->trans($status, [], null'ar'),
  1221.                     ];
  1222.                 }
  1223.                 // $statusArray = [
  1224.                 //     "key" => $status,
  1225.                 //     'name_en' => $translator->trans($status, [], null, 'en'),
  1226.                 //     'name_ar' => $translator->trans($status, [], null, 'ar'),
  1227.                 // ];
  1228.                 $userData[] = [
  1229.                     'id' => $usersData->getId(),
  1230.                     'name' => $usersData->getName(),
  1231.                     'title' => $usersData->getTitle(),
  1232.                     'email' => $usersData->getEmail(),
  1233.                     'phone' => $usersData->getPhoneNo(),
  1234.                     'department' => $usersData->getDepartment(),
  1235.                     'role' => $roleArray,
  1236.                     'company_name_en' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName("en") : null,
  1237.                     'company_name_ar' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName("ar") : null,
  1238.                     'packageData' => $packageData,
  1239.                     'organizationId' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getId() : null,
  1240.                     'location' => $this->getLocationList($usersData),
  1241.                     'allowCustomNotification' => ($permissionObj['success'] && isset($userPermissions['get_custom_notification'])) ? $userPermissions['get_custom_notification'] : false,
  1242.                     'allowAddLocation' => ($permissionObj['success'] && isset($userPermissions['create_location'])) ? $userPermissions['create_location'] : false,
  1243.                     'allowForecast' => ($permissionObj['success'] && isset($userPermissions['get_weather'])) ? $userPermissions['get_weather'] : false,
  1244.                     'allowAlertHistoryForCustomAlerts' => ($permissionObj['success'] && isset($userPermissions['alert_history'])) ? $userPermissions['alert_history'] : false,
  1245.                     'automotive' => ($permissionObj['success'] && isset($userPermissions['automotive'])) ? $userPermissions['automotive'] : false,
  1246.                     'aviation' => ($permissionObj['success'] && isset($userPermissions['aviation'])) ? $userPermissions['aviation'] : false,
  1247.                     'shippingAndOffshore' => ($permissionObj['success'] && isset($userPermissions['shipping_and_offshore'])) ? $userPermissions['shipping_and_offshore'] : false,
  1248.                     'insurance' => ($permissionObj['success'] && isset($userPermissions['insurance'])) ? $userPermissions['insurance'] : false,
  1249.                     'energy' => ($permissionObj['success'] && isset($userPermissions['energy'])) ? $userPermissions['energy'] : false,
  1250.                     'client_type' => $clientTypeArray,
  1251.                     'status' => $statusArray,
  1252.                     'createdBy' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
  1253.                     'createdAt' => date('Y-m-d H:i:s'$usersData->getCreationDate()),
  1254.                     'iqamaId' => $usersData->getIqamaId() ? (string) $usersData->getIqamaId() : null,
  1255.                     //'token' => $status == "Pending" ? $usersData->getToken() : '',
  1256.                     'entity_status' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getStatus() : null,
  1257.                     'entity_status_en' => ($usersData->getOrganization() && $usersData->getOrganization()->getStatus()) ? $translator->trans($usersData->getOrganization()->getStatus(), [], null'en') : null,
  1258.                     'entity_status_ar' => ($usersData->getOrganization() && $usersData->getOrganization()->getStatus()) ? $translator->trans($usersData->getOrganization()->getStatus(), [], null'ar') : null,
  1259.                     'trialLeftDays' => $usersData->getOrganization() ? 
  1260.                         \App\Lib\Utility::getTrialLeftDays(
  1261.                             $usersData->getOrganization()->getPackageActivationDate(),
  1262.                             $usersData->getOrganization()->getTrialLimit()
  1263.                         ) : null,
  1264.                     'isSMSEnabled' => $organization $organization->getIsSMSEnabled() : false,
  1265.                     'SMSLimit' => $userPackage?->getSMSLimit(),
  1266.                     'SMSConsumption' => $organization $organization->getSmsConsumption() : 0,
  1267.                 ];
  1268.                 if (isset($params['sortByStatus']) && !empty($params['sortByStatus'])) {
  1269.                     $statusFilter strtoupper($params['sortByStatus']);
  1270.                     usort($userData, function ($a$b) use ($statusFilter) {
  1271.                         $statusKeyA $a['status']['key'];
  1272.                         $statusKeyB $b['status']['key'];
  1273.                         if ($statusFilter === 'ASC') {
  1274.                             if ($statusKeyA === 'Active' && $statusKeyB !== 'Active') {
  1275.                                 return -1;
  1276.                             }
  1277.                             if ($statusKeyA !== 'Active' && $statusKeyB === 'Active') {
  1278.                                 return 1;
  1279.                             }
  1280.                         } else if ($statusFilter === 'DESC') {
  1281.                             if ($statusKeyA === 'Pending' && $statusKeyB !== 'Pending') {
  1282.                                 return -1;
  1283.                             }
  1284.                             if ($statusKeyA !== 'Pending' && $statusKeyB === 'Pending') {
  1285.                                 return 1;
  1286.                             }
  1287.                         }
  1288.                         return 0// They are equal in terms of status priority
  1289.                     });
  1290.                 }
  1291.             }
  1292.         }
  1293.         if (!$paginator->count()) {
  1294.             return ["success" => false"message" => $translator->trans("no_user_available_to_this_organization")];
  1295.         }
  1296.         return ["success" => TRUE"data" => $userData"paginationVariables" => $paginator->getPaginationData()];
  1297.         // } catch (\Exception $ex) {
  1298.         //     throw new \Exception($ex->getMessage());
  1299.         // }
  1300.         return $result;
  1301.     }
  1302.     /**
  1303.      * Get NCM User List
  1304.      */
  1305.     public function getNCMUsers($request$user$params$paginator$translator)
  1306.     {
  1307.         $result = [];
  1308.         try {
  1309.             $userData = [];
  1310.             // if ($user->getOrganization() === null) {
  1311.             //     return ["success" => false, "message" => $translator->trans("organization_does_not_exists")];
  1312.             //  }
  1313.             //  $organizationId = $user->getOrganization()->getId();
  1314.             // Get All the Classes
  1315.             $class = new \Pimcore\Model\DataObject\ClassDefinition();
  1316.             $customer $class->getDao()->getIdByName('Customer');
  1317.             $subscription $class->getDao()->getIdByName('Subscription');
  1318.             $userRole $class->getDao()->getIdByName('UserRole');
  1319.             $userTag $class->getDao()->getIdByName('UserTag');
  1320.             $organization $class->getDao()->getIdByName('Organization');
  1321.             $package $class->getDao()->getIdByName('Package');
  1322.             $db Db::get();
  1323.             $select $db->createQueryBuilder();
  1324.             $select->select('customer.oo_id');
  1325.             $select->from('object_' $customer'customer');
  1326.             $select->leftJoin('customer''object_' $subscription'subscription''customer.oo_id = subscription.subscribedUser__id');
  1327.             $select->leftJoin('subscription''object_' $package'package''package.oo_id = subscription.subscribedPackage__id');
  1328.             $select->leftJoin('customer''object_' $organization'organization''organization.oo_id = customer.organization__id');
  1329.             $select->leftJoin('customer''object_' $userRole'userRole''userRole.oo_id = customer.role__id');
  1330.             $select->leftJoin('customer''object_' $userTag'userTage''userTage.oo_id = customer.tag__id');
  1331.             if (isset($params['search']) && !empty($params['search'])) {
  1332.                 $select->andWhere("customer.name LIKE " $db->quote("%" $params['search'] . "%") . " OR customer.email LIKE " $db->quote("%" $params['search'] . "%"));
  1333.             }
  1334.             if (isset($params['searchByTag']) && !empty($params['searchByTag'])) {
  1335.                 $select->andWhere("customer.tag__id = " $db->quote($params['searchByTag']));
  1336.             }
  1337.             $select->andWhere("userRole.name = " $db->quote(USER_ROLES['NCM_IT']) . " OR userRole.name = " $db->quote(USER_ROLES['NCM_OPERATOR']));
  1338.             $select->andWhere("customer.oo_id != " $db->quote($user->getId()));
  1339.             $select->andWhere("customer.isDeleted != 1 or customer.isDeleted IS NULL");
  1340.             //$select->andWhere("organization.oo_id = ".$db->quote($organizationId));
  1341.             // if (isset($params['status']) && !empty($params['status'])) {
  1342.             //     $statusFilter = ucfirst($params['status']);
  1343.             //     if ($statusFilter == 'Active') {
  1344.             //         $select->andWhere("customer.token IS NULL AND customer.o_published = 1 AND subscription.subscribedUser__id IS NOT NULL");
  1345.             //     } elseif ($statusFilter == 'Suspended') {
  1346.             //         $select->andWhere("customer.token IS NULL AND customer.o_published = 1 AND subscription.subscribedUser__id IS NULL");
  1347.             //     } elseif ($statusFilter == 'Pending') {
  1348.             //         $select->andWhere("customer.token != '' AND customer.o_published = 0");
  1349.             //     }
  1350.             // }
  1351.             // Dynamic sorting logic
  1352.             $orderKey = isset($params['orderKey']) ? $params['orderKey'] : null;
  1353.             $order = isset($params['order']) ? strtoupper($params['order']) : 'ASC';
  1354.             // Validate order parameter
  1355.             if (!in_array(strtoupper($order), ['ASC''DESC'])) {
  1356.                 $order 'ASC';
  1357.             }
  1358.             // Map orderKey to database fields
  1359.             $fieldMapping = [
  1360.                 'username' => 'customer.name',
  1361.                 'email' => 'customer.email',
  1362.                 'userTag' => 'userTage.name',
  1363.                 'createdBy' => 'createdBy.name',
  1364.                 'role' => 'userRole.name',
  1365.                 'status' => 'status'// This will be handled separately as it's computed
  1366.                 'createdOn' => 'customer.o_creationDate'
  1367.             ];
  1368.             if ($orderKey && isset($fieldMapping[$orderKey])) {
  1369.                 $field $fieldMapping[$orderKey];
  1370.                 if ($orderKey === 'createdBy') {
  1371.                     $select->leftJoin('customer''object_' $customer'createdBy''createdBy.oo_id = customer.createdBy__id');
  1372.                 }
  1373.                 if ($orderKey === 'status') {
  1374.                     $needStatusSort true;
  1375.                 } else {
  1376.                     $select->orderBy($field$order);
  1377.                 }
  1378.             } else {
  1379.                 // Default sorting
  1380.                 $select->orderBy('customer.o_creationDate''DESC');
  1381.             }
  1382.             $select->groupBy(array('oo_id'));
  1383.             $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  1384.             $page = isset($params['page']) ? $params['page'] : 1;
  1385.             $paginator $paginator->paginate(
  1386.                 $select,
  1387.                 $page,
  1388.                 $pageSize
  1389.             );
  1390.             foreach ($paginator as $usersId) {
  1391.                 $usersData DataObject\Customer::getById($usersId['oo_id'], true);
  1392.                 if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
  1393.                     // Get Custom Subscription of the organization and package
  1394.                     $customSubscriptions = new DataObject\Subscription\Listing();
  1395.                     $customSubscriptions->filterBySubscribedUser($usersData);
  1396.                     $customSubscriptions->filterByIsActive(true);
  1397.                     $status "Pending";
  1398.                     if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
  1399.                         if ($usersData->getPermissionGroups() && count($usersData->getPermissionGroups()) > 0) {
  1400.                             $status "Active";
  1401.                         } else {
  1402.                             $status "Suspended";
  1403.                         }
  1404.                     } elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
  1405.                         $status "Pending";
  1406.                     }
  1407.                     $permissionObj $this->getUserPermissionInfo($usersData$translator);
  1408.                     $userPermissions $permissionObj['success'] ? $permissionObj['grants'] : null;
  1409.                     //$customSubscriptions->filterBySubscriptionType("custom");
  1410.                     $customSubscriptions->setOrderKey("o_modificationDate");
  1411.                     $customSubscriptions->setOrder("desc");
  1412.                     $apiGroupData = [];
  1413.                     $packageData = [];
  1414.                     $assignedApiGroupIds = [];
  1415.                     if ($customSubscriptions->count() > 0) {
  1416.                         foreach ($customSubscriptions as $key => $customSubscription) {
  1417.                             if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
  1418.                                 $package $customSubscription->getSubscribedPackage();
  1419.                                 $disallowedApiGroups $customSubscription->getDisallowedApiGroups();
  1420.                                 // get all allowed API Group IDs for the user
  1421.                                 $allowedApiGroups $customSubscription->getAllowedApiGroups();
  1422.                                 if (count($allowedApiGroups) > 0) {
  1423.                                     foreach ($allowedApiGroups as $allowedApiGroup) {
  1424.                                         if ($allowedApiGroup instanceof \Pimcore\Model\DataObject\ApiGroup) {
  1425.                                             # code...
  1426.                                             $assignedApiGroupIds[] = [
  1427.                                                 "id" => $allowedApiGroup->getId(),
  1428.                                                 "name" => $allowedApiGroup->getGroupName(),
  1429.                                             ];
  1430.                                         }
  1431.                                     }
  1432.                                 }
  1433.                                 if ($package) {
  1434.                                     $packageData[] = [
  1435.                                         "id" => $package->getId(),
  1436.                                         "name" => $package->getName(),
  1437.                                         "package_expiry" => $customSubscription->getEndDate(date("M d, Y")),
  1438.                                         "is_no_expiry" => $customSubscription->getIsNoExpiry() == null false $customSubscription->getIsNoExpiry()
  1439.                                     ];
  1440.                                     $apiGroups $package->getApiGroups();
  1441.                                     if ($apiGroups) {
  1442.                                         foreach ($apiGroups as  $apiGroup) {
  1443.                                             $apiGroupId $apiGroup->getId();
  1444.                                             $apiGroupNameEn $apiGroup->getApiGroupName('en');
  1445.                                             $apiGroupNameAr $apiGroup->getApiGroupName('ar');
  1446.                                             $isDisallowed false;
  1447.                                             // Check if the current API group is disallowed
  1448.                                             foreach ($disallowedApiGroups as $disallowedApiGroup) {
  1449.                                                 if ($apiGroupId == $disallowedApiGroup->getId()) {
  1450.                                                     $isDisallowed true;
  1451.                                                     break;
  1452.                                                 }
  1453.                                             }
  1454.                                             // Only add the API group if it's not disallowed
  1455.                                             if (!$isDisallowed) {
  1456.                                                 $apiGroupData[] = [
  1457.                                                     "id" => $apiGroupId,
  1458.                                                     "name" => $apiGroupNameEn,
  1459.                                                     "name_ar" => $apiGroupNameAr
  1460.                                                 ];
  1461.                                             }
  1462.                                         }
  1463.                                     }
  1464.                                 }
  1465.                             }
  1466.                         }
  1467.                     }
  1468.                     $typeArray = [
  1469.                         "key" => 'user',
  1470.                         'name_en' => $translator->trans('user', [], null'en'),
  1471.                         'name_ar' => $translator->trans('user', [], null'ar'),
  1472.                     ];
  1473.                     $roleArray = [
  1474.                         "key" => ($usersData->getRole()) ? $usersData->getRole()->getName() : null,
  1475.                         'name_en' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'en') : null,
  1476.                         'name_ar' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'ar') : null,
  1477.                     ];
  1478.                     $statusArray = [
  1479.                         "key" => $status,
  1480.                         'name_en' => $translator->trans($status, [], null'en'),
  1481.                         'name_ar' => $translator->trans($status, [], null'ar'),
  1482.                     ];
  1483.                     // Fetch Permission Groups Data
  1484.                     $permissionGroups $usersData->getPermissionGroups();
  1485.                     $permissionGroupsData = [];
  1486.                     if ($permissionGroups) {
  1487.                         foreach ($permissionGroups as $permissionGroup) {
  1488.                             if ($permissionGroup instanceof \Pimcore\Model\DataObject\PermissionGroup) {
  1489.                                 $permissionGroupsData[] = [
  1490.                                     'id' => $permissionGroup->getId(),
  1491.                                     'nameEn' => $permissionGroup->getName('en'),
  1492.                                     'nameAr' => $permissionGroup->getName('ar'),
  1493.                                     'descriptionEn' => $permissionGroup->getDescription('en'),
  1494.                                     'descriptionAr' => $permissionGroup->getDescription('ar'),
  1495.                                     'apiGroups' => array_map(function ($group) {
  1496.                                         return ['id' => $group->getId(), 'nameEn' => $group->getApiGroupName('en'), 'nameAr' => $group->getApiGroupName('ar')];
  1497.                                     }, $permissionGroup->getApiGroups() ?? []),
  1498.                                 ];
  1499.                             }
  1500.                         }
  1501.                     }
  1502.                     $userData[] = [
  1503.                         'id' => $usersData->getId(),
  1504.                         'name' => $usersData->getName(),
  1505.                         'title' => $usersData->getTitle(),
  1506.                         'email' => $usersData->getEmail(),
  1507.                         'department' => $usersData->getDepartment(),
  1508.                         'role' => $roleArray,
  1509.                         'organization' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName() : null,
  1510.                         'organizationId' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getId() : null,
  1511.                         'location' => $this->getLocationList($usersData),
  1512.                         'invite_user' => ($permissionObj['success'] && isset($userPermissions['invite_user'])) ? $userPermissions['invite_user'] : false,
  1513.                         'edit_user' => ($permissionObj['success'] && isset($userPermissions['edit_user'])) ? $userPermissions['edit_user'] : false,
  1514.                         'delete_user' => ($permissionObj['success'] && isset($userPermissions['delete_user'])) ? $userPermissions['delete_user'] : false,
  1515.                         'invite_ncm_user' => ($permissionObj['success'] && isset($userPermissions['invite_ncm_user'])) ? $userPermissions['invite_ncm_user'] : false,
  1516.                         'edit_ncm_user' => ($permissionObj['success'] && isset($userPermissions['edit_ncm_user'])) ? $userPermissions['edit_ncm_user'] : false,
  1517.                         'delete_ncm_user' => ($permissionObj['success'] && isset($userPermissions['delete_ncm_user'])) ? $userPermissions['delete_ncm_user'] : false,
  1518.                         'type' => $typeArray,
  1519.                         'status' => $statusArray,
  1520.                         'apiGroups' => $apiGroupData,
  1521.                         'assignedApiGroupIds' => $assignedApiGroupIds,
  1522.                         'packageData' => $packageData,
  1523.                         'createdBy' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
  1524.                         'creationDate' => $usersData->getCreationDate() ? date('Y-m-d'$usersData->getCreationDate()) : null,
  1525.                         'iqamaId' => $usersData->getIqamaId() ? (string) $usersData->getIqamaId() : null,
  1526.                         'tag' => $usersData->getTag() ? ['id' => $usersData->getTag()->getId(), 'name' => $usersData->getTag()->getName()] : null,
  1527.                         'permissionGroupsData' => $permissionGroupsData,
  1528.                         'dualMode' => $usersData->getDualMode() ? true false,
  1529.                         //'token' => $usersData->getToken(),
  1530.                     ];
  1531.                 }
  1532.             }
  1533.             if (!$userData) {
  1534.                 return ["success" => false"message" => $translator->trans("no_user_available_in_NCM")];
  1535.             }
  1536.             // Handle status sorting if needed
  1537.             if (isset($needStatusSort) && $needStatusSort && $orderKey === 'status') {
  1538.                 usort($userData, function ($a$b) use ($order) {
  1539.                     $statusA $a['status']['key'];
  1540.                     $statusB $b['status']['key'];
  1541.                     if ($order === 'ASC') {
  1542.                         return strcmp($statusA$statusB);
  1543.                     } else {
  1544.                         return strcmp($statusB$statusA);
  1545.                     }
  1546.                 });
  1547.             }
  1548.             return ["success" => TRUE"data" => $userData"paginationVariables" => $paginator->getPaginationData()];
  1549.         } catch (\Exception $ex) {
  1550.             throw new \Exception($ex->getMessage());
  1551.         }
  1552.         return $result;
  1553.     }
  1554.     /**
  1555.      * Get User List
  1556.      */
  1557.     public function getUsers($request$user$translator$params$paginator)
  1558.     {
  1559.         $result = [];
  1560.         $userData = [];
  1561.         try {
  1562.             if ($user->getOrganization() === null) {
  1563.                 return ["success" => false"message" => $translator->trans("organization_does_not_exists")];
  1564.             }
  1565.             $organizationId $user->getOrganization()->getId();
  1566.             // Get All the Classes
  1567.             $class = new \Pimcore\Model\DataObject\ClassDefinition();
  1568.             $customer $class->getDao()->getIdByName('Customer');
  1569.             $subscription $class->getDao()->getIdByName('Subscription');
  1570.             $userRole $class->getDao()->getIdByName('UserRole');
  1571.             $organization $class->getDao()->getIdByName('Organization');
  1572.             $package $class->getDao()->getIdByName('Package');
  1573.             $db Db::get();
  1574.             $select $db->createQueryBuilder();
  1575.             $select->select('customer.oo_id');
  1576.             $select->from('object_' $customer'customer');
  1577.             $select->innerJoin('customer''object_' $subscription'subscription''customer.oo_id = subscription.subscribedUser__id');
  1578.             $select->innerJoin('subscription''object_' $package'package''package.oo_id = subscription.subscribedPackage__id');
  1579.             $select->innerJoin('customer''object_' $organization'organization''organization.oo_id = customer.organization__id');
  1580.             $select->innerJoin('customer''object_' $userRole'userRole''userRole.oo_id = customer.role__id');
  1581.             if (isset($params['search']) && !empty($params['search'])) {
  1582.                 $select->andWhere("customer.name LIKE " $db->quote("%" $params['search'] . "%") . " OR customer.email LIKE " $db->quote("%" $params['search'] . "%"));
  1583.             }
  1584.             $select->andWhere("userRole.name = " $db->quote(USER_ROLES['CLIENT_ADMIN']) . " OR userRole.name = " $db->quote(USER_ROLES['CLIENT_USER']));
  1585.             $select->andWhere("customer.oo_id != " $db->quote($user->getId()));
  1586.             $select->andWhere("organization.oo_id = " $db->quote($organizationId));
  1587.             $select->andWhere("customer.isDeleted != 1 or customer.isDeleted IS NULL");
  1588.             if (isset($params['status']) && $params['status'] == true) {
  1589.                 $select->andWhere("customer.o_published = 1");
  1590.             }
  1591.             $select->orderBy('oo_id''DESC');
  1592.             $select->groupBy(array('oo_id'));
  1593.             $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  1594.             $page = isset($params['page']) ? $params['page'] : 1;
  1595.             $paginator $paginator->paginate(
  1596.                 $select,
  1597.                 $page,
  1598.                 $pageSize
  1599.             );
  1600.             foreach ($paginator as $usersId) {
  1601.                 $usersData DataObject\Customer::getById($usersId['oo_id'], true);
  1602.                 if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
  1603.                     // Get Custom Subscription of the organization and package
  1604.                     $customSubscriptions = new DataObject\Subscription\Listing();
  1605.                     $customSubscriptions->filterBySubscribedUser($usersData);
  1606.                     $customSubscriptions->filterByIsActive(true);
  1607.                     $status "Pending";
  1608.                     if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
  1609.                         if ($customSubscriptions->count() > 0) {
  1610.                             $status "Active";
  1611.                         } else {
  1612.                             $status "Suspended";
  1613.                         }
  1614.                     } elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
  1615.                         $status "Pending";
  1616.                     }
  1617.                     $permissionObj $this->getUserPermissionInfo($usersData$translator);
  1618.                     $userPermissions $permissionObj['success'] ? $permissionObj['grants'] : null;
  1619.                     $customSubscriptions->filterBySubscriptionType("custom");
  1620.                     $customSubscriptions->setOrderKey("o_modificationDate");
  1621.                     $customSubscriptions->setOrder("desc");
  1622.                     $apiGroupData = [];
  1623.                     $packageData = [];
  1624.                     $dissAllowedApiGroupID = [];
  1625.                     if ($customSubscriptions->count() > 0) {
  1626.                         foreach ($customSubscriptions as $key => $customSubscription) {
  1627.                             if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
  1628.                                 $package $customSubscription->getSubscribedPackage();
  1629.                                 if ($package) {
  1630.                                     $packageData[] = [
  1631.                                         "id" => $package->getId(),
  1632.                                         "name" => $package->getName(),
  1633.                                         "package_expiry" => $customSubscription->getEndDate(date("M d, Y"))
  1634.                                     ];
  1635.                                 }
  1636.                                 $disallowedApiGroups $customSubscription->getDisallowedApiGroups();
  1637.                                 if (count($disallowedApiGroups) > 0) {
  1638.                                     foreach ($disallowedApiGroups as $value) {
  1639.                                         $dissAllowedApiGroupID[] = $value->getId();
  1640.                                     }
  1641.                                 }
  1642.                                 if ($package) {
  1643.                                     $apiGroups $package->getApiGroups();
  1644.                                     if ($apiGroups) {
  1645.                                         foreach ($apiGroups as  $apiGroup) {
  1646.                                             if (!in_array($apiGroup->getId(), $dissAllowedApiGroupID)) {
  1647.                                                 $apiGroupData[] = [
  1648.                                                     "id" => $apiGroup->getId(),
  1649.                                                     "name" => $apiGroup->getApiGroupName('en'),
  1650.                                                     "name_ar" => $apiGroup->getApiGroupName('ar')
  1651.                                                 ];
  1652.                                             }
  1653.                                         }
  1654.                                     }
  1655.                                 }
  1656.                             }
  1657.                         }
  1658.                     }
  1659.                     $typeArray = [
  1660.                         "key" => 'user',
  1661.                         'name_en' => $translator->trans('user', [], null'en'),
  1662.                         'name_ar' => $translator->trans('user', [], null'ar'),
  1663.                     ];
  1664.                     $roleArray = [
  1665.                         "key" => ($usersData->getRole()) ? $usersData->getRole()->getName() : null,
  1666.                         'name_en' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'en') : null,
  1667.                         'name_ar' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'ar') : null,
  1668.                     ];
  1669.                     $statusArray = [
  1670.                         "key" => $status,
  1671.                         'name_en' => $translator->trans($status, [], null'en'),
  1672.                         'name_ar' => $translator->trans($status, [], null'ar'),
  1673.                     ];
  1674.                     $userData[] = [
  1675.                         'id' => $usersData->getId(),
  1676.                         'name' => $usersData->getName(),
  1677.                         'title' => $usersData->getTitle(),
  1678.                         'email' => $usersData->getEmail(),
  1679.                         'phone' => $usersData->getPhoneNo(),
  1680.                         'department' => $usersData->getDepartment(),
  1681.                         'role' => $roleArray,
  1682.                         'organization' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName() : null,
  1683.                         'organizationId' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getId() : null,
  1684.                         'location' => $this->getLocationList($usersData),
  1685.                         'allowCustomNotification' => ($permissionObj['success']) ? $userPermissions['get_custom_notification'] : false,
  1686.                         'allowAddLocation' => ($permissionObj['success']) ? $userPermissions['create_location'] : false,
  1687.                         'allowForecast' => ($permissionObj['success']) ? $userPermissions['get_weather'] : false,
  1688.                         'allowAlertHistoryForCustomAlerts' => ($permissionObj['success']) ? $userPermissions['alert_history'] : false,
  1689.                         'automotive' => ($permissionObj['success']) ? $userPermissions['automotive'] : false,
  1690.                         'aviation' => ($permissionObj['success']) ? $userPermissions['aviation'] : false,
  1691.                         'shippingAndOffshore' => ($permissionObj['success']) ? $userPermissions['shipping_and_offshore'] : false,
  1692.                         'insurance' => ($permissionObj['success']) ? $userPermissions['insurance'] : false,
  1693.                         'energy' => ($permissionObj['success']) ? $userPermissions['energy'] : false,
  1694.                         'type' => $typeArray,
  1695.                         'status' => $statusArray,
  1696.                         'packageData' => $packageData,
  1697.                         'apiGroups' => $apiGroupData,
  1698.                         'createdBy' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
  1699.                         'iqamaId' => $usersData->getIqamaId() ? (string) $usersData->getIqamaId() : null,
  1700.                         //'token' => $status == "Pending" ? $usersData->getToken() : '',
  1701.                     ];
  1702.                 }
  1703.             }
  1704.             if (!$paginator->count()) {
  1705.                 return ["success" => false"message" => $translator->trans("no_user_available_to_this_organization.")];
  1706.             }
  1707.             return ["success" => TRUE"data" => $userData'paginationVariables' => $paginator->getPaginationData()];
  1708.         } catch (\Exception $ex) {
  1709.             throw new \Exception($ex->getMessage());
  1710.         }
  1711.         return $result;
  1712.     }
  1713.     // /**
  1714.     //  * set package subscription
  1715.     //  */
  1716.     // public function setPcakageSubscription($params)
  1717.     // {
  1718.     //     $result = [];
  1719.     //     try {
  1720.     //         $apiGroup = $this->createApiGrpup($params);
  1721.     //         $package = new DataObject\Package();
  1722.     //         $package->setParent(DataObject\Service::createFolderByPath('/UserManagement/Packages/CustomPackages/'));
  1723.     //         $package->setKey(\Pimcore\Model\Element\Service::getValidKey($apiGroup->getId() . time(), 'object'));
  1724.     //         $package->setApiGroups([$apiGroup]);
  1725.     //         $package->setTenure(1);
  1726.     //         $package->setMaxLocation(100);
  1727.     //         $package->setMaxUsers(100);
  1728.     //         $package->setIsActive(true);
  1729.     //         $package->setPublished(true);
  1730.     //         $package->save();
  1731.     //         $subscription = $this->setSubscription($package, $params['user']);
  1732.     //         if ($subscription instanceof DataObject\Subscription) {
  1733.     //             return ["success" => true, "message" => "set_subscription."];
  1734.     //         }
  1735.     //         //return $subscription;
  1736.     //     } catch (\Exception $ex) {
  1737.     //         throw new \Exception($ex->getMessage());
  1738.     //     }
  1739.     //     return $result;
  1740.     // }
  1741.     /**
  1742.      * set create subscription
  1743.      */
  1744.     public function setSubscription($package$user$disallowedApiGroupsArray$subscriptionType$isNoExpiry false)
  1745.     {
  1746.         $result = [];
  1747.         try {
  1748.             if (!$package instanceof DataObject\Package) {
  1749.                 return ["success" => false"message" => "Package is not available"];
  1750.             }
  1751.             if (!$user instanceof DataObject\Customer) {
  1752.                 return ["success" => false"message" => "User is not available"];
  1753.             }
  1754.             $organization $user->getOrganization();
  1755.             if (!$organization instanceof DataObject\Organization) {
  1756.                 return ["success" => false"message" => "Organization is not available"];
  1757.             }
  1758.             $packageActivationDate $organization->getPackageActivationDate();
  1759.             if (!$packageActivationDate || strtotime($packageActivationDate) === false) {
  1760.                 $packageActivationDate date('Y-m-d');
  1761.             } else {
  1762.                 $packageActivationDate date('Y-m-d'strtotime($packageActivationDate));
  1763.             }
  1764.             // Set Subscription Expiry
  1765.             $subscriptionExpiry date('Y-m-d'strtotime('+' $organization->getTrialLimit() . ' days'strtotime($packageActivationDate)));
  1766.             $subscription = new DataObject\Subscription();
  1767.             $subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' $user->getEmail()));
  1768.             $subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(100010000), 'object'));
  1769.             $subscription->setSubscribedPackage($package);
  1770.             $subscription->setSubscribedUser($user);
  1771.             //Set Disallowed ApiGroups
  1772.             if ($disallowedApiGroupsArray != null) {
  1773.                 $disallowedApiGroups = [];
  1774.                 foreach ($disallowedApiGroupsArray as $disallowedApiGroupsId) {
  1775.                     $apiGroup =  DataObject\APIGroup::getById($disallowedApiGroupsIdtrue);
  1776.                     $disallowedApiGroups[] = $apiGroup;
  1777.                 }
  1778.                 $subscription->setDisallowedApiGroups($disallowedApiGroups);
  1779.             }
  1780.             //$subscription->setDisallowedApis($disAllowPermissions);
  1781.             $subscription->setSubscriptionType($subscriptionType);
  1782.             $subscription->setStartDate(Carbon::parse(new \Datetime(date('Y-m-d'))));
  1783.             $subscription->setEndDate(Carbon::parse(new \Datetime($subscriptionExpiry)));
  1784.             $subscription->setIsNoExpiry($isNoExpiry);
  1785.             $subscription->setIsActive(true);
  1786.             $subscription->setPublished(true);
  1787.             $subscription->save();
  1788.             return  $subscription;
  1789.         } catch (\Exception $ex) {
  1790.             throw new \Exception($ex->getMessage());
  1791.         }
  1792.         return $result;
  1793.     }
  1794.     /**
  1795.      * set NCM User subscription
  1796.      */
  1797.     public function setNcmUserSubscription($role$user$allowedApiGrpups$isNoExpiry false)
  1798.     {
  1799.         $result = [];
  1800.         try {
  1801.             if ($role instanceof DataObject\UserRole) {
  1802.                 $packages $role->getDefaultPackages();
  1803.                 if ($packages) {
  1804.                     $defaultPackage $packages[0];
  1805.                     if ($defaultPackage instanceof DataObject\Package) {
  1806.                         $subscription = new DataObject\Subscription();
  1807.                         $subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/NCM Users/' $user->getEmail()));
  1808.                         $subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($defaultPackage->getId() . time() . uniqid(), 'object'));
  1809.                         $subscription->setSubscribedPackage($defaultPackage);
  1810.                         $subscription->setSubscribedUser($user);
  1811.                         //Set allowed ApiGroups
  1812.                         if ($allowedApiGrpups != null) {
  1813.                             $allowedApiGrpupsArray = [];
  1814.                             foreach ($allowedApiGrpups as $allowedApiGrpupId) {
  1815.                                 $apiGroup =  DataObject\APIGroup::getById($allowedApiGrpupIdtrue);
  1816.                                 if ($apiGroup) {
  1817.                                     $allowedApiGrpupsArray[] = $apiGroup;
  1818.                                 }
  1819.                             }
  1820.                             $subscription->setAllowedApiGroups($allowedApiGrpupsArray);
  1821.                         }
  1822.                         $subscriptionExpiry date('Y-m-d'strtotime('+' $defaultPackage->getTenure() . ' days'));
  1823.                         $subscription->setSubscriptionType("default");
  1824.                         $subscription->setStartDate(Carbon::parse(new \Datetime(date('Y-m-d'))));
  1825.                         $subscription->setEndDate(Carbon::parse(new \Datetime($subscriptionExpiry)));
  1826.                         $subscription->setIsNoExpiry($isNoExpiry);
  1827.                         $subscription->setIsActive(true);
  1828.                         $subscription->setPublished(true);
  1829.                         $subscription->save();
  1830.                         return $subscription;
  1831.                     }
  1832.                 }
  1833.             }
  1834.         } catch (\Exception $ex) {
  1835.             throw new \Exception($ex->getMessage());
  1836.         }
  1837.         return $result;
  1838.     }
  1839.     /**
  1840.      * set create subscription
  1841.      */
  1842.     public function updateSubscription($package$user$disAllowPermissions$subscriptionType "custom")
  1843.     {
  1844.         $result = [];
  1845.         try {
  1846.             if (!$package instanceof DataObject\Package) {
  1847.                 return ["success" => false"message" => "Package is not available"];
  1848.             }
  1849.             if (!$user instanceof DataObject\Customer) {
  1850.                 return ["success" => false"message" => "User is not available"];
  1851.             }
  1852.             $subscriptionExpiry date('Y-m-d'strtotime('+' $package->getTenure() . ' days'));
  1853.             $customSubscriptions = new DataObject\Subscription\Listing();
  1854.             $customSubscriptions->filterBySubscribedUser($user);
  1855.             $customSubscriptions->filterBySubscriptionType($subscriptionType);
  1856.             //$customSubscriptions->filterByIsActive(true);
  1857.             $updateSubscription $customSubscriptions->current();
  1858.             if (!$updateSubscription instanceof  DataObject\Subscription) {
  1859.                 $updateSubscription = new DataObject\Subscription();
  1860.                 $updateSubscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' $user->getEmail()));
  1861.                 $updateSubscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(100010000), 'object'));
  1862.                 $updateSubscription->setStartDate(Carbon::parse(new \Datetime(date('Y-m-d'))));
  1863.                 $updateSubscription->setEndDate(Carbon::parse(new \Datetime($subscriptionExpiry)));
  1864.                 $updateSubscription->setIsActive(true);
  1865.                 $updateSubscription->setSubscriptionType($subscriptionType);
  1866.                 $updateSubscription->setPublished(true);
  1867.                 $updateSubscription->setSubscribedUser($user);
  1868.             }
  1869.             $updateSubscription->setSubscribedPackage($package);
  1870.             if ($subscriptionType == 'default') {
  1871.                 $updateSubscription->setIsNoExpiry(true);
  1872.             }
  1873.             $updateSubscription->save();
  1874.             return  $updateSubscription;
  1875.         } catch (\Exception $ex) {
  1876.             throw new \Exception($ex->getMessage());
  1877.         }
  1878.         return $result;
  1879.     }
  1880.     /**
  1881.      * Update NCM User Subscription
  1882.      */
  1883.     public function updateNCMUserSubscription($user$allowedApiGroups)
  1884.     {
  1885.         $result = [];
  1886.         try {
  1887.             if (!$user instanceof DataObject\Customer) {
  1888.                 return ["success" => false"message" => "User is not available"];
  1889.             }
  1890.             $subscriptionListing = new DataObject\Subscription\Listing();
  1891.             $subscriptionListing->filterBySubscribedUser($user);
  1892.             $subscriptionListing->filterByIsActive(true);
  1893.             // Fetch all active subscriptions
  1894.             $activeSubscriptions iterator_to_array($subscriptionListing);
  1895.             if (count($activeSubscriptions) === 0) {
  1896.                 $defaultPackage $user->getRole()?->getDefaultPackages()[0] ?? null;
  1897.                 if ($defaultPackage instanceof DataObject\Package) {
  1898.                     $subscription = new DataObject\Subscription();
  1899.                     $subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/NCM Users/' $user->getEmail()));
  1900.                     $subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($defaultPackage->getId() . time() . uniqid(), 'object'));
  1901.                     $subscription->setSubscribedPackage($defaultPackage);
  1902.                     $subscription->setSubscribedUser($user);
  1903.                     $subscription->setStartDate(Carbon::parse(new \DateTime(date('Y-m-d'))));
  1904.                     // Set end date to one month from today
  1905.                     $subscription->setEndDate(Carbon::now()->addMonth());
  1906.                     $subscription->setIsNoExpiry(true);
  1907.                     $subscription->setIsActive(true);
  1908.                     $subscription->setPublished(false);
  1909.                     $subscription->save();
  1910.                     $activeSubscriptions = [$subscription];
  1911.                 }
  1912.             }
  1913.             // Unpublish all active subscriptions except the first one
  1914.             foreach ($activeSubscriptions as $index => $subscription) {
  1915.                 if ($index 0) {
  1916.                     $subscription->setPublished(false);
  1917.                     $subscription->save();
  1918.                 }
  1919.             }
  1920.             // Update the first subscription if it exists
  1921.             $updateSubscription $activeSubscriptions[0] ?? null;
  1922.             if ($updateSubscription instanceof DataObject\Subscription) {
  1923.                 // Set allowed ApiGroups
  1924.                 if (!empty($allowedApiGroups)) {
  1925.                     $allowedApiGroupsArray = [];
  1926.                     foreach ($allowedApiGroups as $allowedApiGroupId) {
  1927.                         $apiGroup DataObject\APIGroup::getById($allowedApiGroupIdtrue);
  1928.                         if ($apiGroup) {
  1929.                             $allowedApiGroupsArray[] = $apiGroup;
  1930.                         }
  1931.                     }
  1932.                     $updateSubscription->setAllowedApiGroups($allowedApiGroupsArray);
  1933.                 }
  1934.                 $updateSubscription->setSubscriptionType("default");
  1935.                 $updateSubscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/NCM Users/' $user->getEmail()));
  1936.                 $updateSubscription->save();
  1937.                 return $updateSubscription;
  1938.             }
  1939.         } catch (\Exception $ex) {
  1940.             throw new \Exception($ex->getMessage());
  1941.         }
  1942.         return $result;
  1943.     }
  1944.     /**
  1945.      * set package subscription
  1946.      */
  1947.     public function createApiGrpup($params)
  1948.     {
  1949.         $result = [];
  1950.         try {
  1951.             $mergedArray = [];
  1952.             if (isset($params['allowAddLocation']) && $params['allowAddLocation'] === true) {
  1953.                 foreach (USER_PERMISSIONS['is_allow_location'] as $value) {
  1954.                     $mergedArray[] = $value;
  1955.                 }
  1956.             }
  1957.             if (isset($params['is_allow_user']) && $params['is_allow_user']   === true) {
  1958.                 foreach (USER_PERMISSIONS['is_allow_user'] as $value) {
  1959.                     $mergedArray[] = $value;
  1960.                 }
  1961.             }
  1962.             if (isset($params['is_allow_ncm_user']) && $params['is_allow_ncm_user']  === true) {
  1963.                 foreach (USER_PERMISSIONS['is_allow_ncm_user'] as $value) {
  1964.                     $mergedArray[] = $value;
  1965.                 }
  1966.             }
  1967.             if (isset($params['is_allow_organization']) && $params['is_allow_organization']  === true) {
  1968.                 foreach (USER_PERMISSIONS['is_allow_organization'] as $value) {
  1969.                     $mergedArray[] = $value;
  1970.                 }
  1971.             }
  1972.             if (isset($params['is_allow_ncm_organization']) && $params['is_allow_ncm_organization']  === true) {
  1973.                 foreach (USER_PERMISSIONS['is_allow_ncm_organization'] as $value) {
  1974.                     $mergedArray[] = $value;
  1975.                 }
  1976.             }
  1977.             if (isset($params['is_allow_custom_notification']) && $params['is_allow_custom_notification']  === true) {
  1978.                 foreach (USER_PERMISSIONS['is_allow_custom_notification'] as $value) {
  1979.                     $mergedArray[] = $value;
  1980.                 }
  1981.             }
  1982.             if (isset($params['is_allow_weather_forecast']) && $params['is_allow_weather_forecast']  === true) {
  1983.                 foreach (USER_PERMISSIONS['is_allow_weather_forecast'] as $key => $value) {
  1984.                     $mergedArray[] = $value;
  1985.                 }
  1986.             }
  1987.             if (isset($params['is_allow_alert']) && $params['is_allow_alert']  === true) {
  1988.                 foreach (USER_PERMISSIONS['is_allow_alert'] as $value) {
  1989.                     $mergedArray[] = $value;
  1990.                 }
  1991.             }
  1992.             if (isset($params['is_allow_report']) && $params['is_allow_report']  === true) {
  1993.                 foreach (USER_PERMISSIONS['is_allow_report'] as $value) {
  1994.                     $mergedArray[] = $value;
  1995.                 }
  1996.             }
  1997.             if (isset($params['is_allow_weather_warnings']) && $params['is_allow_weather_warnings']  === true) {
  1998.                 foreach (USER_PERMISSIONS['is_allow_weather_warnings'] as $value) {
  1999.                     $mergedArray[] = $value;
  2000.                 }
  2001.             }
  2002.             if (isset($params['is_energy']) && $params['is_energy']  === true) {
  2003.                 foreach (USER_PERMISSIONS['is_energy'] as $value) {
  2004.                     $mergedArray[] = $value;
  2005.                 }
  2006.             }
  2007.             if (isset($params['is_insurance']) && $params['is_insurance']  === true) {
  2008.                 foreach (USER_PERMISSIONS['is_insurance'] as $value) {
  2009.                     $mergedArray[] = $value;
  2010.                 }
  2011.             }
  2012.             if (isset($params['is_shippingAndOffshore']) && $params['is_shippingAndOffshore']  === true) {
  2013.                 foreach (USER_PERMISSIONS['is_shippingAndOffshore'] as $value) {
  2014.                     $mergedArray[] = $value;
  2015.                 }
  2016.             }
  2017.             if (isset($params['is_automotive']) && $params['is_automotive']  === true) {
  2018.                 foreach (USER_PERMISSIONS['is_automotive'] as $value) {
  2019.                     $mergedArray[] = $value;
  2020.                 }
  2021.             }
  2022.             if (isset($params['is_aviation']) && $params['is_aviation']  === true) {
  2023.                 foreach (USER_PERMISSIONS['is_aviation'] as $value) {
  2024.                     $mergedArray[] = $value;
  2025.                 }
  2026.             }
  2027.             if (isset($params['is_agriculture']) && $params['is_agriculture']  === true) {
  2028.                 foreach (USER_PERMISSIONS['is_agriculture'] as $value) {
  2029.                     $mergedArray[] = $value;
  2030.                 }
  2031.             }
  2032.             if (isset($params['invitingClients']) && $params['invitingClients']  === true) {
  2033.                 foreach (USER_PERMISSIONS['invitingClients'] as $value) {
  2034.                     $mergedArray[] = $value;
  2035.                 }
  2036.             }
  2037.             if (isset($params['managingClients']) && $params['managingClients']  === true) {
  2038.                 foreach (USER_PERMISSIONS['managingClients'] as $value) {
  2039.                     $mergedArray[] = $value;
  2040.                 }
  2041.             }
  2042.             if (isset($params['deletingClients']) && $params['deletingClients']  === true) {
  2043.                 foreach (USER_PERMISSIONS['deletingClients'] as $value) {
  2044.                     $mergedArray[] = $value;
  2045.                 }
  2046.             }
  2047.             if (isset($params['invitingNCMAdmin']) && $params['invitingNCMAdmin']  === true) {
  2048.                 foreach (USER_PERMISSIONS['invitingNCMAdmin'] as $value) {
  2049.                     $mergedArray[] = $value;
  2050.                 }
  2051.             }
  2052.             if (isset($params['managingNCMAdmin']) && $params['managingNCMAdmin']  === true) {
  2053.                 foreach (USER_PERMISSIONS['managingNCMAdmin'] as $value) {
  2054.                     $mergedArray[] = $value;
  2055.                 }
  2056.             }
  2057.             if (isset($params['deletingNCMAdmin']) && $params['deletingNCMAdmin']  === true) {
  2058.                 foreach (USER_PERMISSIONS['deletingNCMAdmin'] as $value) {
  2059.                     $mergedArray[] = $value;
  2060.                 }
  2061.             }
  2062.             // Get unique values using array_unique()
  2063.             $uniqueValues array_unique(array_values($mergedArray));
  2064.             $userPermission  array_values($uniqueValues);
  2065.             $apiGroup = new DataObject\APIGroup();
  2066.             $apiGroup->setParent(DataObject\Service::createFolderByPath('/UserManagement/APIGroups/CustomAPIGroups/'));
  2067.             $apiGroup->setKey(\Pimcore\Model\Element\Service::getValidKey($userPermission[0] . time(), 'object'));
  2068.             $apiGroup->setIsActive(true);
  2069.             $apiGroup->setAllowedApis($userPermission);
  2070.             $apiGroup->setPublished(true);
  2071.             $apiGroup->save();
  2072.             return $apiGroup;
  2073.         } catch (\Exception $ex) {
  2074.             throw new \Exception($ex->getMessage());
  2075.         }
  2076.         return $result;
  2077.     }
  2078.     /**
  2079.      * set User Permissions
  2080.      */
  2081.     public function setUserPermissions($params)
  2082.     {
  2083.         $result = [];
  2084.         try {
  2085.             // check if all permissions are given than now need to create seperate role 
  2086.             $loggedInUserRole = ($params['loggedInUser']->getRole() ? $params['loggedInUser']->getRole()->getName() : null);
  2087.             $invitedUserRoleName = ($params['user']->getRole() ? $params['user']->getRole()->getName() : null);
  2088.             if ($loggedInUserRole == USER_ROLES['NCM_OPERATOR'] || $loggedInUserRole == USER_ROLES['NCM_IT']) {
  2089.                 if ($params['allowCustomNotification'] == true && $params['allowAddLocation'] == true && $params['allowAlertHistoryForCustomAlerts'] == true && $params['allowForecast'] == true && $params['allowOrganizationAdminToInviteUsers'] == true) {
  2090.                     // delete specific role if all permission are given
  2091.                     $permission DataObject\Permission::getByAllowedUserRole($params['user'], true);
  2092.                     if ($permission instanceof \Pimcore\Model\DataObject\Permission) {
  2093.                         $permission->delete();
  2094.                     }
  2095.                     return ["success" => true"message" => "Set Permission."];
  2096.                 }
  2097.             } else {
  2098.                 if (
  2099.                     $params['allowCustomNotification'] == true &&
  2100.                     $params['allowAddLocation'] == true &&
  2101.                     $params['allowAlertHistoryForCustomAlerts'] == true &&
  2102.                     $params['allowForecast'] == true  &&
  2103.                     $params['automotive'] == true &&
  2104.                     $params['aviation'] == true &&
  2105.                     $params['insurance'] == true &&
  2106.                     $params['energy'] == true
  2107.                 ) {
  2108.                     // delete specific role if all permission are given
  2109.                     $permission DataObject\Permission::getByAllowedUserRole($params['user'], true);
  2110.                     if ($permission instanceof \Pimcore\Model\DataObject\Permission) {
  2111.                         $permission->delete();
  2112.                     }
  2113.                     return ["success" => true"message" => "set_permission"];
  2114.                 }
  2115.             }
  2116.             $permission DataObject\Permission::getByAllowedUserRole($params['user'], true);
  2117.             if ($permission) {
  2118.                 // $permission->setDepartment($allowAlertHistoryForCustomAlerts);
  2119.                 $permission->setAlert_history($params['allowAlertHistoryForCustomAlerts']);
  2120.                 $permission->setGet_custom_notification($params['allowCustomNotification']);
  2121.                 $permission->setCreate_location($params['allowAddLocation']);
  2122.                 $permission->setGet_weather($params['allowForecast']);
  2123.                 // set Industry permissions
  2124.                 $permission->setAutomotive($params['automotive'] == false false true);
  2125.                 $permission->setAviation($params['aviation'] == false false true);
  2126.                 $permission->setShipping_and_offshore($params['shippingAndOffshore'] == false false true);
  2127.                 $permission->setInsurance($params['insurance'] == false false true);
  2128.                 $permission->setEnergy($params['energy'] == false false true);
  2129.                 // default permission on the basis of add location
  2130.                 if (false == $params['allowAddLocation']) {
  2131.                     $permission->setEdit_location(false);
  2132.                     $permission->setDelete_location(false);
  2133.                     $permission->setSearch_location(false);
  2134.                     $permission->setCompare_location(false);
  2135.                 } else {
  2136.                     $permission->setEdit_location(true);
  2137.                     $permission->setDelete_location(true);
  2138.                     $permission->setSearch_location(true);
  2139.                     $permission->setCompare_location(true);
  2140.                 }
  2141.                 // default permission on the basis of add invite user
  2142.                 if ($params['allowOrganizationAdminToInviteUsers'] == true || $invitedUserRoleName == USER_ROLES['CLIENT_ADMIN']) {
  2143.                     $permission->setEdit_user(true);
  2144.                     $permission->setDelete_user(true);
  2145.                     $permission->setList_user(true);
  2146.                     $permission->setSuspend_user(true);
  2147.                     $permission->setInvite_user(true);
  2148.                     $permission->setResend_invite(true);
  2149.                     $permission->setCreate_user(true);
  2150.                 } else {
  2151.                     $permission->setEdit_user(false);
  2152.                     $permission->setDelete_user(false);
  2153.                     $permission->setList_user(false);
  2154.                     $permission->setSuspend_user(false);
  2155.                     $permission->setInvite_user(false);
  2156.                     $permission->setResend_invite(false);
  2157.                     $permission->setCreate_user(false);
  2158.                 }
  2159.                 // default permission to any user
  2160.                 $permission->setGet_profile(true);
  2161.                 $permission->setUpdate_profile(true);
  2162.                 $permission->setChange_password(true);
  2163.                 $permission->setView_user(true);
  2164.                 $permission->setList_location(true);
  2165.                 $permission->setView_location(true);
  2166.                 $permission->setAllowedUserRole($params['user']);
  2167.                 $permission->save();
  2168.             } else {
  2169.                 $permissions = new DataObject\Permission();
  2170.                 $permissions->setParent(DataObject\Service::createFolderByPath('/UserManagement/Permission/User'));
  2171.                 $permissions->setKey($params['user']->getEmail());
  2172.                 // $permissions->setDepartment($allowAlertHistoryForCustomAlerts);
  2173.                 $permissions->setAlert_history($params['allowAlertHistoryForCustomAlerts']);
  2174.                 $permissions->setGet_custom_notification($params['allowCustomNotification']);
  2175.                 $permissions->setInvite_user($params['allowOrganizationAdminToInviteUsers']);
  2176.                 $permissions->setCreate_location($params['allowAddLocation']);
  2177.                 $permissions->setGet_weather($params['allowForecast']);
  2178.                 // set Industry permissions
  2179.                 $permissions->setAutomotive($params['automotive'] == false false true);
  2180.                 $permissions->setAviation($params['aviation'] == false false true);
  2181.                 $permissions->setShipping_and_offshore($params['shippingAndOffshore'] == false false true);
  2182.                 $permissions->setInsurance($params['insurance'] == false false true);
  2183.                 $permissions->setEnergy($params['energy'] == false false true);
  2184.                 // default permission on the basis of add location
  2185.                 if ($params['allowAddLocation'] == true) {
  2186.                     $permissions->setEdit_location(true);
  2187.                     $permissions->setDelete_location(true);
  2188.                     $permissions->setSearch_location(true);
  2189.                     $permissions->setCompare_location(true);
  2190.                 } else {
  2191.                     $permissions->setEdit_location(false);
  2192.                     $permissions->setDelete_location(false);
  2193.                     $permissions->setSearch_location(false);
  2194.                     $permissions->setCompare_location(false);
  2195.                 }
  2196.                 // default permission on the basis of add invite user
  2197.                 if ($params['allowOrganizationAdminToInviteUsers'] == true || $invitedUserRoleName == USER_ROLES['CLIENT_ADMIN']) {
  2198.                     $permissions->setEdit_user(true);
  2199.                     $permissions->setDelete_user(true);
  2200.                     $permissions->setList_user(true);
  2201.                     $permissions->setSuspend_user(true);
  2202.                     $permissions->setInvite_user(true);
  2203.                     $permissions->setResend_invite(true);
  2204.                     $permissions->setCreate_user(true);
  2205.                 } else {
  2206.                     $permissions->setEdit_user(false);
  2207.                     $permissions->setDelete_user(false);
  2208.                     $permissions->setList_user(false);
  2209.                     $permissions->setSuspend_user(false);
  2210.                     $permissions->setInvite_user(false);
  2211.                     $permissions->setResend_invite(false);
  2212.                     $permissions->setCreate_user(false);
  2213.                 }
  2214.                 // default permission to any user
  2215.                 $permissions->setGet_profile(true);
  2216.                 $permissions->setUpdate_profile(true);
  2217.                 $permissions->setChange_password(true);
  2218.                 $permissions->setView_user(true);
  2219.                 $permissions->setList_location(true);
  2220.                 $permissions->setView_location(true);
  2221.                 $permissions->setAllowedUserRole($params['user']);
  2222.                 $permissions->setPublished(true);
  2223.                 $permissions->save();
  2224.             }
  2225.             return ["success" => true"message" => "set_permission."];
  2226.         } catch (\Exception $ex) {
  2227.             throw new \Exception($ex->getMessage());
  2228.         }
  2229.         return $result;
  2230.     }
  2231.     /**
  2232.      * set NCM Admin User Permissions
  2233.      */
  2234.     public function setNCMAdminUserPermissions($params)
  2235.     {
  2236.         $result = [];
  2237.         try {
  2238.             if ($params['invitingClients'] == false || $params['managingClients'] == false || $params['deletingClients'] == false || $params['invitingNCMAdmin'] == false || $params['managingNCMAdmin'] == false || $params['deletingNCMAdmin'] == false) {
  2239.                 $permission DataObject\Permission::getByAllowedUserRole($params['user'], true);
  2240.                 if ($permission) {
  2241.                     // default permission to any user
  2242.                     $permission->setGet_profile(true);
  2243.                     $permission->setUpdate_profile(true);
  2244.                     $permission->setChange_password(true);
  2245.                     $permission->setView_user(true);
  2246.                     $permission->setList_location(true);
  2247.                     $permission->setView_location(true);
  2248.                     $permission->setEdit_location(true);
  2249.                     $permission->setDelete_location(true);
  2250.                     $permission->setSearch_location(true);
  2251.                     $permission->setCompare_location(true);
  2252.                     $permission->setList_ncm_user(true);
  2253.                     $permission->setList_user(true);
  2254.                     // set Industry permissions
  2255.                     $permission->setAutomotive(true);
  2256.                     $permission->setAviation(true);
  2257.                     $permission->setShipping_and_offshore(true);
  2258.                     $permission->setInsurance(true);
  2259.                     $permission->setEnergy(true);
  2260.                     // set invitingClients permissions
  2261.                     $permission->setInvite_user($params['invitingClients'] == false false true);
  2262.                     $permission->setInvite_organization($params['invitingClients'] == false false true);
  2263.                     $permission->setResend_invite($params['invitingClients'] == false false true);
  2264.                     // set managingClients permissions
  2265.                     $permission->setEdit_user($params['managingClients'] == false false true);
  2266.                     // set deletingClients permissions
  2267.                     $permission->setDelete_user($params['deletingClients'] == false false true);
  2268.                     // set invitingNCMAdmin permissions
  2269.                     $permission->setInvite_ncm_user($params['invitingNCMAdmin'] == false false true);
  2270.                     // set managingNCMAdmin permissions
  2271.                     $permission->setEdit_ncm_user($params['managingNCMAdmin'] == false false true);
  2272.                     // set deletingNCMAdmin permissions
  2273.                     $permission->setDelete_ncm_user($params['deletingNCMAdmin'] == false false true);
  2274.                     $permission->setAllowedUserRole($params['user']);
  2275.                     $permission->save();
  2276.                 } else {
  2277.                     $permissions = new DataObject\Permission();
  2278.                     $permissions->setParent(DataObject\Service::createFolderByPath('/UserManagement/Permission/User'));
  2279.                     $permissions->setKey($params['user']->getEmail());
  2280.                     // $permissions->setDepartment($allowAlertHistoryForCustomAlerts);
  2281.                     // default permission to any user
  2282.                     $permissions->setGet_profile(true);
  2283.                     $permissions->setUpdate_profile(true);
  2284.                     $permissions->setChange_password(true);
  2285.                     $permissions->setView_user(true);
  2286.                     $permissions->setList_location(true);
  2287.                     $permissions->setView_location(true);
  2288.                     $permissions->setList_ncm_user(true);
  2289.                     $permissions->setList_user(true);
  2290.                     // set Industry permissions
  2291.                     $permissions->setAutomotive(true);
  2292.                     $permissions->setAviation(true);
  2293.                     $permissions->setShipping_and_offshore(true);
  2294.                     $permissions->setInsurance(true);
  2295.                     $permissions->setEnergy(true);
  2296.                     // set invitingClients permissions
  2297.                     $permissions->setInvite_user($params['invitingClients'] == false false true);
  2298.                     $permissions->setInvite_organization($params['invitingClients'] == false false true);
  2299.                     $permissions->setResend_invite($params['invitingClients'] == false false true);
  2300.                     // set managingClients permissions
  2301.                     $permissions->setEdit_user($params['managingClients'] == false false true);
  2302.                     // set deletingClients permissions
  2303.                     $permissions->setDelete_user($params['deletingClients'] == false false true);
  2304.                     // set invitingNCMAdmin permissions
  2305.                     $permissions->setInvite_ncm_user($params['invitingNCMAdmin'] == false false true);
  2306.                     // set managingNCMAdmin permissions
  2307.                     $permissions->setEdit_ncm_user($params['managingNCMAdmin'] == false false true);
  2308.                     // set deletingNCMAdmin permissions
  2309.                     $permissions->setDelete_ncm_user($params['deletingNCMAdmin'] == false false true);
  2310.                     $permissions->setAllowedUserRole($params['user']);
  2311.                     $permissions->setPublished(true);
  2312.                     $permissions->save();
  2313.                 }
  2314.                 return ["success" => true"message" => "set_permission"];
  2315.             } else {
  2316.                 // delete specific role if all permission are given
  2317.                 $permission DataObject\Permission::getByAllowedUserRole($params['user'], true);
  2318.                 if ($permission instanceof \Pimcore\Model\DataObject\Permission) {
  2319.                     $permission->delete();
  2320.                 }
  2321.                 return ["success" => true"message" => "set_permission"];
  2322.             }
  2323.         } catch (\Exception $ex) {
  2324.             throw new \Exception($ex->getMessage());
  2325.         }
  2326.         return $result;
  2327.     }
  2328.     public function getUserPermissionInfo($user$translator)
  2329.     {
  2330.         $userEmail = [];
  2331.         $userEmail['username'] = $user->getEmail();
  2332.         // return $permission = DataObject\Permission::getByAllowedUserRole($user, true);
  2333.         return $permission $this->userPermission->getUserPermissions($userEmail$translator);
  2334.     }
  2335.     public function getLocationList($user)
  2336.     {
  2337.         try {
  2338.             $entries = new DataObject\Location\Listing();
  2339.             $entries->setCondition("user LIKE " $entries->quote("%," $user->getId() . ",%"));
  2340.             $entries->load();
  2341.             $tempArr = [];
  2342.             if (!empty($entries)) {
  2343.                 foreach ($entries as $object) {
  2344.                     array_push($tempArr$object->getId());
  2345.                 }
  2346.             }
  2347.             return $tempArr;
  2348.         } catch (\Exception $ex) {
  2349.             throw new \Exception($ex->getMessage());
  2350.         }
  2351.     }
  2352.     public function assignLocationToUser($loggedInUser$locationIds$locationTagIds$targetUsers$targetUserGroups$weatherSevereAlert$customNotificationAlert$translator)
  2353.     {
  2354.         $assignedLocationArr = [];
  2355.         // Validate all users and user groups upfront
  2356.         $validatedUsers = [];
  2357.         if ($targetUsers) {
  2358.             foreach ($targetUsers as $userId) {
  2359.                 $user \Pimcore\Model\DataObject::getById($userId);
  2360.                 if (!$user instanceof Customer) {
  2361.                     return ["success" => false"message" => $translator->trans("Invalid User ID"), "userId" => $userId];
  2362.                 }
  2363.                 $organizationMatch \App\Lib\Utility::matchOrganization($user$loggedInUser);
  2364.                 if (!$organizationMatch["success"]) {
  2365.                     return ["success" => false"message" => $translator->trans("User ID does not belong to your organization."), "userId" => $userId];
  2366.                 }
  2367.                 $validatedUsers[] = $user;
  2368.             }
  2369.         }
  2370.         $validatedUserGroups = [];
  2371.         if ($targetUserGroups) {
  2372.             foreach ($targetUserGroups as $userGroupId) {
  2373.                 $userGroup \Pimcore\Model\DataObject::getById($userGroupId);
  2374.                 if (!$userGroup instanceof UserGroup) {
  2375.                     return ["success" => false"message" => $translator->trans("Invalid User Group ID"), "userGroupId" => $userGroupId];
  2376.                 }
  2377.                 $targetUsersInGroup = new DataObject\Customer\Listing();
  2378.                 $targetUsersInGroup->filterByUserGroup($userGroup);
  2379.                 foreach ($targetUsersInGroup as $user) {
  2380.                     $organizationMatch \App\Lib\Utility::matchOrganization($user$loggedInUser);
  2381.                     if (!$organizationMatch["success"]) {
  2382.                         return ["success" => false"message" => $translator->trans("A user in group ID does not belong to your organization."), "userGroupId" => $userGroupId];
  2383.                     }
  2384.                 }
  2385.                 $validatedUserGroups[] = $userGroup;
  2386.             }
  2387.         }
  2388.         // Process Locations by Location IDs
  2389.         if ($locationIds) {
  2390.             foreach ($locationIds as $locationID) {
  2391.                 $location \Pimcore\Model\DataObject::getById($locationID);
  2392.                 if ($location instanceof Location) {
  2393.                     // Assign to validated users
  2394.                     foreach ($validatedUsers as $user) {
  2395.                         $this->locationModel->locationMetaData($location$user$weatherSevereAlert$customNotificationAlert);
  2396.                         $assignedLocationArr[] = $location->getId();
  2397.                     }
  2398.                     // Assign to validated user groups
  2399.                     foreach ($validatedUserGroups as $userGroup) {
  2400.                         $targetUsersInGroup = new DataObject\Customer\Listing();
  2401.                         $targetUsersInGroup->filterByUserGroup($userGroup);
  2402.                         foreach ($targetUsersInGroup as $user) {
  2403.                             $this->locationModel->locationMetaData($location$user$weatherSevereAlert$customNotificationAlert);
  2404.                             $assignedLocationArr[] = $location->getId();
  2405.                         }
  2406.                     }
  2407.                 } else {
  2408.                     return ["success" => false"message" => $translator->trans("Invalid Location ID"), "locationId" => $locationID];
  2409.                 }
  2410.             }
  2411.         }
  2412.         // Process Locations by Location Tag IDs
  2413.         if ($locationTagIds) {
  2414.             foreach ($locationTagIds as $locationTagId) {
  2415.                 $locationTag \Pimcore\Model\DataObject::getById($locationTagId);
  2416.                 if ($locationTag instanceof Tags) {
  2417.                     $locations = new DataObject\Location\Listing();
  2418.                     $locations->setCondition("Tag LIKE " $locations->quote("%," $locationTag->getId() . ",%"));
  2419.                     $locations->load();
  2420.                     foreach ($locations as $location) {
  2421.                         if ($location instanceof Location) {
  2422.                             // Assign to validated users
  2423.                             foreach ($validatedUsers as $user) {
  2424.                                 $this->locationModel->locationMetaData($location$user$weatherSevereAlert$customNotificationAlert);
  2425.                                 $assignedLocationArr[] = $location->getId();
  2426.                             }
  2427.                             // Assign to validated user groups
  2428.                             foreach ($validatedUserGroups as $userGroup) {
  2429.                                 $targetUsersInGroup = new DataObject\Customer\Listing();
  2430.                                 $targetUsersInGroup->filterByUserGroup($userGroup);
  2431.                                 foreach ($targetUsersInGroup as $user) {
  2432.                                     $this->locationModel->locationMetaData($location$user$weatherSevereAlert$customNotificationAlert);
  2433.                                     $assignedLocationArr[] = $location->getId();
  2434.                                 }
  2435.                             }
  2436.                         }
  2437.                     }
  2438.                 } else {
  2439.                     return ["success" => false"message" => $translator->trans("Invalid Location Tag ID"), 'locationId' => $locationTagId];
  2440.                 }
  2441.             }
  2442.         }
  2443.         return array_values(array_unique($assignedLocationArr));
  2444.     }
  2445.     public function getUserLocations($user)
  2446.     {
  2447.         try {
  2448.             $locationData = [];
  2449.             $locations $this->getLocationList($user);
  2450.             if ($locations) {
  2451.                 foreach ($locations as $locationId) {
  2452.                     $location \Pimcore\Model\DataObject::getById($locationId);
  2453.                     if ($location instanceof Location) {
  2454.                         $alertConfig $this->locationModel->getUserSevereAlertAndCustomNotification($location$user);
  2455.                         $locationData[] = [
  2456.                             'id' => $location->getId(),
  2457.                             'name' => $location->getName(),
  2458.                             'title' => $location->getTitle(),
  2459.                             'coordinates' => $location->getCoordinates(),
  2460.                             'severeWeatherAlert' => isset($alertConfig['get_severe_alert']) && ($alertConfig['get_severe_alert'] == true) ?? false,
  2461.                             'customNotificationAlert' => isset($alertConfig['get_custom_notification']) && ($alertConfig['get_custom_notification'] == true) ?? false,
  2462.                         ];
  2463.                     }
  2464.                 }
  2465.             }
  2466.             return $locationData;
  2467.         } catch (\Exception $ex) {
  2468.             throw new \Exception($ex->getMessage());
  2469.         }
  2470.     }
  2471.     public function getUsersLocationByOrganizationId($organizationId)
  2472.     {
  2473.         // try {
  2474.         $organization \Pimcore\Model\DataObject::getById($organizationId);
  2475.         if (!$organization instanceof \Pimcore\Model\DataObject\Organization) {
  2476.             throw new \Exception("Organization not found");
  2477.         }
  2478.         $customers = new \Pimcore\Model\DataObject\Customer\Listing();
  2479.         $customers->filterByOrganization($organization);
  2480.         if ($customers->getCount() == 0) {
  2481.             throw new \Exception("Customers does not exists in this organization");
  2482.         }
  2483.         $locationData = [];
  2484.         foreach ($customers as $customer) {
  2485.             $locations $this->getLocationList($customer);
  2486.             if ($locations) {
  2487.                 foreach ($locations as $locationId) {
  2488.                     $location \Pimcore\Model\DataObject::getById($locationId);
  2489.                     if ($location instanceof Location) {
  2490.                         $alertConfig $this->locationModel->getUserSevereAlertAndCustomNotification($location$customer);
  2491.                         $locationData[] = [
  2492.                             'id' => $location->getId(),
  2493.                             'name' => $location->getName(),
  2494.                             'title' => $location->getTitle(),
  2495.                             'coordinates' => $location->getCoordinates(),
  2496.                             'severeWeatherAlert' => isset($alertConfig['get_severe_alert']) && ($alertConfig['get_severe_alert'] == true) ?? false,
  2497.                             'customNotificationAlert' => isset($alertConfig['get_custom_notification']) && ($alertConfig['get_custom_notification'] == true) ?? false,
  2498.                             "customerId" => $customer->getId(),
  2499.                             "customerName" => $customer->getName(),
  2500.                             "customerEmail" => $customer->getEmail()
  2501.                         ];
  2502.                     }
  2503.                 }
  2504.             }
  2505.         }
  2506.         return $locationData;
  2507.         // } catch (\Exception $ex) {
  2508.         //     throw new \Exception($ex->getMessage());
  2509.         // }
  2510.     }
  2511.     /**
  2512.      * Get User Assigned API Groups
  2513.      *
  2514.      */
  2515.     public function getUserApiGroups($user)
  2516.     {
  2517.         $apiGroups = [];
  2518.         $subscriptions = new DataObject\Subscription\Listing();
  2519.         $subscriptions->filterBySubscribedUser($user);
  2520.         $currentDate date('Y-m-d'); // Assuming the date and time format is 'YYYY-MM-DD'
  2521.         $subscriptions->filterByEndDate(strtotime($currentDate), ">=");
  2522.         $subscriptions->filterBySubscriptionType("custom");
  2523.         $subscriptions->filterByIsActive(true);
  2524.         $subscriptions->load();
  2525.         foreach ($subscriptions as $subscription) {
  2526.             $package $subscription->getSubscribedPackage();
  2527.             if ($package instanceof DataObject\Package) {
  2528.                 if ($package->getApiGroups()) {
  2529.                     foreach ($package->getApiGroups() as $key => $ApiGroup) {
  2530.                         $apiGroups[] = [
  2531.                             "apiGroupId" => $ApiGroup->getId(),
  2532.                             "type" => $ApiGroup->getApiGroupType(),
  2533.                             "name" => $ApiGroup->getApiGroupName('en'),
  2534.                             "name_ar" => $ApiGroup->getApiGroupName('ar'),
  2535.                         ];
  2536.                     }
  2537.                 }
  2538.             }
  2539.         }
  2540.         return $apiGroups;
  2541.     }
  2542.     /**
  2543.      * generate unsubscribe token user
  2544.      */
  2545.     public function unSubscribeGenerateToken($email)
  2546.     {
  2547.         $token '';
  2548.         try {
  2549.             //generate token
  2550.             $user DataObject\Customer::getByEmail($emailtrue);
  2551.             // $token = md5($user->getEmail() . time() . uniqid());
  2552.             $token base64_encode($user->getEmail() . time() . uniqid());
  2553.             $user->setunSubscribeToken($token);
  2554.             $user->save();
  2555.             return $token;
  2556.         } catch (\Exception $ex) {
  2557.             throw new \Exception($ex->getMessage());
  2558.         }
  2559.         return $token;
  2560.     }
  2561.     /**
  2562.      * generate unsubscribe ews notification token user
  2563.      */
  2564.     public function unSubscribeEwsGenerateToken($email)
  2565.     {
  2566.         $token '';
  2567.         try {
  2568.             //generate token
  2569.             $user DataObject\Customer::getByEmail($emailtrue);
  2570.             // $token = md5($user->getEmail() . time() . uniqid());
  2571.             $token base64_encode($user->getEmail() . time() . uniqid());
  2572.             $user->setEwsNotificationToken($token);
  2573.             $user->save();
  2574.             return $token;
  2575.         } catch (\Exception $ex) {
  2576.             throw new \Exception($ex->getMessage());
  2577.         }
  2578.         return $token;
  2579.     }
  2580.     /**
  2581.      * Get NCM User List
  2582.      */
  2583.     public function getAllActiveUsersInExcelData($params$user$translator)
  2584.     {
  2585.         $result = [];
  2586.         try {
  2587.             $userDataEn = [];
  2588.             // Get All the Classes
  2589.             $class = new \Pimcore\Model\DataObject\ClassDefinition();
  2590.             $customer $class->getDao()->getIdByName('Customer');
  2591.             $subscription $class->getDao()->getIdByName('Subscription');
  2592.             $userRole $class->getDao()->getIdByName('UserRole');
  2593.             $organization $class->getDao()->getIdByName('Organization');
  2594.             $package $class->getDao()->getIdByName('Package');
  2595.             $db Db::get();
  2596.             $select $db->createQueryBuilder();
  2597.             $select->select('customer.oo_id');
  2598.             $select->from('object_' $customer'customer');
  2599.             $select->innerJoin('customer''object_' $subscription'subscription''customer.oo_id = subscription.subscribedUser__id');
  2600.             $select->innerJoin('subscription''object_' $package'package''package.oo_id = subscription.subscribedPackage__id');
  2601.             $select->innerJoin('customer''object_' $organization'organization''organization.oo_id = customer.organization__id');
  2602.             $select->innerJoin('customer''object_' $userRole'userRole''userRole.oo_id = customer.role__id');
  2603.             // if (isset($params['search']) && !empty($params['search'])) {
  2604.             //     $select->andWhere("customer.name LIKE " . $db->quote("%" . $params['search'] . "%") . " OR customer.email LIKE " . $db->quote("%" . $params['search'] . "%"));
  2605.             // }
  2606.             if (isset($params['type']) && !empty($params['type'])) {
  2607.                 if ($params['type'] == 'client') {
  2608.                     $select->andWhere("userRole.name = " $db->quote(USER_ROLES['CLIENT_ADMIN']) . " OR userRole.name = " $db->quote(USER_ROLES['CLIENT_USER']));
  2609.                 } elseif ($params['type'] == 'ncm') {
  2610.                     $select->andWhere("userRole.name = " $db->quote(USER_ROLES['NCM_IT']) . " OR userRole.name = " $db->quote(USER_ROLES['NCM_OPERATOR']));
  2611.                 }
  2612.             }
  2613.             $select->andWhere("customer.oo_id != " $db->quote($user->getId()));
  2614.             $select->andWhere("customer.isDeleted != 1 or customer.isDeleted IS NULL");
  2615.             if (!empty($params["entityId"])) {
  2616.                 $select->andWhere("organization.oo_id = " $db->quote($params["entityId"]));
  2617.             }
  2618.             $select->orderBy('oo_id''DESC');
  2619.             $select->groupBy(array('oo_id'));
  2620.             $select $select->execute();
  2621.             $usersIds $select->fetchAllAssociative();
  2622.             if (count($usersIds) == 0) {
  2623.                 return ["success" => false"message" => $translator->trans("no_user_available_in_NCM")];
  2624.             }
  2625.             $userDataEn[] = [
  2626.                 'S. No' => 'S. No',
  2627.                 'Username' => 'Username',
  2628.                 'Entity' => 'Entity',
  2629.                 'Entity AR' => 'Entity AR',
  2630.                 'Email Address' => 'Email Address',
  2631.                 'Type' => 'Type',
  2632.                 'Role' => 'Role',
  2633.                 'Created By' => 'Created By',
  2634.                 'Created On' => 'Created On',
  2635.                 'Package' => 'Package',
  2636.                 'Package Expiry' => 'Package Expiry',
  2637.                 'Status' => 'Status',
  2638.             ];
  2639.             foreach ($usersIds as $userKey => $usersId) {
  2640.                 $usersData DataObject\Customer::getById($usersId['oo_id'], true);
  2641.                 if ($usersData instanceof \Pimcore\Model\DataObject\Customer) {
  2642.                     // Get Custom Subscription of the organization and package
  2643.                     $customSubscriptions = new DataObject\Subscription\Listing();
  2644.                     $customSubscriptions->filterBySubscribedUser($usersData);
  2645.                     $customSubscriptions->filterByIsActive(true);
  2646.                     $status "";
  2647.                     if ($usersData->getToken() == "" && $usersData->isPublished() == true) {
  2648.                         if ($customSubscriptions->count() > 0) {
  2649.                             $status "Active";
  2650.                         } else {
  2651.                             $status "Suspended";
  2652.                         }
  2653.                     } elseif ($usersData->getToken() != "" && $usersData->isPublished() == false) {
  2654.                         $status "Pending";
  2655.                     }
  2656.                     $permissionObj $this->getUserPermissionInfo($usersData$translator);
  2657.                     $userPermissions $permissionObj['success'] ? $permissionObj['grants'] : null;
  2658.                     $customSubscriptions->filterBySubscriptionType("custom");
  2659.                     $customSubscriptions->setOrderKey("o_modificationDate");
  2660.                     $customSubscriptions->setOrder("desc");
  2661.                     $apiGroupData = [];
  2662.                     $packageData = [];
  2663.                     if ($customSubscriptions->count() > 0) {
  2664.                         foreach ($customSubscriptions as $key => $customSubscription) {
  2665.                             if ($customSubscription instanceof \Pimcore\Model\DataObject\Subscription) {
  2666.                                 $package $customSubscription->getSubscribedPackage();
  2667.                                 $disallowedApiGroups $customSubscription->getDisallowedApiGroups();
  2668.                                 if ($package) {
  2669.                                     $packageData[] = [
  2670.                                         "id" => $package->getId(),
  2671.                                         "name" => $package->getPackageName("en"),
  2672.                                         "package_expiry" => $customSubscription->getEndDate(date("M d, Y"))
  2673.                                     ];
  2674.                                     $apiGroups $package->getApiGroups();
  2675.                                     if ($apiGroups) {
  2676.                                         foreach ($apiGroups as  $apiGroup) {
  2677.                                             $apiGroupId $apiGroup->getId();
  2678.                                             $apiGroupNameEn $apiGroup->getApiGroupName('en');
  2679.                                             $apiGroupNameAr $apiGroup->getApiGroupName('ar');
  2680.                                             $isDisallowed false;
  2681.                                             // Check if the current API group is disallowed
  2682.                                             foreach ($disallowedApiGroups as $disallowedApiGroup) {
  2683.                                                 if ($apiGroupId == $disallowedApiGroup->getId()) {
  2684.                                                     $isDisallowed true;
  2685.                                                     break;
  2686.                                                 }
  2687.                                             }
  2688.                                             // Only add the API group if it's not disallowed
  2689.                                             if (!$isDisallowed) {
  2690.                                                 $apiGroupData[] = [
  2691.                                                     "id" => $apiGroupId,
  2692.                                                     "name" => $apiGroupNameEn,
  2693.                                                     "name_ar" => $apiGroupNameAr
  2694.                                                 ];
  2695.                                             }
  2696.                                         }
  2697.                                     }
  2698.                                 }
  2699.                             }
  2700.                         }
  2701.                     }
  2702.                     $userDataEn[] = [
  2703.                         'S. No' => $userKey 1,
  2704.                         'Username' => $usersData->getName(),
  2705.                         'Entity' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName() : null,
  2706.                         'Entity AR' => ($usersData->getOrganization()) ? $usersData->getOrganization()->getName('ar') : null,
  2707.                         'Email Address' => $usersData->getEmail(),
  2708.                         'Type' => $translator->trans('user', [], null'en'),
  2709.                         'Role' => $usersData->getRole() ? $translator->trans($usersData->getRole()->getName(), [], null'en') : null,
  2710.                         'Created By' => $usersData->getCreatedBy() ? $usersData->getCreatedBy()->getName() : null,
  2711.                         'Created On' => $usersData->getCreationDate() ? date('Y-m-d'$usersData->getCreationDate()) : null,
  2712.                         'Package' => isset($packageData[0]['name']) ? $packageData[0]['name'] : null,
  2713.                         'Package Expiry' => isset($packageData[0]['package_expiry']) ? date("M d, Y"strtotime($packageData[0]['package_expiry'])) : null,
  2714.                         'Status' => $translator->trans($status, [], null'en'),
  2715.                     ];
  2716.                 }
  2717.             }
  2718.             $excelData ExcelGenerator::createAndSaveXlsx($userDataEn$params['type'] . "_users_data"true'/users/excel/');
  2719.             return ["success" => true"message" => $translator->trans("excel_generated"), "data" =>  $excelData];
  2720.         } catch (\Exception $ex) {
  2721.             throw new \Exception($ex->getMessage());
  2722.         }
  2723.     }
  2724.     public function createWsoUser($name$email$translator): array
  2725.     {
  2726.         try {
  2727.             Utility::validateEmail($email);
  2728.             Utility::validateName($name);
  2729.             $user DataObject\Customer::getByEmail($emailtrue);
  2730.             if ($user instanceof \Pimcore\Model\DataObject\Customer) {
  2731.                 return ["success" => false"message" => $translator->trans("user_already_exists")];
  2732.             }
  2733.             $registerUser = new DataObject\Customer();
  2734.             $registerUser->setParent(DataObject\Service::createFolderByPath('/UserManagement/WsoUsers'));
  2735.             $registerUser->setKey(trim(strip_tags($email)));
  2736.             $registerUser->setUserType('public');
  2737.             $registerUser->setName(strip_tags($name));
  2738.             $registerUser->setEmail(trim(strip_tags($email)));
  2739.             $registerUser->setPublished(true);
  2740.             $registerUser->setIsActive(true);
  2741.             $registerUser->setSendEwsEmail(false);
  2742.             $registerUser->setOmitMandatoryCheck(true);
  2743.             $registerUser->save();
  2744.             return ["success" => true"message" => $translator->trans("user_registered_success"), 'data' => $registerUser->getId()];
  2745.         } catch (\Exception $ex) {
  2746.             throw new \Exception($ex->getMessage());
  2747.         }
  2748.         return [];
  2749.     }
  2750.     /**
  2751.      * Create User Tag
  2752.      */
  2753.     public function createUserTag($user$name$request$lang$translator$organization false)
  2754.     {
  2755.         $result = [];
  2756.         try {
  2757.             $userTag = new DataObject\UserTag();
  2758.             if ($organization) {
  2759.                 $userTag->setParent(DataObject\Service::createFolderByPath('/Organization/tags/'));
  2760.             } else {
  2761.                 $userTag->setParent(DataObject\Service::createFolderByPath('/UserManagement/user tags/'));
  2762.             }
  2763.             $userTag->setKey(\Pimcore\Model\Element\Service::getValidKey($name '_' uniqid(), 'object'));
  2764.             $userTag->setName(strip_tags($name));
  2765.             $userTag->setOrganization($organization);
  2766.             $userTag->setPublished(true);
  2767.             $userTag->save();
  2768.             if ($userTag) {
  2769.                 return ["success" => true"message" => $translator->trans("user_tag_created_successfully"), "user_tag_id" => $userTag->getId()];
  2770.             }
  2771.         } catch (\Exception $ex) {
  2772.             throw new \Exception($ex->getMessage());
  2773.         }
  2774.         return $result;
  2775.     }
  2776.     /**
  2777.      * User Tag Listing
  2778.      */
  2779.     public function userTagListing($user$translator$paginator$params)
  2780.     {
  2781.         $result = [];
  2782.         try {
  2783.             $tagData = [];
  2784.             $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  2785.             $page = isset($params['page']) ? $params['page'] : 1;
  2786.             $tagList = new DataObject\UserTag\Listing();
  2787.             // Check if organization parameter is set and not empty
  2788.             if (isset($params['organization']) && !empty($params['organization'])) {
  2789.                 $organization $params['organization'];
  2790.                 $tagList->setCondition("organization = true");
  2791.             } else {
  2792.                 $tagList->setCondition("(organization = false OR organization is null)");
  2793.             }
  2794.             if (isset($params['search']) && !empty($params['search'])) {
  2795.                 $tagList->setCondition("name LIKE " $tagList->quote("%" $params['search'] . "%"));
  2796.             }
  2797.             $allowed = [
  2798.                 'name'
  2799.             ];
  2800.             if ($params['sortBy'] && in_array($params['sortBy'], $allowedtrue)) {
  2801.                 $tagList->setOrderKey($params['sortBy']);
  2802.                 $tagList->setOrder($params['sortDir'] === 'DESC' 'DESC' 'ASC');
  2803.             }
  2804.             $paginator $paginator->paginate(
  2805.                 $tagList,
  2806.                 $page,
  2807.                 $pageSize
  2808.             );
  2809.             if ($paginator->getTotalItemCount() > 0) {
  2810.                 foreach ($paginator as $key => $tag) {
  2811.                     $tagData[] = [
  2812.                         'id' => $tag->getId(),
  2813.                         'name' => $tag->getName()
  2814.                     ];
  2815.                 }
  2816.                 if (!empty($tagData) && count($tagData) > 0) {
  2817.                     return ["success" => true"data" => $tagData"paginationVariables" => $paginator->getPaginationData()];
  2818.                 }
  2819.             }
  2820.             return ["success" => false"message" => $translator->trans("user_groups_are_not_available")];
  2821.         } catch (\Exception $ex) {
  2822.             throw new \Exception($ex->getMessage());
  2823.         }
  2824.         return $result;
  2825.     }
  2826.     /**
  2827.      * Validate the unsubscribe token
  2828.      *
  2829.      * @param string $token
  2830.      * @param Translator $translator
  2831.      * @return array
  2832.      */
  2833.     public function unsubscribeTokenValidate($token$translator)
  2834.     {
  2835.         // Fetch user by unsubscribe token
  2836.         $user Customer::getByUnSubToken($tokentrue);
  2837.         if (!$user) {
  2838.             return [
  2839.                 "success" => false,
  2840.                 "message" => $translator->trans("invalid_token")
  2841.             ];
  2842.         }
  2843.         // Prepare the data
  2844.         $data = [
  2845.             "success" => true,
  2846.             "id" => $user->getId(),
  2847.             "email" => $user->getEmail(),
  2848.             "customNotification" => $user->getCustomNotification(),
  2849.             "earlyWarningNotification" => $user->getEarlyWarningNotification(),
  2850.             "advanceCustomNotification" => $user->getAdvanceCustomNotification(),
  2851.             "severeWeatherAlert" => $user->getSevereWeatherAlert()
  2852.         ];
  2853.         return $data;
  2854.     }
  2855.     /**
  2856.      * update user Subscription
  2857.      *
  2858.      * @param string $params
  2859.      * @param Translator $translator
  2860.      * @return array
  2861.      */
  2862.     public function updateUserSubscription($params$translator)
  2863.     {
  2864.         // Fetch user by unsubscribe token
  2865.         $user Customer::getById($params['id'], true);
  2866.         if (!$user) {
  2867.             return [
  2868.                 "success" => false,
  2869.                 "message" => $translator->trans("invalid_user_id")
  2870.             ];
  2871.         }
  2872.         if (isset($params['customNotification'])) {
  2873.             $user->setCustomNotification($params['customNotification']);
  2874.         }
  2875.         if (isset($params['earlyWarningNotification'])) {
  2876.             $user->setEarlyWarningNotification($params['earlyWarningNotification']);
  2877.         }
  2878.         if (isset($params['advanceCustomNotification'])) {
  2879.             $user->setAdvanceCustomNotification($params['advanceCustomNotification']);
  2880.         }
  2881.         if (isset($params['severeWeatherAlert'])) {
  2882.             $user->setSevereWeatherAlert($params['severeWeatherAlert']);
  2883.         }
  2884.         $user->save();
  2885.         // Prepare the data
  2886.         $data = [
  2887.             "success" => true,
  2888.             "message" => $translator->trans("subscription_updated")
  2889.         ];
  2890.         return $data;
  2891.     }
  2892.     public function saveBulkUserInviteLog($user$data$organizationId)
  2893.     {
  2894.         $bulkUserInviteLog = new DataObject\BulkInviteUserReport();
  2895.         $bulkUserInviteLog->setParent(DataObject\Service::createFolderByPath('/UserManagement/BulkUserInviteLog'));
  2896.         $bulkUserInviteLog->setKey(\Pimcore\Model\Element\Service::getValidKey(uniqid(), 'object'));
  2897.         $bulkUserInviteLog->setPublished(true);
  2898.         $bulkUserInviteLog->setJsonData(json_encode($data));
  2899.         $organization DataObject\Organization::getById($organizationId);
  2900.         if ($organization) {
  2901.             $bulkUserInviteLog->setOrganization($organization);
  2902.         }
  2903.         $bulkUserInviteLog->setCreatedBy($user);
  2904.         $bulkUserInviteLog->save();
  2905.         return $bulkUserInviteLog;
  2906.     }
  2907.     public function getEntitySubscription($user)
  2908.     {
  2909.         $package null;
  2910.         $subscriptions = new Subscription\Listing();
  2911.         $subscriptions->filterBySubscribedUser($user);
  2912.         $subscriptions->filterBySubscriptionType("custom");
  2913.         $subscription $subscriptions->current();
  2914.         return $subscription;
  2915.     }
  2916.     public function getEntityPackage($user)
  2917.     {
  2918.         $package null;
  2919.         $subscriptions = new Subscription\Listing();
  2920.         $subscriptions->filterBySubscribedUser($user);
  2921.         $subscriptions->filterBySubscriptionType("custom");
  2922.         $subscription $subscriptions->current();
  2923.         if ($subscription) {
  2924.             $package $subscription->getSubscribedPackage();
  2925.         }
  2926.         return $package;
  2927.     }
  2928.     private function getInvitationDate($user): string
  2929.     {
  2930.         try {
  2931.             $token $user->getToken();
  2932.             if (empty($token)) {
  2933.                 $creationDate $user->getCreationDate();
  2934.                 if ($creationDate) {
  2935.                     return date('Y-m-d H:i:s'$creationDate);
  2936.                 }
  2937.                 return "Unknown";
  2938.             }
  2939.             $tokenParts explode('.'$token);
  2940.             if (count($tokenParts) !== 3) {
  2941.                 $creationDate $user->getCreationDate();
  2942.                 if ($creationDate) {
  2943.                     return date('Y-m-d H:i:s'$creationDate);
  2944.                 }
  2945.                 return "Invalid token";
  2946.             }
  2947.             $payload json_decode(base64_decode(str_replace(['-''_'], ['+''/'], $tokenParts[1])), true);
  2948.             if (!$payload || !isset($payload['time'])) {
  2949.                 $creationDate $user->getCreationDate();
  2950.                 if ($creationDate) {
  2951.                     return date('Y-m-d H:i:s'$creationDate);
  2952.                 }
  2953.                 return "No invitation time found";
  2954.             }
  2955.             $invitationTime $payload['time'];
  2956.             return date('Y-m-d H:i:s'$invitationTime);
  2957.         } catch (\Exception $e) {
  2958.             $creationDate $user->getCreationDate();
  2959.             if ($creationDate) {
  2960.                 return date('Y-m-d H:i:s'$creationDate);
  2961.             }
  2962.             return "Error getting date";
  2963.         }
  2964.     }
  2965.     public function listC2Users($params$translator)
  2966.     {
  2967.         try {
  2968.             $userData = [];
  2969.             // Get class IDs for table names
  2970.             $class = new \Pimcore\Model\DataObject\ClassDefinition();
  2971.             $customerClassId $class->getDao()->getIdByName('Customer');
  2972.             $subscriptionClassId $class->getDao()->getIdByName('Subscription');
  2973.             $packageClassId $class->getDao()->getIdByName('Package');
  2974.             $db Db::get();
  2975.             $select $db->createQueryBuilder();
  2976.             // Select customer data and subscription/package info
  2977.             $select->select([
  2978.                 'customer.oo_id AS customer_id',
  2979.                 'customer.name AS customer_name',
  2980.                 'customer.email AS customer_email',
  2981.                 'customer.phoneNo AS customer_phone',
  2982.                 'subscription.oo_id AS subscription_id',
  2983.                 'subscription.isActive AS subscription_is_active',
  2984.                 'subscription.endDate AS subscription_end_date',
  2985.                 'subscription.subscriptionType AS subscription_type'
  2986.             ]);
  2987.             $select->from('object_' $customerClassId'customer');
  2988.             // INNER JOIN with Subscription to get only customers with subscriptions
  2989.             // Then filter by active subscriptions
  2990.             $select->innerJoin(
  2991.                 'customer',
  2992.                 'object_' $subscriptionClassId,
  2993.                 'subscription',
  2994.                 'customer.oo_id = subscription.subscribedUser__id'
  2995.             );
  2996.             // Apply filters
  2997.             // Phone number must exist and be exactly 9 digits
  2998.             $select->where("customer.phoneNo IS NOT NULL AND customer.phoneNo != '' AND CHAR_LENGTH(customer.phoneNo) = 9");
  2999.             
  3000.             // Customer must be published
  3001.             $select->andWhere("customer.o_published = 1");
  3002.             
  3003.             // Only active subscriptions
  3004.             $select->andWhere("subscription.isActive = 1");
  3005.             
  3006.             // Only 'custom' subscription type (matching the commented code pattern)
  3007.             $select->andWhere("subscription.subscriptionType = " $db->quote('custom'));
  3008.             
  3009.             // Only subscriptions with end date in future (or no expiry)
  3010.             // Pimcore stores dates as Unix timestamps, so compare with current timestamp
  3011.             $currentTimestamp time();
  3012.             $select->andWhere("(subscription.endDate IS NULL OR subscription.endDate >= " $currentTimestamp ")");
  3013.             // Execute query
  3014.             $results $select->execute()->fetchAllAssociative();
  3015.             // Process results
  3016.             foreach ($results as $row) {
  3017.                 // Parse endDate - Pimcore stores dates as Unix timestamps
  3018.                 $packageExpiry null;
  3019.                 if (!empty($row['subscription_end_date'])) {
  3020.                     try {
  3021.                         // Check if it's a Unix timestamp (numeric) or date string
  3022.                         if (is_numeric($row['subscription_end_date'])) {
  3023.                             // Unix timestamp - use @ prefix to parse
  3024.                             $date = new \DateTime('@' $row['subscription_end_date']);
  3025.                             $date->setTimezone(new \DateTimeZone('Asia/Riyadh'));
  3026.                             $packageExpiry $date->format('M d, Y');
  3027.                         } else {
  3028.                             // Date string - parse directly
  3029.                             $date = new \DateTime($row['subscription_end_date']);
  3030.                             $packageExpiry $date->format('M d, Y');
  3031.                         }
  3032.                     } catch (\Exception $e) {
  3033.                         // If parsing fails, log and continue
  3034.                         error_log('Error parsing subscription end date: ' $e->getMessage() . ' - Value: ' $row['subscription_end_date']);
  3035.                         $packageExpiry null;
  3036.                     }
  3037.                 }
  3038.                 
  3039.                 $userData[] = [
  3040.                     'id' => (int) $row['customer_id'],
  3041.                     'name' => $row['customer_name'] ?? '',
  3042.                     'email' => $row['customer_email'] ?? '',
  3043.                     'phoneNumber' => '+966' $row['customer_phone'],
  3044.                     'package_expiry' => $packageExpiry,
  3045.                     'status' => $row['subscription_is_active'] ? 'Active' 'Suspended',
  3046.                 ];
  3047.             }
  3048.             return ["success" => true"data" => $userData];
  3049.         } catch (\Exception $e) {
  3050.             error_log('Error in listC2Users: ' $e->getMessage());
  3051.             return ["success" => false"error" => $e->getMessage(), "data" => []];
  3052.         }
  3053.     }
  3054.     /**
  3055.      * List user groups with simplified response (groupid, name, user_ids)
  3056.      * Only includes users with mobile numbers (like listC2Users logic)
  3057.      */
  3058.     public function listUserGroupsSimple($user$translator): array
  3059.     {
  3060.         try {
  3061.             $organization $user->getOrganization();
  3062.             if (!$organization instanceof DataObject\Organization) {
  3063.                 return ["success" => false"message" => $translator->trans("user_does_not_belongs_to_organization")];
  3064.             }
  3065.             // Get class IDs for table names
  3066.             $class = new \Pimcore\Model\DataObject\ClassDefinition();
  3067.             $customerClassId $class->getDao()->getIdByName('Customer');
  3068.             $subscriptionClassId $class->getDao()->getIdByName('Subscription');
  3069.             $db Db::get();
  3070.             // Load UserGroup listing
  3071.             $userGroupList = new DataObject\UserGroup\Listing();
  3072.             $userGroupList->filterByOrganization($organization);
  3073.             $userGroupList->setOrderKey("oo_id");
  3074.             $userGroupList->setOrder("desc");
  3075.             $userGroupListData = [];
  3076.             foreach ($userGroupList as $userGroup) {
  3077.                 $groupId $userGroup->getId();
  3078.                 
  3079.                 // Use direct SQL to find users in this group
  3080.                 // Pimcore stores userGroup as comma-separated string: ",398039,398040,"
  3081.                 $select $db->createQueryBuilder();
  3082.                 $select->select(['customer.oo_id AS customer_id''customer.phoneNo AS phone_no']);
  3083.                 $select->from('object_' $customerClassId'customer');
  3084.                 
  3085.                 // Filter by user group - format is ",groupId," to match exact group ID
  3086.                 $select->where("customer.userGroup LIKE :groupIdPattern");
  3087.                 $select->setParameter('groupIdPattern''%,' $groupId ',%');
  3088.                 
  3089.                 // Join with subscription to filter active subscriptions
  3090.                 $select->innerJoin(
  3091.                     'customer',
  3092.                     'object_' $subscriptionClassId,
  3093.                     'subscription',
  3094.                     'customer.oo_id = subscription.subscribedUser__id'
  3095.                 );
  3096.                 // Apply mobile number filter (same as listC2Users)
  3097.                 $select->andWhere("customer.phoneNo IS NOT NULL AND customer.phoneNo != '' AND CHAR_LENGTH(customer.phoneNo) = 9");
  3098.                 
  3099.                 // Customer must be published
  3100.                 $select->andWhere("customer.o_published = 1");
  3101.                 
  3102.                 // Only active subscriptions
  3103.                 $select->andWhere("subscription.isActive = 1");
  3104.                 
  3105.                 // Only 'custom' subscription type
  3106.                 $select->andWhere("subscription.subscriptionType = " $db->quote('custom'));
  3107.                 
  3108.                 // Only subscriptions with end date in future (or no expiry)
  3109.                 $currentTimestamp time();
  3110.                 $select->andWhere("(subscription.endDate IS NULL OR subscription.endDate >= " $currentTimestamp ")");
  3111.                 $results $select->execute()->fetchAllAssociative();
  3112.                 
  3113.                 // Convert user_ids to phone numbers
  3114.                 $userPhones = [];
  3115.                 foreach ($results as $row) {
  3116.                     $phoneNo $row['phone_no'];
  3117.                     if (!empty($phoneNo) && strlen($phoneNo) === 9) {
  3118.                         $userPhones[] = '+966' $phoneNo;
  3119.                     }
  3120.                 }
  3121.                 $userGroupListData[] = [
  3122.                     'groupid' => $userGroup->getId(),
  3123.                     'name' => $userGroup->getGroupName("en") ?: $userGroup->getGroupName("ar") ?: '',
  3124.                     'user_phones' => $userPhones
  3125.                 ];
  3126.             }
  3127.             
  3128.             // Also fetch UserSMSGroup objects
  3129.             $userSMSGroupList = new DataObject\UserSMSGroup\Listing();
  3130.             $userSMSGroupList->setOrderKey("oo_id");
  3131.             $userSMSGroupList->setOrder("desc");
  3132.             
  3133.             foreach ($userSMSGroupList as $userSMSGroup) {
  3134.                 // Extract phone numbers from groupData JSON
  3135.                 $groupData $userSMSGroup->getGroupData();
  3136.                 $userPhones = [];
  3137.                 
  3138.                 if (!empty($groupData)) {
  3139.                     try {
  3140.                         $userInfoArray json_decode($groupDatatrue);
  3141.                         if (is_array($userInfoArray)) {
  3142.                             foreach ($userInfoArray as $userInfo) {
  3143.                                 if (isset($userInfo['phoneNumber']) && !empty($userInfo['phoneNumber'])) {
  3144.                                     $phoneNumber $userInfo['phoneNumber'];
  3145.                                     // Ensure phone number is in +966XXXXXXXXX format
  3146.                                     if (!preg_match('/^\+966/'$phoneNumber)) {
  3147.                                         // Remove +966 or 966 prefix to get 9 digits
  3148.                                         $phoneDigits preg_replace('/^\+966/'''$phoneNumber);
  3149.                                         $phoneDigits preg_replace('/^966/'''$phoneDigits);
  3150.                                         $phoneDigits preg_replace('/[^0-9]/'''$phoneDigits);
  3151.                                         if (strlen($phoneDigits) === 9) {
  3152.                                             $phoneNumber '+966' $phoneDigits;
  3153.                                         }
  3154.                                     }
  3155.                                     $userPhones[] = $phoneNumber;
  3156.                                 }
  3157.                             }
  3158.                         }
  3159.                     } catch (\Exception $ex) {
  3160.                         // Skip invalid JSON
  3161.                         continue;
  3162.                     }
  3163.                 }
  3164.                 
  3165.                 // Merge with existing UserGroup if same name, otherwise add as new entry
  3166.                 $groupName $userSMSGroup->getGroupName("en") ?: $userSMSGroup->getGroupName("ar") ?: '';
  3167.                 $merged false;
  3168.                 
  3169.                 foreach ($userGroupListData as &$existingGroup) {
  3170.                     if ($existingGroup['name'] === $groupName) {
  3171.                         // Merge phone numbers (remove duplicates)
  3172.                         $existingGroup['user_phones'] = array_values(array_unique(array_merge($existingGroup['user_phones'], $userPhones)));
  3173.                         $merged true;
  3174.                         break;
  3175.                     }
  3176.                 }
  3177.                 
  3178.                 if (!$merged && !empty($userPhones)) {
  3179.                     // Add as new entry if not merged
  3180.                     $userGroupListData[] = [
  3181.                         'groupid' => $userSMSGroup->getId(),
  3182.                         'name' => $groupName,
  3183.                         'user_phones' => $userPhones
  3184.                     ];
  3185.                 }
  3186.             }
  3187.             if (!empty($userGroupListData)) {
  3188.                 return ["success" => true"data" => $userGroupListData];
  3189.             }
  3190.             return ["success" => false"message" => $translator->trans("user_groups_are_not_available")];
  3191.         } catch (\Exception $ex) {
  3192.             throw new \Exception($ex->getMessage());
  3193.         }
  3194.     }
  3195.     /**
  3196.      * Create or update user group with simplified parameters
  3197.      * Only assigns users that have mobile numbers (like listC2Users logic)
  3198.      */
  3199.     public function createUpdateUserGroupSimple($user$groupName$userIds$groupId null$translator): array
  3200.     {
  3201.         try {
  3202.             $organization $user->getOrganization();
  3203.             if (!$organization instanceof DataObject\Organization) {
  3204.                 return ["success" => false"message" => $translator->trans("user_does_not_belongs_to_organization")];
  3205.             }
  3206.             // Get class IDs for table names
  3207.             $class = new \Pimcore\Model\DataObject\ClassDefinition();
  3208.             $customerClassId $class->getDao()->getIdByName('Customer');
  3209.             $subscriptionClassId $class->getDao()->getIdByName('Subscription');
  3210.             $db Db::get();
  3211.             // Validate and filter user_ids - only include users with mobile numbers
  3212.             $validUserIds = [];
  3213.             if (!empty($userIds)) {
  3214.                 $select $db->createQueryBuilder();
  3215.                 $select->select(['customer.oo_id AS customer_id']);
  3216.                 $select->from('object_' $customerClassId'customer');
  3217.                 
  3218.                 // Join with subscription to filter active subscriptions
  3219.                 $select->innerJoin(
  3220.                     'customer',
  3221.                     'object_' $subscriptionClassId,
  3222.                     'subscription',
  3223.                     'customer.oo_id = subscription.subscribedUser__id'
  3224.                 );
  3225.                 // Filter by provided user IDs
  3226.                 $select->where("customer.oo_id IN (:userIds)");
  3227.                 $select->setParameter('userIds'$userIds\Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
  3228.                 // Apply mobile number filter (same as listC2Users)
  3229.                 $select->andWhere("customer.phoneNo IS NOT NULL AND customer.phoneNo != '' AND CHAR_LENGTH(customer.phoneNo) = 9");
  3230.                 
  3231.                 // Customer must be published
  3232.                 $select->andWhere("customer.o_published = 1");
  3233.                 
  3234.                 // Only active subscriptions
  3235.                 $select->andWhere("subscription.isActive = 1");
  3236.                 
  3237.                 // Only 'custom' subscription type
  3238.                 $select->andWhere("subscription.subscriptionType = " $db->quote('custom'));
  3239.                 
  3240.                 // Only subscriptions with end date in future (or no expiry)
  3241.                 $currentTimestamp time();
  3242.                 $select->andWhere("(subscription.endDate IS NULL OR subscription.endDate >= " $currentTimestamp ")");
  3243.                 $results $select->execute()->fetchAllAssociative();
  3244.                 
  3245.                 foreach ($results as $row) {
  3246.                     $validUserIds[] = (int) $row['customer_id'];
  3247.                 }
  3248.             }
  3249.             if (empty($validUserIds)) {
  3250.                 return ["success" => false"message" => $translator->trans("no_valid_users_with_mobile_numbers_found")];
  3251.             }
  3252.             // Validate group name uniqueness when creating new group
  3253.             if (!$groupId) {
  3254.                 // Check if group name already exists in the same organization
  3255.                 $existingGroupList = new DataObject\UserGroup\Listing();
  3256.                 $existingGroupList->filterByOrganization($organization);
  3257.                 $existingGroupList->setLocale('en');
  3258.                 
  3259.                 foreach ($existingGroupList as $existingGroup) {
  3260.                     if ($existingGroup instanceof DataObject\UserGroup) {
  3261.                         $existingGroupNameEn $existingGroup->getGroupName('en');
  3262.                         $existingGroupNameAr $existingGroup->getGroupName('ar');
  3263.                         
  3264.                         // Check if group name matches (case-insensitive)
  3265.                         if (strcasecmp(trim($existingGroupNameEn), trim($groupName)) === || 
  3266.                             strcasecmp(trim($existingGroupNameAr), trim($groupName)) === 0) {
  3267.                             return ["success" => false"message" => $translator->trans("group_name_already_exists")];
  3268.                         }
  3269.                     }
  3270.                 }
  3271.             }
  3272.             // Create or update user group
  3273.             if ($groupId) {
  3274.                 // Update existing group
  3275.                 $userGroup DataObject\UserGroup::getById($groupIdtrue);
  3276.                 
  3277.                 
  3278.                 if (!$userGroup instanceof DataObject\UserGroup) {
  3279.                     return ["success" => false"message" => $translator->trans("user_group_is_not_available")];
  3280.                 }
  3281.                 // Verify organization
  3282.                 if (!$userGroup->getOrganization() || $userGroup->getOrganization()->getId() != $organization->getId()) {
  3283.                     return ["success" => false"message" => $translator->trans("user_group_is_not_assigned_to_your_organization")];
  3284.                 }
  3285.                 // Update group name
  3286.                 $userGroup->setGroupName($groupName"en");
  3287.                 $userGroup->setGroupName($groupName"ar");
  3288.             } else {
  3289.                 // Create new group
  3290.                 $userGroup = new DataObject\UserGroup();
  3291.                 $userGroup->setParent(DataObject\Service::createFolderByPath('/UserManagement/UserGroups/' $organization->getName()));
  3292.             $userGroup->setKey(trim(strip_tags($groupName.'-'.uniqid())));
  3293.             $userGroup->setGroupName($groupName'en');
  3294.             $userGroup->setGroupName($groupName'ar');
  3295.             $userGroup->setDetail($groupName'en');
  3296.             $userGroup->setDetail($groupName'ar');
  3297.             $userGroup->setOrganization($organization);
  3298.             $userGroup->setPublished(true);
  3299.                 // dump($userGroup);
  3300.                 // die;
  3301.                 // $userGroup->setGroupName($groupName, "en");
  3302.                 // $userGroup->setGroupName($groupName, "ar");
  3303.                 // $userGroup->setOrganization($organization);
  3304.                 $userGroup->setIsActive(true);
  3305.             }
  3306.             $userGroup->save();
  3307.             
  3308.             // Reload the group to ensure it has all necessary data
  3309.             $userGroup DataObject\UserGroup::getById($userGroup->getId(), true);
  3310.             // Assign users to group
  3311.             foreach ($validUserIds as $userId) {
  3312.                 $customer DataObject\Customer::getById($userIdtrue);
  3313.                 
  3314.                 if ($customer instanceof DataObject\Customer) {
  3315.                     // Get existing user groups for this customer
  3316.                     $existingGroups = [];
  3317.                     
  3318.                     // Collect existing groups and their IDs
  3319.                     $currentGroups $customer->getUserGroup();
  3320.                     if ($currentGroups) {
  3321.                         foreach ($currentGroups as $group) {
  3322.                             if ($group instanceof DataObject\UserGroup) {
  3323.                                 $groupId $group->getId();
  3324.                                 // Skip if this is the same group we're adding
  3325.                                 if ($groupId != $userGroup->getId()) {
  3326.                                     $existingGroups[] = $group;
  3327.                                 }
  3328.                             }
  3329.                         }
  3330.                     }
  3331.                     
  3332.                     // Add the new/updated group
  3333.                     $existingGroups[] = $userGroup;
  3334.                     
  3335.                     // Update customer's user groups
  3336.                     $customer->setUserGroup($existingGroups);
  3337.                     $customer->save();
  3338.                 }
  3339.             }
  3340.             // Remove users from group if they're not in the valid list
  3341.             // Get all users currently in this group
  3342.             $allUsersInGroup = new DataObject\Customer\Listing();
  3343.             $allUsersInGroup->filterByUserGroup($userGroup);
  3344.             
  3345.             foreach ($allUsersInGroup as $customer) {
  3346.                 if (!in_array($customer->getId(), $validUserIds)) {
  3347.                     // Get existing groups and remove this one
  3348.                     $existingGroups = [];
  3349.                     $currentGroups $customer->getUserGroup();
  3350.                     
  3351.                     if ($currentGroups) {
  3352.                         foreach ($currentGroups as $group) {
  3353.                             if ($group instanceof DataObject\UserGroup) {
  3354.                                 // Only keep groups that are NOT the one we're removing
  3355.                                 if ($group->getId() != $userGroup->getId()) {
  3356.                                     $existingGroups[] = $group;
  3357.                                 }
  3358.                             }
  3359.                         }
  3360.                     }
  3361.                     
  3362.                     $customer->setUserGroup($existingGroups);
  3363.                     $customer->save();
  3364.                 }
  3365.             }
  3366.             $action $groupId "updated" "created";
  3367.             return [
  3368.                 "success" => true
  3369.                 "message" => $translator->trans("user_group_{$action}_successfully"),
  3370.                 "data" => [
  3371.                     "groupid" => $userGroup->getId(),
  3372.                     "name" => $groupName,
  3373.                     "user_ids" => $validUserIds
  3374.                 ]
  3375.             ];
  3376.         } catch (\Exception $ex) {
  3377.             throw new \Exception($ex->getMessage());
  3378.         }
  3379.     }
  3380.     /**
  3381.      * Internal user dual mode
  3382.      * @param array $params
  3383.      * @param Translator $translator
  3384.      * @return array
  3385.      */
  3386.     public function internalUserDualMode($params$translator): array
  3387.     {
  3388.         try {
  3389.             $user DataObject\Customer::getById($params['id'], true);
  3390.             // check if user is internal user
  3391.             if (!$user) {
  3392.                 return ["success" => false"message" => $translator->trans("user_does_not_exists")];
  3393.             }
  3394.             // get internal organization
  3395.             $organization = new DataObject\Organization\Listing();
  3396.             $organization->filterByIsInternal(true);
  3397.             $entity $organization->current();
  3398.             if(!$entity) {
  3399.                 return ["success" => false"message" => $translator->trans("internal_organization_does_not_exists")];
  3400.             }
  3401.             $package $entity->getPackage();
  3402.             if (!$package) {
  3403.                 return ["success" => false"message" => $translator->trans("package_does_not_exists")];
  3404.             }
  3405.             if ($params['mode'] == true) {
  3406.                 $user->setDualMode(true);
  3407.                 $user->save();
  3408.                
  3409.                 // get existing subscription
  3410.                 $subscriptions = new DataObject\Subscription\Listing();
  3411.                 $subscriptions->filterBySubscribedUser($user);
  3412.                 $subscriptions->filterBySubscriptionType('custom');
  3413.                 $subscriptions->filterBySubscribedPackage($package);
  3414.                 $subscription $subscriptions->current();
  3415.                 if ($subscription) {
  3416.                     $subscription->setIsNoExpiry(true);
  3417.                     $subscription->setIsActive(true);
  3418.                     $subscription->setSubscriptionType('custom');
  3419.                     $subscription->setPublished(true);
  3420.                     $subscription->setSubscribedPackage($package);
  3421.                     $subscription->setSubscribedUser($user);
  3422.                     $subscription->save();
  3423.                 } else {
  3424.                     // create new subscription
  3425.                     $subscription = new DataObject\Subscription();
  3426.                     $subscription->setParent(DataObject\Service::createFolderByPath('/UserManagement/Subscriptions/' $user->getEmail()));
  3427.                     $subscription->setKey(\Pimcore\Model\Element\Service::getValidKey($package->getId() . time() . rand(100010000), 'object'));
  3428.                     $subscription->setSubscribedPackage($package);
  3429.                     $subscription->setSubscribedUser($user);
  3430.                     $subscription->setSubscriptionType('custom');
  3431.                     $subscription->setIsNoExpiry(true);
  3432.                     $subscription->setIsActive(true);
  3433.                     $subscription->setPublished(true);
  3434.                     $subscription->save();
  3435.                 }
  3436.               
  3437.             } else {
  3438.                 // disable dual mode
  3439.                 $user->setDualMode(false);
  3440.                 $user->save();
  3441.                 // get existing subscription
  3442.                 $subscriptions = new DataObject\Subscription\Listing();
  3443.                 $subscriptions->filterBySubscribedUser($user);
  3444.                 $subscriptions->filterBySubscribedPackage($package);
  3445.                 $subscriptions->filterBySubscriptionType('custom');
  3446.                 $subscription $subscriptions->current();
  3447.                 // delete subscription
  3448.                 if ($subscription) {
  3449.                     $subscription->delete();
  3450.                 }
  3451.             }
  3452.             return ["success" => true"message" => $translator->trans("internal_user_dual_mode_updated_successfully")];
  3453.         } catch (\Exception $ex) {
  3454.             throw new \Exception($ex->getMessage());
  3455.         }
  3456.     }
  3457. }