<?php

namespace App\Models;

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

class SmsHistory extends Model
{
    protected $table = 'tb_sms_history';
    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 data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_sms_history.*',
            'users.sid',
            'users.name',
            'users.nickname',
            'users.email'
        );

        if ($params->keyword) {
            switch ($params->field) {
                case 'tb_sms_history.id' :
                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_history.subject':
                case 'tb_sms_history.content':
                case 'tb_sms_history.tel':
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'users.created_at':
                case 'users.last_login_at':
                    $query->whereDate($params->field, $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_history.user_id');
        $query->orderByDesc('tb_sms_history.id');

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

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

    /**
     * 전송 내역 key 조회
     */
    public function setHistory(array $data): mixed
    {
        return DB::transaction(function () use ($data)
        {
            DB::table($this->table)->insert($data);
            $keys = DB::select('SELECT LAST_INSERT_ID() AS id');
            $sk = $keys[0]->id;
            $ek = ($sk + count($data) - 1);
            return range($sk, $ek);
        });
    }
}
