<?php

namespace App\Models;

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

class SmsBook extends Model
{
    protected $table = 'tb_sms_book';
    protected $primaryKey = 'id';

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

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

    protected $guarded = [];

    public function smsUser()
    {
        return $this->hasMany(SmsUser::class);
    }

    /**
     * 연락처 그룹 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_sms_book.*',
            DB::raw('(SELECT FORMAT(COUNT(*), 0) FROM tb_sms_user WHERE sms_book_id = tb_sms_book.id) AS userCount')
        );
        $query->orderByDesc('tb_sms_book.order');
        $query->orderByDesc('tb_sms_book.created_at');

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

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