<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Usertype;
use App\Utils;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

final class UsertypeService
{
    public function paginateList(
        ?string $sortOrder,
        ?string $subject1,
        ?string $subject2,
        ?string $subject3,
        string $sort,
        string $sortType
    ): LengthAwarePaginator {
        $query = Usertype::query();

        if ($sortOrder !== null && $sortOrder !== '') {
            // sort_order は数値想定だが、まずは部分一致せず完全一致で
            $query->where('sort_order', $sortOrder);
        }

        if ($subject1 !== null && $subject1 !== '') {
            $query->where('usertype_subject1', 'like', '%' . $subject1 . '%');
        }

        if ($subject2 !== null && $subject2 !== '') {
            $query->where('usertype_subject2', 'like', '%' . $subject2 . '%');
        }

        if ($subject3 !== null && $subject3 !== '') {
            $query->where('usertype_subject3', 'like', '%' . $subject3 . '%');
        }

        $query->orderBy($sort, $sortType);

        return $query->paginate(Utils::item_per_page);
    }

    public function create(array $validated): Usertype
    {
        return Usertype::create($this->payload($validated));
    }

    public function update(Usertype $usertype, array $validated): Usertype
    {
        $usertype->fill($this->payload($validated));
        $usertype->save();

        return $usertype;
    }

    private function payload(array $validated): array
    {
        return [
            'sort_order'        => $validated['sort_order'],
            'usertype_subject1' => $validated['usertype_subject1'],
            'usertype_subject2' => $validated['usertype_subject2'],
            'usertype_subject3' => $validated['usertype_subject3'] ?? null,
            'print_name'        => $validated['print_name'] ?? null,
            'usertype_money'    => $validated['usertype_money'] ?? null,
            'usertype_remarks'  => $validated['usertype_remarks'] ?? null,
        ];
    }
}
