<?php

namespace Modules\User\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Modules\User\Entities\Bank;
use Modules\User\Repositories\Contracts\BankRepositoryInterface;

class BankRepository implements BankRepositoryInterface
{
    protected function baseQuery()
    {
        return Bank::query()->orderBy('name');
    }

    public function getAllPaginated(int $perPage = 10, string $search = '')
    {
        $query = $this->baseQuery();

        return $query->paginate($perPage);
    }

    public function getAllWithRelationsPaginated(
        int $perPage = 10,
        string $search = '',
        string $sortBy = 'name',
        string $sortOrder = 'asc'
    ) {
        $allowedSortColumns = [
            'name',
            'code',
            'swift_code',
            'is_active',
            'created_at',
        ];
        $sortBy = in_array($sortBy, $allowedSortColumns, true) ? $sortBy : 'name';
        $sortOrder = strtolower($sortOrder) === 'desc' ? 'desc' : 'asc';

        $query = Bank::query()->orderBy($sortBy, $sortOrder);

        return $query->paginate($perPage);
    }

    public function getAllWithRelations(string $search = ''): Collection
    {
        $query = Bank::query()->orderBy('name');

        return $query->get();
    }

    public function create(array $data): Bank
    {
        return Bank::create($data);
    }

    public function findById(string $id): ?Bank
    {
        return Bank::query()
            ->find($id);
    }

    // public function delete(string $id): bool
    // {
    //     $bank = $this->findById($id);
    //     if ($bank) {
    //         return $bank->delete();
    //     }

    //     return false;
    // }

    public function all(string $search = ''): Collection
    {
        return $this->baseQuery()->get();
    }

    public function active(): Collection
    {
        return Bank::query()->where('is_active', true)->get();
    }
}
