<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;

class UserGradeHistory extends Model
{
    protected $table = 'tb_member_grade_history';
    protected $primaryKey = 'mgh_key';

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

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

    /*
     * 회원등급 기록/변경 처리
     */
    public function register(int $memKey, int $toMgdKey, string $reason)
    {
        $MemberGradeMember = new MemberGradeMember();

        $member = $MemberGradeMember->findByMemKey($memKey);
        if(!$member) {
            return;
        }

        $fromMgdKey = intval($member->mgd_key);
        if($fromMgdKey === $toMgdKey) {
            return;
        }

        try{

            $sql = '
                INSERT INTO tb_member_grade_history(
                    mem_key, from_key, from_name, to_key, to_name, reason, ip_address, useragent, created_at
                ) VALUES (
                    ?,
                    ?,
                    (SELECT CONCAT(kor_name, \'(\', eng_name, \')\') FROM tb_member_grade WHERE mgd_key = ?),
                    ?,
                    (SELECT CONCAT(kor_name, \'(\', eng_name, \')\') FROM tb_member_grade WHERE mgd_key = ?),
                    ?,
                    ?,
                    ?,
                    NOW()
                );
            ';

            // 회원그룹 변경 기록
            DB::insert($sql, [
                $memKey,
                $fromMgdKey,
                $fromMgdKey,
                $toMgdKey,
                $toMgdKey,
                $reason,
                IP_ADDRESS,
                USER_AGENT,
            ]);

            // 회원그룹 변경 처리
            $MemberGradeMember->replace($memKey, $toMgdKey);

            DB::commit();
            return true;
        }catch(QueryException $e) {
            DB::rollBack();
            return false;
        }
    }
}
