<?php

namespace App\Services\Master;

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

class CustomerService
{
    public function paginateForIndex(array $tableQuery): LengthAwarePaginator
    {
        $query = Customer::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
    {
        Customer::create($validated);
    }

    public function createAndReturn(array $validated): Customer
    {
        return Customer::create($validated);
    }

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

    public function delete(Customer $customer): void
    {
        $customer->delete();
    }

    public function getSelectOptions(): array
    {
        return Customer::query()
            ->orderBy('name')
            ->get(['id', 'name'])
            ->map(fn (Customer $customer) => [
                'value' => $customer->id,
                'label' => $customer->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();
    }
}
