<?php

namespace App\Services\Reimbursements;

use Illuminate\Support\Facades\DB;

class ReimbursementRecipientService
{
    public const SPECIAL_RECIPIENTS = [
        990001 => 'Masjid',
        990002 => 'Donation',
    ];

    public function staffUsers(): array
    {
        $rows = DB::table('users')
            ->select('users.id', 'users.firstname', 'users.lastname', 'roles.name as role_name')
            ->leftJoin('user_roles', 'user_roles.user_id', '=', 'users.id')
            ->leftJoin('roles', 'roles.id', '=', 'user_roles.role_id')
            ->whereNotNull('roles.name')
            ->get();

        $excludedRoles = array_map('strtolower', ['parent', 'student', 'guest']);
        $staff = [];

        foreach ($rows as $row) {
            $roleName = strtolower((string) ($row->role_name ?? ''));
            $id = (int) ($row->id ?? 0);
            if ($id <= 0 || in_array($roleName, $excludedRoles, true)) {
                continue;
            }
            if (!isset($staff[$id])) {
                $staff[$id] = [
                    'id' => $id,
                    'firstname' => $row->firstname ?? '',
                    'lastname' => $row->lastname ?? '',
                ];
            }
        }

        uasort($staff, static function (array $a, array $b) {
            $nameA = trim(($a['firstname'] ?? '') . ' ' . ($a['lastname'] ?? ''));
            $nameB = trim(($b['firstname'] ?? '') . ' ' . ($b['lastname'] ?? ''));
            return strcasecmp($nameA, $nameB);
        });

        return array_values($staff);
    }

    public function recipientOptions(): array
    {
        return $this->appendSpecialRecipients($this->staffUsers());
    }

    public function adminRoster(): array
    {
        $admins = $this->staffUsers();
        if (!empty($admins)) {
            return $admins;
        }

        return $this->recipientOptions();
    }

    public function specialRecipientLabel($value): ?string
    {
        if ($value === null || !is_numeric($value)) {
            return null;
        }

        $id = (int) $value;
        return self::SPECIAL_RECIPIENTS[$id] ?? null;
    }

    private function appendSpecialRecipients(array $users): array
    {
        $existingIds = array_map(static function ($row) {
            return isset($row['id']) && is_numeric($row['id']) ? (int) $row['id'] : null;
        }, $users);

        foreach (self::SPECIAL_RECIPIENTS as $id => $label) {
            if (!in_array($id, $existingIds, true)) {
                $users[] = [
                    'id' => $id,
                    'firstname' => $label,
                    'lastname' => '',
                ];
            }
        }

        return $users;
    }
}
