<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\DTO\SearchData;

class UserGrade extends Model
{
    protected $table = 'tb_user_grade';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $guarded = [];

    public function user()
    {
        return $this->hasMany(User::class);
    }

    /**
     * 회원등급 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select('tb_user_grade.*');
        $query->orderBy('sort');
        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count();
        $rows = $list->count();

        return (object)[
            'total' => $total,
            'rows' => $rows,
            'list' => $list
        ];
    }

    /**
     * 전체 사용 회원등급 조회
     */
    public function getAllGrade()
    {
        return $this->where('is_use', 1)->orderBy('sort', 'ASC')->get();
    }

    /**
     * 회원등급 조회하여 배열로 반환
     */
    public function findUserGrade(int $userGradeID)
    {
        return $this->where('id', $userGradeID)->where('is_use', 1)->orderBy('sort', 'ASC')->get();
    }

    /**
     * 회원 등급 정보 조회
     */
    public function findByUserID(?int $userID)
    {
        $sql = "
            SELECT
                UGD.*
            FROM tb_user_grade UGD
            JOIN users USR ON UGD.id = USR.user_grade_id
            WHERE USR.id = ? AND UGD.is_use = 1 LIMIT 1;
        ";

        return DB::selectOne($sql, [$userID]);
    }
}
