<?php
namespace App\Models\common;

use CodeIgniter\Model;

class SmsModel extends Model
{

    // 문자발송
    public function sendSms($dest_phone, $dest_name, $send_phone, $send_name, $subject, $msg_body, $msg_type, $memo)
    {
        // 1) DB에서 NOW() 가져오고 싶으면 (기존 로직 유지)
        $sql = "SELECT DATE_FORMAT(NOW(), '%Y%m%d-%H%i%s') AS cmid, NOW() AS currDttm";
        $query = $$this->db->query($sql);
        $row = $query->getRowArray();

        $cmid = $row['cmid'] ?? null;
        $currDate = $row['currDttm'] ?? Time::now()->toDateTimeString(); // fallback

        // 2) 메시지 길이(EUC-KR) 체크
        $msg_length = strlen(iconv('UTF-8', 'EUC-KR//IGNORE', $msg_body));
        if ($msg_length > 80 && (int) $msg_type === 0) {
            $msg_type = 5; // LMS
        }

        // 3) etc2 분기
        $etc2 = ($memo === '로그인 인증') ? 'S13' : 'S12';

        // 4) insert 데이터
        $data = [
            // 'cmid'         => $cmid,   // 필요하면 활성화
            'dest_phone' => $dest_phone,
            'dest_name' => $dest_name,
            'send_phone' => $send_phone,
            'send_name' => $send_name,
            'subject' => $subject,
            'msg_body' => $msg_body,
            'msg_type' => $msg_type,
            'request_time' => $currDate,
            'send_time' => $currDate,
            'etc2' => $etc2,
            'etc3' => $memo,
        ];

        // 5) Query Builder insert
        $builder = $this->db->table('ums_data');
        $res = $builder->insert($data);

        // 6) 실행 쿼리 로그 (CI4)
        log_message('debug', '161616 ' . $this->db->getLastQuery());
    }
}