<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Model\Magento;

use Magento\User\Model\ResourceModel\User\CollectionFactory as UserCollectionFactory;
use WriteTextAI\WriteTextAI\Setup\Patch\Data\UserRoles;

class User
{
    /**
     * @var UserCollectionFactory
     */
    protected $userCollectionFactory;

    /**
     * Constructor
     *
     * @param UserCollectionFactory $userCollectionFactory
     */
    public function __construct(
        UserCollectionFactory $userCollectionFactory
    ) {
        $this->userCollectionFactory = $userCollectionFactory;
    }

    /**
     * Get admin users
     *
     * @return array
     */
    public function getUsers()
    {
        $collection = $this->userCollectionFactory->create()
            ->addFieldToSelect([
                'firstname',
                'lastname',
                'email',
            ]);

        $users = [];
        foreach ($collection as $user) {
            $users[] = [
                'id' => $user->getUserId(),
                'firstname' => $user->getFirstname(),
                'lastname' => $user->getLastname(),
                'name' => $user->getFirstname() . ' ' . $user->getLastname(),
                'email' => $user->getEmail()
            ];
        }

        return $users;
    }
    
    /**
     * Get users for notification for keyword optimization
     *
     * @return array
     */
    public function getUsersForNotification()
    {
        try {
            $roles = [
                'Administrators',
                UserRoles::ADMIN_ROLE,
                UserRoles::EDITOR_ROLE,
                UserRoles::CONTRIBUTOR_ROLE
            ];
            $collection = $this->userCollectionFactory->create();
            $collection->addFieldToSelect([
                'user_id',
                'firstname',
                'lastname',
                'email'
            ]);
            $collection->getSelect()
                ->where('detail_role.role_name IN (?)', $roles);

            $users = [];
            foreach ($collection as $user) {
                $users[] = [
                    'id' => $user->getUserId(),
                    'firstname' => $user->getFirstname(),
                    'lastname' => $user->getLastname(),
                    'name' => $user->getFirstname() . ' ' . $user->getLastname(),
                    'email' => $user->getEmail()
                ];
            }
        } catch (\Exception $e) {
            $users = $this->getUsers();
        }

        return $users;
    }
}
