<?php

namespace App\Models;

use App\Utils;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Usertype extends Model
{
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    const PERPAGE = 50;

    protected $table = 'usertype';
    protected $primaryKey = 'user_categoryid';

    protected $fillable = [
        'sort_order',
        'usertype_subject1',
        'usertype_subject2',
        'usertype_subject3',
        'print_name',
        'usertype_money',
        'usertype_remarks',
        'operator_id',
    ];

    public static function boot()
    {
        parent::boot();
        self::creating(function (Usertype $model) {
            $model->operator_id = Auth::user()->ope_id;
        });
    }

    public static function search(array $inputs)
    {
        $query = self::query();
        $table = (new self())->getTable();

        if (!empty($inputs['filter_sort_order'])) {
            $query->where('sort_order', $inputs['filter_sort_order']);
        }
        if (!empty($inputs['filter_usertype_subject1'])) {
            $query->where('usertype_subject1', 'like', '%' . $inputs['filter_usertype_subject1'] . '%');
        }
        if (!empty($inputs['filter_usertype_subject2'])) {
            $query->where('usertype_subject2', 'like', '%' . $inputs['filter_usertype_subject2'] . '%');
        }
        if (!empty($inputs['filter_usertype_subject3'])) {
            $query->where('usertype_subject3', 'like', '%' . $inputs['filter_usertype_subject3'] . '%');
        }

        $sortable = [
            'user_categoryid'     => "{$table}.user_categoryid",
            'sort_order'          => "{$table}.sort_order",
            'usertype_subject1'   => "{$table}.usertype_subject1",
            'usertype_subject2'   => "{$table}.usertype_subject2",
            'usertype_subject3'   => "{$table}.usertype_subject3",
            'print_name'          => "{$table}.print_name",
            'usertype_remarks'    => "{$table}.usertype_remarks",
        ];

        $sortKey = $inputs['sort'] ?? 'user_categoryid';
        $sortColumn = $sortable[$sortKey] ?? "{$table}.user_categoryid";

        $direction = strtolower($inputs['sort_type'] ?? 'asc');
        if (!in_array($direction, ['asc', 'desc'], true)) {
            $direction = 'asc';
        }

        $query->orderBy($sortColumn, $direction);

        return !empty($inputs['isExport'])
            ? $query->get()
            : $query->paginate(Utils::item_per_page);
    }

    public static function getByPk($pk)
    {
        return self::find($pk);
    }
    
    public static function deleteByPk($arr)
    {
        return self::whereIn('user_categoryid', $arr)->delete();
    }
    
    //TODO 利用者分類ID not found in database specs

   //TODO 利用者分類名 not found in database specs
    public static function getList(){
        return self::pluck('print_name','user_categoryid');
    }

}