<?php

namespace App\Services\Admin\Master;

use App\Models\Supplier;
use App\Services\Concerns\LogsFormHistory;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class SupplierService
{
    use LogsFormHistory;

    public function paginated(int $perPage = 25, string $search = '', string $sort = 'created_at', string $direction = 'desc', array $filters = []): LengthAwarePaginator
    {
        return Supplier::query()
            ->select(['id', 'name', 'phone_number', 'address'])
            ->when($search, fn ($q) => $q->where('name', 'like', "%{$search}%"))
            ->orderBy($sort, $direction)
            ->paginate($perPage);
    }

    public function getAll(): Collection
    {
        return Supplier::select(['id', 'name', 'phone_number', 'address'])->latest()->get();
    }

    public function store(array $data): Supplier
    {
        $supplier = Supplier::create($data);

        $this->logCreated($supplier, 'Supplier', [
            'Nama' => $supplier->name,
            'No. Telepon' => $supplier->phone_number,
            'Alamat' => $supplier->address,
        ]);

        return $supplier;
    }

    public function update(Supplier $supplier, array $data): Supplier
    {
        $oldValues = [
            'Nama' => $supplier->name,
            'No. Telepon' => $supplier->phone_number,
            'Alamat' => $supplier->address,
        ];

        $supplier->update($data);

        $this->logUpdated($supplier, 'Supplier', $oldValues, [
            'Nama' => $supplier->name,
            'No. Telepon' => $supplier->phone_number,
            'Alamat' => $supplier->address,
        ]);

        return $supplier;
    }

    public function destroy(Supplier $supplier): bool
    {
        $this->logDeleted($supplier, 'Supplier', [
            'Nama' => $supplier->name,
            'No. Telepon' => $supplier->phone_number,
            'Alamat' => $supplier->address,
        ]);

        return $supplier->delete();
    }
}
