<?php

namespace App\Models;

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

class SmsResult extends Model
{
    protected $table = 'tb_sms_result';
    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 user()
    {
        return $this->belongsTo(User::class)->withDefault();
    }

    /**
     * 전송결과 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_sms_result.*',
            'users.sid',
            'users.name',
            'users.nickname',
            'users.email'
        );

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

        if($params->startDate || $params->endDate) {
            if($params->startDate) {
                $query->where('created_at', '>=', $params->startDate . ' 00:00:00');
            }
            if($params->endDate) {
                $query->where('created_at', '<=', $params->endDate . ' 23:59:59');
            }
        }

        $query->leftjoin('users', 'users.id', '=', 'tb_sms_result.user_id');
        $query->orderByDesc('tb_sms_result.id');

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

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