<?php 

    trait User  {

        public function getLastComercialUser() {

            $sql = "
                SELECT US.id FROM users AS US
                LEFT JOIN roles AS RO ON US.role_id = RO.id
                WHERE LOWER(RO.name) = 'comercial'
                ORDER BY US.id ASC
            ";

            $stmt = parent::$conn->query($sql);
            $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $user_ids = array_map(function($user) {
                return $user['id'];
            }, $users);

            $sql = "
                SELECT count(*) AS total FROM companies AS C
                LEFT JOIN users AS U ON C.owner_id = U.id
                LEFT JOIN roles AS R ON R.id = U.role_id
                WHERE owner_id IS NOT NULL AND LOWER(R.name) = 'comercial'
            ";
            $stmt = parent::$conn->query($sql);
            $count_company = $stmt->fetch(PDO::FETCH_ASSOC);            
            $current_index = $count_company['total'] % sizeof($user_ids);
            $user_id = $user_ids[$current_index];

            return $user_id;

        }

    }