<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\DTO\SearchData;

class SmsUser extends Model
{
    protected $table = 'tb_sms_user';
    protected $primaryKey = 'id';

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

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;
    const DELETED_AT = null;

    protected $guarded = [];

    public function smsBook()
    {
        return $this->belongsTo(SmsBook::class);
    }

    /**
     * 주소록 회원 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_sms_user.*',
            'users.sid',
            'users.name',
            'users.nickname',
            'users.email',
            'users.phone'
        );

        if ($params->keyword) {
            switch ($params->field) {
                case 'tb_sms_user.id':
                case 'users.id':
                case 'users.sid':
                    $query->where($params->field, '=', $params->keyword);
                    break;
                case 'users.name':
                case 'users.nickname':
                case 'users.email':
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
            }
        }

        if ($params->userGroupID) {
            $query->whereIn('users.user_group_id', $params->userGroupID);
        }
        if ($params->userGradeID) {
            $query->whereIn('users.user_grade_id', $params->userGradeID);
        }
        if ($params->smsBookID) {
            $query->where('tb_sms_user.sms_book_id', $params->smsBookID);
        }

        $query->join('users', 'users.id', '=', 'tb_sms_user.user_id');
        $query->orderByDesc('tb_sms_user.id');

        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count();
        $rows = $list->count();

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