<?php

namespace App\Models;

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

class UserDormantNotify extends Model
{
    protected $table = 'tb_user_dormant_notify';
    protected $primaryKey = 'id';

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

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

    protected $guarded = [];

    protected $dates = [
        'register_at',
        'last_login_at',
        'dormant_at',
        'notify_at'
    ];

    /**
     * 알림 발송 내역 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select('tb_user_dormant_notify.*');

        if ($params->keyword) {
            switch ($params->field) {
                case 'tb_user_dormant_notify.id':
                case 'tb_user_dormant_notify.user_id':
                case 'tb_user_dormant_notify.sid':
                    $query->where($params->field, '=', $params->keyword);
                    break;
                case 'tb_user_dormant_notify.name':
                case 'tb_user_dormant_notify.nickname':
                case 'tb_user_dormant_notify.email':
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'tb_user_dormant_notify.last_login_at': // 마지막 로그인 일시
                case 'tb_user_dormant_notify.dormant_at': // 휴면예정 일시
                case 'tb_user_dormant_notify.created_at': // 알림 발송일시
                    $query->whereDate($params->field, $params->keyword);
                    break;
            }
        }

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

        $query->orderByDesc('tb_user_dormant_notify.id');

        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count(); // 전체 수
        $rows = $list->count(); // 검색 수

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

    /**
     * 휴면(예정) 알림 발송
     */
    public function register(User $user): bool
    {
        // 이메일 전송
        (new EmailLib)->send(SEND_MAIL_FORM_TYPE_11, $user);

        // 전송 내역 기록
        return $this->insert([
            'user_id' => $user->id,
            'sid' => $user->sid,
            'email' => $user->email,
            'name' => $user->name,
            'nickname' => $user->nickname,
            'last_login_at' => $user->last_login_at,
            'dormant_at' => $user->last_login_at->addYear(1),
            'created_at' => now()
        ]);
    }
}
