<?php

namespace App\Models;

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

class EmailLog extends Model
{
    protected $table = 'tb_email_log';
    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_email_log.*',
            'users.id',
            'users.sid',
            'users.name',
            'users.nickname',
            'users.email'
        );

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

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

        $query->leftJoin('users', 'users.id', '=', 'tb_email_log.user_id');
        $query->orderByDesc('tb_email_log.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(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);
        });
    }
}
