<?php

namespace App\Services\Master;

use App\Models\Supplier;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;

class SupplierService
{
    public function paginateForIndex(array $tableQuery): LengthAwarePaginator
    {
        $query = Supplier::query()
            ->when($tableQuery['search'] !== '', function (Builder $query) use ($tableQuery): void {
                $search = $tableQuery['search'];
                $query->where(function (Builder $query) use ($search): void {
                    $query->where('name', 'like', "%{$search}%")
                        ->orWhere('phone_number', 'like', "%{$search}%")
                        ->orWhere('address', 'like', "%{$search}%");
                });
            });

        $this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);

        return $query
            ->paginate(25)
            ->withQueryString();
    }

    public function create(array $validated): void
    {
        Supplier::create($validated);
    }

    public function update(Supplier $supplier, array $validated): void
    {
        $supplier->update($validated);
    }

    public function delete(Supplier $supplier): void
    {
        $supplier->delete();
    }

    public function getSelectOptions(): array
    {
        return Supplier::query()
            ->orderBy('name')
            ->get(['id', 'name'])
            ->map(fn (Supplier $supplier) => [
                'value' => $supplier->id,
                'label' => $supplier->name,
            ])
            ->all();
    }

    private function applySorting(Builder $query, string $sort, string $direction): void
    {
        if (in_array($sort, ['name', 'phone_number', 'address'], true)) {
            $query->orderBy($sort, $direction);

            return;
        }

        $query->latest();
    }
}
