<?php

namespace App\Services;

use App\Models\Entities\V2chgstatModel;
use App\Models\Entities\V2chghistoryModel;

class StatusService
{
    protected $V2chgstatModel, $V2chghistoryModel;

    public function __construct()
    {
        // $this->V2chgstatModel = model(V2chgstatModel::class);
        // $this->V2chghistoryModel = model(V2chghistoryModel::class);
    }

    /**
     * 상태 변경 및 이력 기록 공통 메서드
     */
    public function recordStatusAndHistory($vr_sq, $stat_cd, $chg_type, $memo)
    {
        $statModel = model(V2chgstatModel::class);
        $histModel = model(V2chghistoryModel::class);
        // 1. 상태(stat) 저장 (Insert or Update)
        try {
            $statModel->saveChgstat([
                'vr_sq'       => $vr_sq,
                'stat_cd'     => $stat_cd,
                'insert_user' => '0',
                'insert_tm'   => db_now()
            ], 'I');
        } catch (\Exception $e) {
            $lastSql = (string)$statModel->getLastQuery();
            write_custom_log("STAT_SAVE_ERR | vr_sq: $vr_sq | SQL: $lastSql | Msg: " . $e->getMessage(), 'ERROR', 'failed');
        }

        // 2. 이력(history) 저장
        try {
            $histModel->v2_savehistory([
                'vr_sq'     => $vr_sq,
                'stat_cd'   => $stat_cd,
                'chg_type'  => $chg_type,
                'memo'      => $memo,
                'insert_id' => 'SYSTEM',
                'insert_tm' => db_now()
            ]);
        } catch (\Exception $e) {
            $lastSql = (string)$histModel->getLastQuery();
            write_custom_log("HIST_SAVE_ERR | vr_sq: $vr_sq | SQL: $lastSql | Msg: " . $e->getMessage(), 'ERROR', 'failed');
        }
    }
}