<?php

namespace App\Services\ExtraCharges;

use Illuminate\Support\Facades\DB;

class ExtraChargesParentService
{
    public function searchParents(string $q = '', int $limit = 20): array
    {
        $builder = DB::table('users')
            ->select('users.id', 'users.firstname', 'users.lastname', 'users.email')
            ->join('user_roles', 'user_roles.user_id', '=', 'users.id')
            ->join('roles', 'roles.id', '=', 'user_roles.role_id')
            ->where('roles.name', 'parent')
            ->whereNull('user_roles.deleted_at');

        if ($q !== '') {
            $builder->where(function ($query) use ($q) {
                $query->where('users.firstname', 'like', "%{$q}%")
                    ->orWhere('users.lastname', 'like', "%{$q}%")
                    ->orWhere('users.email', 'like', "%{$q}%");
            });
        }

        $rows = $builder
            ->orderBy('users.lastname', 'ASC')
            ->orderBy('users.firstname', 'ASC')
            ->limit($limit)
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        return array_map(function ($row) {
            $name = trim(($row['lastname'] ?? '') . ', ' . ($row['firstname'] ?? ''));
            $email = $row['email'] ?? '';
            $label = $name !== ',' ? $name : ('User #' . $row['id']);
            if ($email) {
                $label .= ' — ' . $email;
            }
            $label .= ' (ID: ' . $row['id'] . ')';
            return [
                'id' => (int) $row['id'],
                'text' => $label,
            ];
        }, $rows);
    }
}
