<?php

namespace HelpGent\App\Repositories;

defined( "ABSPATH" ) || exit;

use stdClass;

use HelpGent\App\Models\User;
use HelpGent\App\Models\UserMeta;

class AgentRepository {
    public function get(): array {
        global $wpdb;

        $usermeta_table = UserMeta::get_table_name();

        $users = User::query( 'user' )
            ->select( [ 'user.ID as id', 'user.display_name as name', 'user.user_email as email' ] )
            ->join( $usermeta_table, 'user.id', '=', "{$usermeta_table}.user_id" )
            ->where( "{$usermeta_table}.meta_key", "{$wpdb->prefix}capabilities" )
            ->where(
                function( $builder ) use( $usermeta_table ) {
                    $builder
                    ->where_like( "{$usermeta_table}.meta_value", '%helpgent_agent%' )
                    ->or_where_like( "{$usermeta_table}.meta_value", '%administrator%' );
                } 
            )
            ->group_by( 'user.id' )
            ->get();

        return array_map( [ $this, 'format_data_item' ], $users );
    }

    public function format_data_item( stdClass $item ): stdClass {
        $item->avatar = get_avatar_url( $item->id );

        return $item;
    }
}