<?php

namespace App\Services;

use App\Models\rate;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class RateService
{
    public function getRateData(
        int $page,
        int $length,
        ?string $searchValue = null,
        ?string $status = null
    ): LengthAwarePaginator {
        $query = rate::query()
            ->select([
                'id',
                'usd_rate',
                'is_active',
                'created_at',
            ])
            ->orderByDesc('id');

        if (! empty($searchValue)) {
            $normalizedSearch = strtolower(trim($searchValue));

            $query->where(function ($subQuery) use ($searchValue): void {
                $subQuery->where('usd_rate', 'like', "%{$searchValue}%");
            });

            if (in_array($normalizedSearch, ['activa', 'activo', 'activas', 'activos'], true)) {
                $query->where('is_active', 1);
            }

            if (in_array($normalizedSearch, ['inactiva', 'inactivo', 'inactivas', 'inactivos'], true)) {
                $query->where('is_active', 0);
            }
        }

        if ($status !== null && $status !== '') {
            $query->where('is_active', (int) ((string) $status === '1'));
        }

        $paginator = $query->paginate($length, ['*'], 'page', $page);

        $paginator->getCollection()->transform(function (rate $rateItem): array {
            return [
                'id' => $rateItem->id,
                'usd_rate' => number_format((float) $rateItem->usd_rate, 4, ',', '.'),
                'is_active' => (int) $rateItem->is_active,
                'created_at_formatted' => $rateItem->created_at?->format('d/m/Y H:i'),
            ];
        });

        return $paginator;
    }

    public function getActiveRate()
    {
        return rate::where('is_active', 1)->latest()->first();
    }
}
