<?php
namespace App\Models\v2;

use App\Models\receipt\ReceiptModel;
use App\Models\webfax\FaxModel;
use CodeIgniter\Model;

class M703Model extends Model
{
    // 지역 목록 조회
    public function getAreaList($sido = '', $gugun = '')
    {

        if (!empty($gugun)) {
            $gugun = substr($gugun, '0', '5');

            $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
                " FROM region_codes a" .
                " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,5),'00000')" .
                " WHERE a.region_cd LIKE concat(?, '%')" .
                " AND a.region_cd NOT LIKE '%00000'" .
                " AND a.region_cd LIKE '%00'" .
                " AND a.use_yn = 'Y'" .
                " ORDER BY a.region_nm ASC";

            $query = $this->db->query($sql, [$gugun]);

        } else if (!empty($sido)) {
            $chk_sido = substr($sido, '0', '2');

            if ($chk_sido === '36') {
                $sido = substr($sido, '0', '4');
                $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm " .
                    "FROM region_codes a " .
                    "LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,4),'000000') " .
                    "WHERE a.region_cd LIKE concat(?, '%') " .
                    "AND a.region_cd NOT LIKE '%000000' " .
                    "AND a.region_cd LIKE '%00' " .
                    "AND a.use_yn = 'Y' " .
                    "AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000')) " .
                    "ORDER BY a.region_nm ASC";
            } else {
                $sido = substr($sido, '0', '2');
                $sql = "SELECT a.region_cd, TRIM(REPLACE(a.region_nm, b.region_nm, '')) region_nm" .
                    " FROM region_codes a" .
                    " LEFT JOIN region_codes b ON b.region_cd = CONCAT(SUBSTR(a.region_cd,1,2),'00000000')" .
                    " WHERE a.region_cd LIKE concat(?, '%')" .
                    " AND a.region_cd NOT LIKE '%00000000'" .
                    " AND a.region_cd LIKE '%00000'" .
                    " AND a.use_yn = 'Y'" .
                    " AND EXISTS (SELECT 'x' FROM region_codes c WHERE c.region_cd LIKE CONCAT(SUBSTR(a.region_cd,1,5),'%') AND c.region_cd > CONCAT(SUBSTR(a.region_cd,1,5),'00000'))" .
                    " ORDER BY a.region_nm ASC";
            }

            $query = $this->db->query($sql, [$sido]);
        } else {
            $sql = "SELECT a.region_cd, a.region_nm " .
                "FROM region_codes a " .
                "WHERE (a.region_cd LIKE '%00000000' " .
                "AND a.use_yn = 'Y') " .
                "OR region_cd = 3611000000;";

            $query = $this->db->query($sql);
        }


        return $query->getResultArray();
    }

    // 소속본부조회
    public function getBonbuList()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
            "  FROM departments" .
            " WHERE depth = 1" .
            "   AND use_yn = 'Y'" .
            " ORDER BY lft";

        $query = $this->db->query($sql);


        return $query->getResultArray();
    }

    // 소속팀 조회
    public function getTeamList()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm" .
            "  FROM departments" .
            " WHERE depth = 2" .
            "   AND use_yn = 'Y'" .
            " ORDER BY dept_nm";

        $query = $this->db->query($sql);


        return $query->getResultArray();
    }

    // 유저 조회
    public function getUserList()
    {
        $sql = "SELECT 
                    a.usr_sq, a.usr_id, a.usr_nm, a.dept_sq
                FROM users a
                WHERE 
                        a.usr_level IN ('3','4','40','5','50','6','60','61','62','7','8','70')
                        AND a.use_yn = 'Y'
                        AND EXISTS (
                        SELECT 'x' FROM departments a1 INNER JOIN departments a2 ON a2.lft BETWEEN a1.lft AND a1.rgt AND a2.use_yn = 'Y' 
                        WHERE 1=1 AND a2.dept_sq = a.dept_sq AND a1.use_yn = 'Y'
                )
                ORDER BY a.usr_level DESC, a.usr_nm ASC ";

        $query = $this->db->query($sql);

        return $query->getResultArray();
    }

    public function getTotalCount($data)
    {
        $sql = "SELECT
                    COUNT(*) AS cnt
                FROM
                    fax_imgs a
                LEFT JOIN region_codes c ON c.region_cd = a.address_code
                LEFT JOIN users d ON d.usr_id = a.charger
                LEFT JOIN users e ON e.usr_id = a.reg_charger

                LEFT JOIN receipt f1 ON f1.rcpt_sq = a.vr_sq
                LEFT JOIN v2_vrfc_req f2 ON f2.vr_sq = a.vr_sq and f2.stat_cd < 40
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39' ";

        $sql .= "WHERE 1=1 ";

        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";
        } else if (!empty($data['caller_no'])) {
            $sql .= "AND EXISTS (SELECT 'x'
								    FROM fax_imgs b
									WHERE b.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)
									AND b.RECV_TIME >= '{$data['']}' AND b.RECV_TIME <= '{$data['']}'
									AND b.caller_no LIKE CONCAT('%', '{$data['']}', '%')
									AND b.fax_sq = a.fax_sq) ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                if ($data['stat_cd'] == "10") {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND f2.stat_cd != '40' ";
                } else if ($data['stat_cd'] == "10") {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND rcpt_stat IS NULL ";
                } else {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND f2.stat_cd != '{$data['stat_cd']}' ";
                }
            }

            // 매물번호입력
            if ($data['chk_atcl_no'] == "N") {
                $sql .= "AND a.atcl_no = '' ";
            } else if ($data['chk_atcl_no'] == "Y") {
                $sql .= "AND a.atcl_no != '' ";
            }

            // 중개소
            if (!empty($data['realtor_nm'])) {
                $sql .= "AND a.realtor_nm = '{$data['realtor_nm']}' ";
            }

            // 수신기간
            if (!empty($data['receipt_sdate'])) {
                $sql .= "AND a.RECV_TIME >= '{$data['receipt_sdate']} 00:00:00' ";
            }

            if (!empty($data['recv_etime'])) {
                $sql .= "AND a.RECV_TIME <= '{$data['recv_etime']} 23:59:59' ";
            }

            // 완료기간
            if (!empty($data['complete_sdate'])) {
                $sql .= "AND a.send_tm >= '{$data['complete_sdate']} 00:00:00' ";
            }

            if (!empty($data['complete_edate'])) {
                $sql .= "AND a.send_tm <= '{$data['complete_edate']} 23:59:59' ";
            }

            // 홍보확인서여부
            if ($data['target_yn']) {
                switch ($data['target_yn']) {
                    case "Y":
                        $sql .= "AND a.work_type IN ('1', '2') ";
                        break;
                    case "N":
                        $sql .= "AND a.work_type = 'E' ";
                        break;
                    case "3":
                        $sql .= "AND a.work_type = '3' ";
                        break;
                    case "B":
                        $sql .= "AND a.work_type = 'B' ";
                        break;
                }
            }

            // 매체사
            if (!empty($data['rcpt_cpid'])) {
                $sql .= "AND a.cpid = '{$data['rcpt_cpid']}' ";
            }

            // 동의서 유무
            if ($data['chk_rec'] === "Y") {
                $sql .= "AND a.work_type = '1' ";
                $sql .= "AND EXISTS(SELECT \'x\' FROM receipt z WHERE z.rcpt_sq = a.vr_sq AND z.rcpt_stat = '701000') ";
            }

            // 팩스업체
            if (!empty($data['fax_corp'])) {
                $sql .= "AND a.receiver = '{$data['fax_corp']}' ";
            }

            // 지역구분
            if (!empty($data['srcDong'])) {
                $sql .= "AND a.address_code = '{$data['srcDong']}' ";
            } else {
                if (!empty($data['srcGugun'])) {
                    $str_gugun = substr($data['srcGugun'], '0', '2');
                    if ($str_gugun == '36') { //세종시는 군구가 없고 바로 동이라서 예외
                        $sql .= "AND a.address_code = '{$data['srcGugun']}' ";
                    } else {
                        $gugunPrefix = substr($data['srcGugun'], '0', '5');
                        $sql .= "AND a.address_code LIKE '{$gugunPrefix}%' ";
                    }
                } else {
                    if (!empty($data['srcSido'])) {
                        $sidoPrefix = substr($data['srcSido'], '0', '2');
                        $sql .= "AND a.address_code LIKE '{$sidoPrefix}%' ";
                    }
                }
            }

            // 담당자
            if (!empty($data['damdang'])) {

                switch ($data['charger_gbn']) {
                    case "1":
                        $sql .= "a.charger = '{$data['damdang']}' ";
                        break;
                    case "2":
                        $sql .= "a.reg_charger = '{$data['damdang']}' ";
                        break;
                }

            } else {
                // 배정여부
                if ($data['assign_yn'] !== "A") {
                    switch ($data['charger_gbn'] . $data['assign_yn']) {
                        case "1Y":	// 전화/서류 담당자
                            $sql .= "a.charger != '' ";
                            break;
                        case "1N":	// 전화/서류 담당자                            
                            $sql .= "a.charger = '' ";
                            break;
                        case "2Y":	// 등기부등본 담당자
                            $sql .= "a.reg_charger != '' ";
                            break;
                        case "2N":	// 등기부등본 담당자
                            $sql .= "a.reg_charger IS NULL ";
                            break;
                    }
                }
            }

            // 본부
            if (!empty($data['bonbu'])) {
                if ($data['charger_gbn'] === "1") {
                    $sql .= "AND a.dept1_sq = '{$data['bonbu']}' ";
                } else {
                    $sql .= "AND a.reg_dept1_sq = '{$data['bonbu']}' ";
                }
            }

            // 팀
            if (!empty($data['team'])) {
                if ($data['charger_gbn'] === "1") {
                    $sql .= "AND a.dept2_sq = '{$data['team']}' ";
                } else {
                    $sql .= "AND a.reg_dept2_sq = '{$data['team']}' ";
                }
            }

            // 참고파일
            if (!empty($data['reference_file_url_yn'])) {
                $sql .= "AND a.reference_file_url_yn = '{$data['a.reference_file_url_yn']}' ";
            }

            // 법인
            if (!empty($data['corp_own'])) {
                $sql .= "AND m.corp_own = '{$data['a.corp_own']}' ";
            }

        }


        $query = $this->db->query($sql);

        return $query->getRow()->cnt;
    }

    public function getResultList($start, $end, $data)
    {
        $sql = "SELECT
                    a.fax_sq, a.mid, a.file_name, a.file_path, a.thumbnail, a.img_width, a.img_height, a.img_size, a.img_sq, a.remark, a.work_type, a.receiver
                    , case when a.atcl_no = '' and a.work_type = '1' then f1.rcpt_atclno when a.atcl_no = '' and a.work_type = '2' then f2.atcl_no else a.atcl_no end as atcl_no
                    , a.cpid, a.realtor_nm, a.stat_cd, a.proc_tm, a.send_tm
                    , a.address_code, a.address2b, a.address2, IFNULL(a.address3, '') AS address3, a.charger, a.reg_charger, a.CALLER_NO, a.callee_no, a.tiff_file_name, a.tiff_save_path, a.tiff_file_size, a.RECV_TIME, a.save_time
                    , c.region_nm, d.usr_nm, e.usr_nm reg_charger_nm, d2.insert_tm as stat_39_tm, f1.rcpt_stat, f2.stat_cd as stat_cd2 , f2.vr_sq as vr_sq
                FROM
                    fax_imgs a
                LEFT JOIN region_codes c ON c.region_cd = a.address_code
                LEFT JOIN users d ON d.usr_id = a.charger
                LEFT JOIN users e ON e.usr_id = a.reg_charger

                LEFT JOIN receipt f1 ON f1.rcpt_sq = a.vr_sq
                LEFT JOIN v2_vrfc_req f2 ON f2.vr_sq = a.vr_sq and f2.stat_cd < 40
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39' ";

        $sql .= "WHERE 1=1 ";

        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";
        } else if (!empty($data['caller_no'])) {
            $sql .= "AND EXISTS (SELECT 'x'
								    FROM fax_imgs b
									WHERE b.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)
									AND b.RECV_TIME >= '{$data['']}' AND b.RECV_TIME <= '{$data['']}'
									AND b.caller_no LIKE CONCAT('%', '{$data['']}', '%')
									AND b.fax_sq = a.fax_sq) ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                if ($data['stat_cd'] == "10") {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND f2.stat_cd != '40' ";
                } else if ($data['stat_cd'] == "10") {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND rcpt_stat IS NULL ";
                } else {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND f2.stat_cd != '{$data['stat_cd']}' ";
                }
            }

            // 매물번호입력
            if ($data['chk_atcl_no'] == "N") {
                $sql .= "AND a.atcl_no = '' ";
            } else if ($data['chk_atcl_no'] == "Y") {
                $sql .= "AND a.atcl_no != '' ";
            }

            // 중개소
            if (!empty($data['realtor_nm'])) {
                $sql .= "AND a.realtor_nm = '{$data['realtor_nm']}' ";
            }

            // 수신기간
            if (!empty($data['receipt_sdate'])) {
                $sql .= "AND a.RECV_TIME >= '{$data['receipt_sdate']} 00:00:00' ";
            }

            if (!empty($data['recv_etime'])) {
                $sql .= "AND a.RECV_TIME <= '{$data['recv_etime']} 23:59:59' ";
            }

            // 완료기간
            if (!empty($data['complete_sdate'])) {
                $sql .= "AND a.send_tm >= '{$data['complete_sdate']} 00:00:00' ";
            }

            if (!empty($data['complete_edate'])) {
                $sql .= "AND a.send_tm <= '{$data['complete_edate']} 23:59:59' ";
            }

            // 홍보확인서여부
            if ($data['target_yn']) {
                switch ($data['target_yn']) {
                    case "Y":
                        $sql .= "AND a.work_type IN ('1', '2') ";
                        break;
                    case "N":
                        $sql .= "AND a.work_type = 'E' ";
                        break;
                    case "3":
                        $sql .= "AND a.work_type = '3' ";
                        break;
                    case "B":
                        $sql .= "AND a.work_type = 'B' ";
                        break;
                }
            }

            // 매체사
            if (!empty($data['rcpt_cpid'])) {
                $sql .= "AND a.cpid = '{$data['rcpt_cpid']}' ";
            }

            // 동의서 유무
            if ($data['chk_rec'] === "Y") {
                $sql .= "AND a.work_type = '1' ";
                $sql .= "AND EXISTS(SELECT \'x\' FROM receipt z WHERE z.rcpt_sq = a.vr_sq AND z.rcpt_stat = '701000') ";
            }

            // 팩스업체
            if (!empty($data['fax_corp'])) {
                $sql .= "AND a.receiver = '{$data['fax_corp']}' ";
            }

            // 지역구분
            if (!empty($data['srcDong'])) {
                $sql .= "AND a.address_code = '{$data['srcDong']}' ";
            } else {
                if (!empty($data['srcGugun'])) {
                    $str_gugun = substr($data['srcGugun'], '0', '2');
                    if ($str_gugun == '36') { //세종시는 군구가 없고 바로 동이라서 예외
                        $sql .= "AND a.address_code = '{$data['srcGugun']}' ";
                    } else {
                        $gugunPrefix = substr($data['srcGugun'], '0', '5');
                        $sql .= "AND a.address_code LIKE '{$gugunPrefix}%' ";
                    }
                } else {
                    if (!empty($data['srcSido'])) {
                        $sidoPrefix = substr($data['srcSido'], '0', '2');
                        $sql .= "AND a.address_code LIKE '{$sidoPrefix}%' ";
                    }
                }
            }

            // 담당자
            if (!empty($data['damdang'])) {

                switch ($data['charger_gbn']) {
                    case "1":
                        $sql .= "a.charger = '{$data['damdang']}' ";
                        break;
                    case "2":
                        $sql .= "a.reg_charger = '{$data['damdang']}' ";
                        break;
                }

            } else {
                // 배정여부
                if ($data['assign_yn'] !== "A") {
                    switch ($data['charger_gbn'] . $data['assign_yn']) {
                        case "1Y":	// 전화/서류 담당자
                            $sql .= "a.charger != '' ";
                            break;
                        case "1N":	// 전화/서류 담당자                            
                            $sql .= "a.charger = '' ";
                            break;
                        case "2Y":	// 등기부등본 담당자
                            $sql .= "a.reg_charger != '' ";
                            break;
                        case "2N":	// 등기부등본 담당자
                            $sql .= "a.reg_charger IS NULL ";
                            break;
                    }
                }
            }

            // 본부
            if (!empty($data['bonbu'])) {
                if ($data['charger_gbn'] === "1") {
                    $sql .= "AND a.dept1_sq = '{$data['bonbu']}' ";
                } else {
                    $sql .= "AND a.reg_dept1_sq = '{$data['bonbu']}' ";
                }
            }

            // 팀
            if (!empty($data['team'])) {
                if ($data['charger_gbn'] === "1") {
                    $sql .= "AND a.dept2_sq = '{$data['team']}' ";
                } else {
                    $sql .= "AND a.reg_dept2_sq = '{$data['team']}' ";
                }
            }

            // 참고파일
            if (!empty($data['reference_file_url_yn'])) {
                $sql .= "AND a.reference_file_url_yn = '{$data['a.reference_file_url_yn']}' ";
            }

            // 법인
            if (!empty($data['corp_own'])) {
                $sql .= "AND m.corp_own = '{$data['a.corp_own']}' ";
            }

        }

        $sql .= "ORDER BY a.fax_sq DESC , a.RECV_TIME DESC ";

        $sql .= "LIMIT {$start}, {$end}";

        $query = $this->db->query($sql);

        return $query->getResultArray();
    }


    // 엑셀 다운로드
    public function getExcelList($data)
    {
        $sql = "SELECT
                    CONCAT(c1.cd_nm, ' ', a.receiver) AS '팩스업체', 
                    a.atcl_no AS '매물번호',
                    CASE WHEN f2.stat_cd IS NULL THEN CASE WHEN f1.rcpt_stat IS NULL THEN c2.cd_nm ELSE c3.cd_nm END
                    ELSE c4.cd_nm END AS '현재상태',
                    CASE WHEN a.work_type = '1' OR a.work_type = '2' THEN 'Y' WHEN a.work_type = 'E' THEN 'N' END AS '홍보확인서여부',
                    a.RECV_TIME AS '수신시간',
                    a.CALLER_NO AS '발신번호',
                    c.region_nm AS '주소',
                    a.address2 AS '상세주소',
                    a.cpid AS '매체사',
                    a.realtor_nm AS '중개소',
                    d.usr_nm AS '서류/전화 담당자',
                    a.proc_tm AS '서류/전화 확인시간',
                    e.usr_nm AS '등기부등본 담당자',
                    a.send_tm AS '검증완료일시'
                FROM
                    fax_imgs a
                LEFT JOIN region_codes c ON c.region_cd = a.address_code
                LEFT JOIN users d ON d.usr_id = a.charger
                LEFT JOIN users e ON e.usr_id = a.reg_charger

                LEFT JOIN receipt f1 ON f1.rcpt_sq = a.vr_sq
                LEFT JOIN v2_vrfc_req f2 ON f2.vr_sq = a.vr_sq and f2.stat_cd < 40
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39'

                LEFT JOIN codes c1 ON c1.cd = a.receiver AND c1.category = 'FAX_CORP'
                LEFT JOIN codes c2 ON c2.cd = a.stat_cd AND c2.category = 'STEP_VERIFICATION'
                LEFT JOIN codes c3 ON c3.cd = f1.rcpt_stat AND c3.category = 'RECEIPT_STATUS3'
                LEFT JOIN codes c4 ON c4.cd = f2.stat_cd AND c4.category = 'STEP_VERIFICATION'

                WHERE 1=1 ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";
        } else if (!empty($data['caller_no'])) {
            $sql .= "AND EXISTS (SELECT 'x'
								    FROM fax_imgs b
									WHERE b.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)
									AND b.RECV_TIME >= '{$data['']}' AND b.RECV_TIME <= '{$data['']}'
									AND b.caller_no LIKE CONCAT('%', '{$data['']}', '%')
									AND b.fax_sq = a.fax_sq) ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                if ($data['stat_cd'] == "10") {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND f2.stat_cd != '40' ";
                } else if ($data['stat_cd'] == "10") {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND rcpt_stat IS NULL ";
                } else {
                    $sql .= "AND a.stat_cd = '{$data['stat_cd']}' ";
                    $sql .= "AND f2.stat_cd != '{$data['stat_cd']}' ";
                }
            }

            // 매물번호입력
            if ($data['chk_atcl_no'] == "N") {
                $sql .= "AND a.atcl_no = '' ";
            } else if ($data['chk_atcl_no'] == "Y") {
                $sql .= "AND a.atcl_no != '' ";
            }

            // 중개소
            if (!empty($data['realtor_nm'])) {
                $sql .= "AND a.realtor_nm = '{$data['realtor_nm']}' ";
            }

            // 수신기간
            if (!empty($data['receipt_sdate'])) {
                $sql .= "AND a.RECV_TIME >= '{$data['receipt_sdate']} 00:00:00' ";
            }

            if (!empty($data['recv_etime'])) {
                $sql .= "AND a.RECV_TIME <= '{$data['recv_etime']} 23:59:59' ";
            }

            // 완료기간
            if (!empty($data['complete_sdate'])) {
                $sql .= "AND a.send_tm >= '{$data['complete_sdate']} 00:00:00' ";
            }

            if (!empty($data['complete_edate'])) {
                $sql .= "AND a.send_tm <= '{$data['complete_edate']} 23:59:59' ";
            }

            // 홍보확인서여부
            if ($data['target_yn']) {
                switch ($data['target_yn']) {
                    case "Y":
                        $sql .= "AND a.work_type IN ('1', '2') ";
                        break;
                    case "N":
                        $sql .= "AND a.work_type = 'E' ";
                        break;
                    case "3":
                        $sql .= "AND a.work_type = '3' ";
                        break;
                    case "B":
                        $sql .= "AND a.work_type = 'B' ";
                        break;
                }
            }

            // 매체사
            if (!empty($data['rcpt_cpid'])) {
                $sql .= "AND a.cpid = '{$data['rcpt_cpid']}' ";
            }

            // 동의서 유무
            if ($data['chk_rec'] === "Y") {
                $sql .= "AND a.work_type = '1' ";
                $sql .= "AND EXISTS(SELECT \'x\' FROM receipt z WHERE z.rcpt_sq = a.vr_sq AND z.rcpt_stat = '701000') ";
            }

            // 팩스업체
            if (!empty($data['fax_corp'])) {
                $sql .= "AND a.receiver = '{$data['fax_corp']}' ";
            }

            // 지역구분
            if (!empty($data['srcDong'])) {
                $sql .= "AND a.address_code = '{$data['srcDong']}' ";
            } else {
                if (!empty($data['srcGugun'])) {
                    $str_gugun = substr($data['srcGugun'], '0', '2');
                    if ($str_gugun == '36') { //세종시는 군구가 없고 바로 동이라서 예외
                        $sql .= "AND a.address_code = '{$data['srcGugun']}' ";
                    } else {
                        $gugunPrefix = substr($data['srcGugun'], '0', '5');
                        $sql .= "AND a.address_code LIKE '{$gugunPrefix}%' ";
                    }
                } else {
                    if (!empty($data['srcSido'])) {
                        $sidoPrefix = substr($data['srcSido'], '0', '2');
                        $sql .= "AND a.address_code LIKE '{$sidoPrefix}%' ";
                    }
                }
            }

            // 담당자
            if (!empty($data['damdang'])) {

                switch ($data['charger_gbn']) {
                    case "1":
                        $sql .= "a.charger = '{$data['damdang']}' ";
                        break;
                    case "2":
                        $sql .= "a.reg_charger = '{$data['damdang']}' ";
                        break;
                }

            } else {
                // 배정여부
                if ($data['assign_yn'] !== "A") {
                    switch ($data['charger_gbn'] . $data['assign_yn']) {
                        case "1Y":	// 전화/서류 담당자
                            $sql .= "a.charger != '' ";
                            break;
                        case "1N":	// 전화/서류 담당자                            
                            $sql .= "a.charger = '' ";
                            break;
                        case "2Y":	// 등기부등본 담당자
                            $sql .= "a.reg_charger != '' ";
                            break;
                        case "2N":	// 등기부등본 담당자
                            $sql .= "a.reg_charger IS NULL ";
                            break;
                    }
                }
            }

            // 본부
            if (!empty($data['bonbu'])) {
                if ($data['charger_gbn'] === "1") {
                    $sql .= "AND a.dept1_sq = '{$data['bonbu']}' ";
                } else {
                    $sql .= "AND a.reg_dept1_sq = '{$data['bonbu']}' ";
                }
            }

            // 팀
            if (!empty($data['team'])) {
                if ($data['charger_gbn'] === "1") {
                    $sql .= "AND a.dept2_sq = '{$data['team']}' ";
                } else {
                    $sql .= "AND a.reg_dept2_sq = '{$data['team']}' ";
                }
            }

            // 참고파일
            if (!empty($data['reference_file_url_yn'])) {
                $sql .= "AND a.reference_file_url_yn = '{$data['a.reference_file_url_yn']}' ";
            }

            // 법인
            if (!empty($data['corp_own'])) {
                $sql .= "AND m.corp_own = '{$data['a.corp_own']}' ";
            }

        }

        $sql .= "ORDER BY a.fax_sq DESC , a.RECV_TIME DESC ";


        $query = $this->db->query($sql);

        return $query->getResultArray();
    }


    // 상세조회
    public function getDetail($fax_sq)
    {
        $sql = "SELECT
                    a.fax_sq, a.mid, a.file_name, a.file_path, a.thumbnail, a.img_width, a.img_height, a.img_size, a.img_sq, a.remark, 
                    a.work_type, a.vr_sq, a.atcl_no, a.cpid, a.realtor_nm, a.stat_cd, a.proc_tm, a.send_tm, a.address_code, a.address2, 
                    a.address2a, a.address2b, a.charger, a.caller_no, a.receiver
                FROM
                    fax_imgs a
                WHERE 
                    fax_sq = ?";

        $query = $this->db->query($sql, [$fax_sq]);

        $row = $query->getRowArray();

        $this->db->transStart();


        if ($row['stat_cd'] === "10") {

            $usr_id = session('usr_id');
            $usr_sq = session('usr_sq');
            $row_dept = $this->getDepartmentPath($usr_sq);
            $dept1_sq = '';
            $dept2_sq = '';
            if (!empty($row_dept)) {
                $dept1_sq = $row_dept['dept1_sq'];
                $dept2_sq = $row_dept['dept2_sq'];
            }

            $sql = "UPDATE fax_imgs SET
                    stat_cd = '20', charger = ?, dept1_sq = ?, dept2_sq = ?
                    WHERE fax_sq = ?
                    ";

            $this->db->query($sql, [$usr_id, $dept1_sq, $dept2_sq, $fax_sq]);

        }

        $this->db->transComplete();

        return $row;
    }

    // 현장확인매물 조회
    public function getArticleInfo1($atcl_no, $vr_sq = '')
    {
        $sql_where = "";
        if (!empty($vr_sq)) {
            $sql_where = " and a.rcpt_sq = '" . $vr_sq . "'";
        }

        $sql = "select a.rcpt_sq vr_sq, a.rcpt_atclno atcl_no, a.rcpt_floor as floor, a.rcpt_floor2 as floor2, a.rcpt_cpid cpid, a.agent_nm realtor_nm, a.agent_head_tel agent_tel, a.agent_fax agent_fax, a.agent_contact_tel realtor_tel_no, a.rcpt_tm rdate, '' seller_nm, '' seller_tel_no, a.rcpt_product rlet_type_cd, a.rcpt_dong address_code, c.region_nm address1 , a.rcpt_dtl_addr address2, a.rcpt_li_addr address2a, a.rcpt_jibun_addr address2b, a.rcpt_etc_addr, a.rcpt_ho address3 , a.rcpt_ref_addr address4, a.rcpt_hscp_nm as hscp_nm, a.rcpt_ptp_nm as ptp_nm, a.trade_type" .
            ", case substr(a.trade_type, 1, 1) when 'A' then SUBSTRING_INDEX(a.rcpt_product_info2, '/', 1) else 0 end deal_amt" .
            ", case substr(a.trade_type, 1, 1) when 'B' then SUBSTRING_INDEX(a.rcpt_product_info2, '/', 1) else 0 end wrrnt_amt" .
            ", case substr(a.trade_type, 1, 1) when 'B' then case when a.rcpt_product_info3 is null || a.rcpt_product_info3 = '' || a.rcpt_product_info3 = '0' then SUBSTRING_INDEX(a.rcpt_product_info2, '/', -1) else a.rcpt_product_info3 end else 0 end  lease_amt" .
            ", a.rcpt_product_info4 isale_amt, a.rcpt_product_info5 prem_amt, a.rcpt_product_nm rlet_type_nm, d.cd_nm trade_type_nm, b.dbUsageAgrYn, b.resYn ,'1' try_cnt, '10' stat_cd" .
            ", b.request_msg" .
            ", (SELECT cd_nm FROM codes WHERE category = 'RECEIPT_STATUS3' AND cd = a.rcpt_stat) AS current_stat" .
            ", case when a.isSiteVRVerification = 'Y' then '현장v2' else '현장' end as typeOfProperty" .
            ", a.rcpt_hscp_no as hscp_no " .
            " from receipt a" .
            " inner join result b on b.rcpt_sq = a.rcpt_sq" .
            " left join region_codes c on c.region_cd = a.rcpt_dong" .
            " left join codes d on d.category = 'TRADE_TYPE' AND d.cd = a.trade_type" .
            " where a.rcpt_atclno = ? " . $sql_where .
            "order by a.rcpt_sq desc, b.rsrv_sq desc";

        $data = [
            $atcl_no
        ];

        $query = $this->db->query($sql, $data);

        return $query->getRowArray();
    }

    // 일반확인매물 조회
    public function getArticleInfo2($atcl_no, $vr_sq = '')
    {
        $sql_where = "";
        if (!empty($vr_sq)) {
            $sql_where = " and a.vr_sq = ? ";
            $data = array(
                $vr_sq
            );
        } else {
            $sql_where = " and a.atcl_no = ? ";
            $data = array(
                $atcl_no
            );
        }

        // b.address1 대신에 region_nm 을 사용했음.... 
        $sql = "select a.memo, g.cd_nm as pre_stat, a.vr_sq, a.atcl_no, a.cpid, a.realtor_nm, a.realtor_tel_no, b.floor, b.floor2, b.rdate, b.seller_nm, b.seller_tel_no agent_tel, b.rlet_type_cd, b.address_code, f.bild_nm as address1, f.address2, j.address2a, j.address2b, f.address3, f.address4, f.hscp_nm, f.ptp_nm, b.trade_type, f.deal_amt, f.wrrnt_amt, f.lease_amt, f.isale_amt, f.prem_amt, c.cd_nm as rlet_type_nm, d.cd_nm  as trade_type_nm, a.try_cnt, a.stat_cd, '' request_msg, b.vrfc_type_sub, i.cd_nm as vrfc_type_sub_nm, b.confirm_doc_owner_check_yn, b.ownerNm, j.vir_addr_yn" .
            ", (SELECT cd_nm FROM codes WHERE category = 'STEP_VERIFICATION' AND cd = a.stat_cd) AS current_stat, a.vrfc_type, h.cd_nm AS vrfc_type_nm" .
            ", get_code_name('VRFCREQ_WAY',a.vrfc_type) as typeOfProperty " .
            ", b.hscp_no as hscp_no " .
            " from v2_vrfc_req a" .
            " inner join v2_article_info b on b.vr_sq = a.vr_sq  and b.rdate >= date_add( now(), interval -3 month)" .
            " inner join v2_article_info_etc j on j.vr_sq = a.vr_sq " .
            " left join codes c on c.category = 'ARTICLE_TYPE' AND c.cd = b.rlet_type_cd" .
            " left join codes d on d.category = 'VRFCREQ_DEAL_TYPE' AND d.cd = b.trade_type" .
            " left join codes i on i.category like 'VRFC_TYPE_SUB_%' AND i.cd = b.vrfc_type_sub" .
            " left join codes g on g.category = 'STEP_VERIFICATION' AND g.cd = a.stat_cd" .
            " left join codes h on h.category = 'VRFCREQ_WAY' AND h.cd = a.vrfc_type" .
            " left join region_codes e on e.region_cd = b.address_code" .
            " left join v2_modify_info f on f.vr_sq = a.vr_sq" .
            " where 1=1" . $sql_where .
            " AND a.vrfc_type in('D','M')" .
            " order by a.vr_sq desc" .
            " limit 1";

        $query = $this->db->query($sql, $data);

        return $query->getRowArray();
    }

    // 홍보확인서 확인결과 읽어오기
    public function getV2Confirm($vr_sq, $work_type = '2')
    {
        $sql = "SELECT b.type type_d11, b.code code_d11, b.comment comment_d11, c.type type_d12, c.code code_d12, c.comment comment_d12, d.type type_d13, d.code code_d13, d.comment comment_d13, e.type type_d14, e.code code_d14, e.comment comment_d14" .
            " FROM v2_confirm a" .
            " INNER JOIN v2_check_list b ON b.vr_sq = a.vr_sq AND b.type = 'D11'" .
            " INNER JOIN v2_check_list c ON c.vr_sq = a.vr_sq AND c.type = 'D12'" .
            " INNER JOIN v2_check_list d ON d.vr_sq = a.vr_sq AND d.type = 'D13'" .
            " INNER JOIN v2_check_list e ON e.vr_sq = a.vr_sq AND e.type = 'D14'" .
            " WHERE a.vr_sq = ?" .
            " AND a.vrfc_type = 'D'" .
            " AND a.work_type = ?";
        $data = array($vr_sq, $work_type);
        $query = $this->db->query($sql, $data);

        return $query->getRowArray();
    }

    // 메모조회
    public function getMomo($vr_sq)
    {
        $sql = "SELECT memo FROM v2_vrfc_req where vr_sq = ?";
        $data = [
            $vr_sq
        ];
        $query = $this->db->query($sql, $data);

        return $query->getRowArray();
    }

    // 변경이력 조회
    public function getHistory($rcpt_key, $work_type = '')
    {
        if ($work_type == '1') {

            $sql = "SELECT
                            a.seq,
                            a.rcpt_sq vr_sq,
                            a.rcpt_stat stat_cd,
                            a.changed_type chg_type,
                            a.changed_id insert_id,
                            a.changed_tm insert_tm,
                            a.remark memo,
                            b.cd_nm as stat_cd_nm,
                            c.cd_nm as chg_type
                        FROM changed_history a
                        LEFT JOIN codes b ON a.rcpt_stat = b.cd AND b.category = 'RECEIPT_STATUS3'
                        LEFT JOIN codes c ON a.changed_type = c.cd AND c.category = 'CHANGED_TYPE'
                        WHERE a.rcpt_sq = ?
                        ORDER BY a.seq DESC
                        ";

            $query = $this->db->query($sql, [$rcpt_key]);

            $history = $query->getResultArray();

            return $history;
        } else {

            $sql = "SELECT
                            a.seq,
                            a.vr_sq,
                            a.stat_cd,
                            a.chg_type,
                            a.insert_id,
                            a.insert_tm,
                            a.memo,
                            b.cd_nm as stat_cd_nm,
                            c.cd_nm as chg_type
                        FROM v2_chg_history a
                        LEFT JOIN codes b ON a.stat_cd = b.cd AND b.category = 'STEP_VERIFICATION'
                        LEFT JOIN codes c ON a.chg_type = c.cd AND c.category = 'CHANGED_TYPE'
                        WHERE a.vr_sq = ?
                        ORDER BY a.seq DESC
                            ";


            $query = $this->db->query($sql, [$rcpt_key]);
            $history = $query->getResultArray();

            return $history;
        }
    }

    // 현장확인 저장
    public function saveReceiptFax($memo, $fax_sq, $vr_sq, $atcl_no, $work_type, $result_d11, $comment_d11, $fax_conf_yn_1, $fax_conf_yn_2, $fax_conf_yn_3, $fax_conf_info_1, $fax_conf_info_2, $fax_conf_info_3, $stat_cd = '')
    {
        $this->db->transStart();

        $article = NULL;
        $current_tm = date('Y-m-d H:i:s');
        $usr_id = session('usr_id');
        $usr_sq = session('usr_sq');

        if ($work_type == '2') {
            $article = $this->getArticleInfo2($atcl_no, $vr_sq);
        } else {
            $article = $this->getArticleInfo1($atcl_no, $vr_sq);
        }

        $row_dept = $this->getDepartmentPath($usr_sq);
        $dept1_sq = '';
        $dept2_sq = '';
        if (!empty($row_dept)) {
            $dept1_sq = $row_dept['dept1_sq'];
            $dept2_sq = $row_dept['dept2_sq'];
        }

        if ($article['vrfc_type'] == 'M') {
            $mobile_yn = 'Y';
        } else {
            $mobile_yn = 'N';
        }

        $data = [
            'work_type' => $work_type,
            'vr_sq' => $vr_sq,
            'atcl_no' => $atcl_no,
            'cpid' => $article['cpid'],
            'realtor_nm' => $article['realtor_nm'],
            'proc_tm' => $current_tm,
            'address_code' => $article['address_code'],
            'address2' => $article['address2'],
            'charger' => $usr_id,
            'dept1_sq' => $dept1_sq,
            'dept2_sq' => $dept2_sq,
            'mobile_yn' => $mobile_yn
        ];


        $builder = $this->db->table('fax_imgs')->where('fax_sq', $fax_sq);
        $ok = $builder->update($data);

        if ($ok === false) {
            return [
                'success' => false,
                'msg' => 'fax_imgs 저장 실패',
            ];
        }

        //1.만약 모바일건이면 insert
        if ($article['vrfc_type'] == "M") {
            $data = [
                'fax_sq' => $fax_sq,
                'vr_sq' => $vr_sq,
                'atcl_no' => $atcl_no,
                'recv_time' => $fax_sq
            ];

            $sql = "INSERT INTO fax_imgs_mobile (fax_sq, vr_sq, atcl_no, recv_time)
					VALUES (?, ?, ?, (SELECT recv_time FROM fax_imgs WHERE fax_sq = ?))
					ON DUPLICATE KEY UPDATE  vr_sq = VALUES(vr_sq), atcl_no= VALUES(atcl_no), recv_time = VALUES(recv_time)";

            $this->db->query($sql, $data);
        }

        $this->db->transComplete();

        return [
            'success' => true,
        ];

    }

    // 홍보확인서 아님
    public function saveNotArticleFax($fax_sq)
    {
        $this->db->transStart();

        $usr_id = session('usr_id');
        $usr_sq = session('usr_sq');
        $row_dept = $this->getDepartmentPath($usr_sq);
        $dept1_sq = '';
        $dept2_sq = '';
        if (!empty($row_dept)) {
            $dept1_sq = $row_dept['dept1_sq'];
            $dept2_sq = $row_dept['dept2_sq'];
        }

        $data = [
            'work_type' => 'E',
            'proc_tm' => date('Y-m-d H:i:s'),
            'stat_cd' => '69',
            'charger' => $usr_id,
            'dept1_sq' => $dept1_sq,
            'dept2_sq' => $dept2_sq
        ];

        $builder = $this->db->table('fax_imgs')->where('fax_sq', $fax_sq);
        $ok = $builder->update($data);

        if ($ok === false) {
            return [
                'success' => false,
                'msg' => 'fax_imgs 저장 실패',
            ];
        }

        $this->db->transComplete();

        return [
            'success' => true,
        ];
    }

    // 중복저장
    public function saveDuplicateFax($fax_sq, $atcl_no, $vr_sq)
    {
        $this->db->transStart();

        $current_tm = date('Y-m-d H:i:s');
        $article = $this->getArticleInfo2($atcl_no, $vr_sq);

        $this->saveFaxImgs($fax_sq, '2', $vr_sq, $atcl_no, $article['cpid'], $article['realtor_nm'], $article['stat_cd'], $current_tm, $article['address_code'], $article['address2']);

        $this->db->transComplete();

        return [
            'success' => true,
        ];
    }

    // 부분수신
    public function saveBubunFax($fax_sq)
    {
        $this->db->transStart();

        $usr_id = session('usr_id');
        $usr_sq = session('usr_sq');
        $row_dept = $this->getDepartmentPath($usr_sq);
        $dept1_sq = '';
        $dept2_sq = '';
        if (!empty($row_dept)) {
            $dept1_sq = $row_dept['dept1_sq'];
            $dept2_sq = $row_dept['dept2_sq'];
        }

        $data = [
            'work_type' => 'B',
            'proc_tm' => date('Y-m-d H:i:s'),
            'stat_cd' => '69',
            'charger' => $usr_id,
            'dept1_sq' => $dept1_sq,
            'dept2_sq' => $dept2_sq
        ];

        $builder = $this->db->table('fax_imgs')->where('fax_sq', $fax_sq);
        $ok = $builder->update($data);

        if ($ok === false) {
            return [
                'success' => false,
                'msg' => 'fax_imgs 저장 실패',
            ];
        }

        $this->db->transComplete();

        return [
            'success' => true,
        ];
    }

    // 매물정보 변경
    public function saveFaxImgInfo($fax_sq, $vr_sq, $atcl_no, $trade_type, $deal_amt, $wrrnt_amt, $lease_amt, $isale_amt, $prem_amt)
    {
        $current_tm = date('Y-m-d H:i:s');
        $article = $this->getArticleInfo2($atcl_no, $vr_sq);

        $this->db->transStart();
        $this->saveFaxImgs($fax_sq, '2', $vr_sq, $atcl_no, $article['cpid'], $article['realtor_nm'], $article['stat_cd'], $current_tm, $article['address_code'], $article['address2']);
        $this->saveModifyInfo($vr_sq, $trade_type, $deal_amt, $wrrnt_amt, $lease_amt);
        $this->saveTradetypeFloor($vr_sq, $trade_type, $deal_amt, $wrrnt_amt, $lease_amt, $isale_amt, $prem_amt);

        $this->db->transComplete();

        return [
            'success' => true,
        ];
    }

    // ============================================================================================================================
// ===================================== 홍보확인서 저장시 각각의 테이블에 저장하는 함수 ======================================
// ============================================================================================================================
    /**
     * 전송 후 FAX에 상태 및 전송시간을 저장한다.
     */
    public function saveFaxImgsAfterSend($fax_sq, $vr_sq, $stat_cd, $send_tm = '')
    {
        if (empty($send_tm))
            $send_tm = date('Y-m-d H:i:s');

        $data_fax_imgs = array(
            'stat_cd' => $stat_cd,	// 서류확인 완료
            'send_tm' => $send_tm,
        );
        $this->db->where('fax_sq', $fax_sq);
        $this->db->where('vr_sq', $vr_sq);
        $this->db->update('fax_imgs', $data_fax_imgs);

        log_message('debug', $this->db->last_query());
    }

    // 매물정보 저장
    public function saveFaxImgs($fax_sq, $work_type, $vr_sq, $atcl_no, $cpid, $realtor_nm, $stat_cd, $proc_tm, $address_code, $address2)
    {
        $insert_id = session('usr_id');
        $usr_sq = session('usr_sq');

        // 부서 정보
        $row_dept = $this->getDepartmentPath($usr_sq);

        $dept1_sq = $row_dept['dept1_sq'] ?? '';
        $dept2_sq = $row_dept['dept2_sq'] ?? '';

        // 업데이트 데이터
        $dataFaxImgs = [
            'work_type' => $work_type,
            'vr_sq' => $vr_sq,
            'atcl_no' => $atcl_no,
            'cpid' => $cpid,
            'realtor_nm' => $realtor_nm,
            'stat_cd' => $stat_cd,     // 서류확인 완료
            'proc_tm' => $proc_tm,
            'address_code' => $address_code,
            'address2' => $address2,
            'charger' => $insert_id,
            'dept1_sq' => $dept1_sq,
            'dept2_sq' => $dept2_sq,
        ];

        // DB        
        $builder = $this->db->table('fax_imgs')->where('fax_sq', $fax_sq);
        $ok = $builder->update($dataFaxImgs);

        if ($ok === false) {
            return [
                'success' => false,
                'msg' => 'fax_imgs 저장 실패',
            ];
        }

        return [
            'success' => true,
        ];
    }


    // 
    public function saveModifyInfo($vr_sq, $trade_type, $deal_amt, $wrrnt_amt, $lease_amt, $isale_amt = null, $prem_amt = null)
    {
        $usr_id = session('usr_id');

        $sql = "SELECT a.address2, a.address3, b.stat_cd 
                FROM v2_modify_info a
                INNER JOIN v2_vrfc_req b on b.vr_sq = a.vr_sq
                WHERE a.vr_sq = ?";
        $query = $this->db->query($sql, [$vr_sq]);
        $row = $query->getRowArray();


        $data = [
            'trade_type' => $trade_type,
            'deal_amt' => $deal_amt,
            'wrrnt_amt' => $wrrnt_amt,
            'lease_amt' => $lease_amt,
            'isale_amt' => $isale_amt,
            'prem_amt' => $prem_amt,
            'modify_yn' => 'Y',
        ];

        $builder = $this->db->table('v2_modify_info')->where('vr_sq', $vr_sq);
        $ok = $builder->update($data);

        if ($ok === false) {
            return [
                'success' => false,
                'msg' => 'v2_modify_info 저장 실패',
            ];
        }

        $memo = "거래종류 : " . $row['stat_cd'] . " => " . $trade_type;
        $this->saveChangedHistory($vr_sq, $row['stat_cd'], 'C17', $usr_id, $memo);

        return [
            'success' => true,
        ];
    }

    // 
    public function saveTradetypeFloor($vr_sq, $trade_type, $deal_amt, $wrrnt_amt, $lease_amt, $isale_amt, $prem_amt)
    {
        $data = [
            'trade_type' => $trade_type,
            'deal_amt' => $deal_amt,
            'wrrnt_amt' => $wrrnt_amt,
            'lease_amt' => $lease_amt,
            'isale_amt' => $isale_amt,
            'prem_amt' => $prem_amt
        ];

        $builder = $this->db->table('v2_article_info')->where('vr_sq', $vr_sq);
        $ok = $builder->update($data);

        if ($ok === false) {
            return [
                'success' => false,
                'msg' => 'v2_article_info 저장 실패',
            ];
        }

        return [
            'success' => true,
        ];
    }

    // 중개서 요청 메모 저장
    public function saveRequestMessage($rcpt_sq, $rsrv_sq, $msg)
    {
        $usr_id = session('usr_id');

        $this->db->transStart();

        if (empty($rsrv_sq)) {
            $sql = "SELECT rsrv_sq FROM result WHERE rcpt_sq = ? ORDER BY rsrv_sq DESC LIMIT 1";
            $query = $this->db->query($sql, [$rcpt_sq]);

            $row = $query->getRowArray();
            $rsrv_sq = $row['rsrv_sq'];
        }

        $sql = "SELECT result_cd3, request_msg FROM result WHERE rsrv_sq = ?";
        $query = $this->db->query($sql, [$rsrv_sq]);
        $row = $query->getRowArray();

        $sql = "UPDATE result SET 
                request_msg = ?
                WHERE rsrv_sq = ?, rcpt_sq = ?
                ";

        if ($this->db->query($sql, binds: [$msg, $rsrv_sq, $rcpt_sq]) === false) {
            return [
                'success' => false,
                'msg' => '저장 실패',
            ];
        }

        $memo = "메모변경 : " . $row['request_msg'] . " => " . $msg;
        $this->saveChangedHistory($rcpt_sq, $row['result_cd3'], 'C19', $usr_id, $memo);

        $this->db->transComplete();

        return [
            'success' => true,
        ];
    }

    // 사용자 부서 조회
    public function getDepartmentPath($usr_sq)
    {
        $sql = "SELECT 
                    b.dept_sq AS dept2_sq, c.dept_sq AS dept1_sq         
                FROM users a 
                JOIN departments b ON b.dept_sq = a.dept_sq
                JOIN departments c ON c.dept_sq = b.pdept_sq
                WHERE a.usr_sq = ?";

        $query = $this->db->query($sql, [$usr_sq]);

        return $query->getRowArray();
    }

    // 변경내용 저장
    public function saveChangedHistory($rcpt_sq, $rcpt_stat, $changed_type, $usr_id, $remark)
    {
        $sql = "INSERT INTO changed_history" .
            " (rcpt_sq, rcpt_stat, changed_type, changed_id, changed_tm, remark)" .
            " VALUES" .
            " (?, ?, ?, ?, now(), ?)";
        $data = [
            $rcpt_sq,
            $rcpt_stat,
            $changed_type,
            $usr_id,
            $remark
        ];

        $this->db->query($sql, $data);
    }


    // 다음 매물 조회
    public function getNextFaxImgs($fax_sq)
    {
        $this->db->transStart();

        $h_y = $this->get_send_yn('H');
        $usr_id = session('usr_id');
        $usr_sq = session('usr_sq');
        $row_dept = $this->getDepartmentPath($usr_sq);
        $dept1_sq = '';
        $dept2_sq = '';
        if (!empty($row_dept)) {
            $dept1_sq = $row_dept['dept1_sq'];
            $dept2_sq = $row_dept['dept2_sq'];
        }


        if ($h_y['stop_yn'] == 'N') {
            $where = '';
        } else {
            $where = " AND a.recv_time < date_format(curdate( ), '%Y-%m-%d 17:30:00') ";
        }

        $sql = "SELECT a.fax_sq FROM fax_imgs a
                WHERE a.recv_time > DATE_ADD(NOW(), INTERVAL -7 DAY) " .
            $where .
            " AND a.stat_cd = '10'" .
            " AND a.fax_sq > ?" .
            " and not exists ( SELECT 'x' from v2_vrfc_req v2 where a.vr_sq = v2.vr_sq AND v2.stat_cd = '40' ) " .
            " ORDER BY a.fax_sq asc" .
            " LIMIT 1" .
            " FOR UPDATE SKIP LOCKED";

        $query = $this->db->query($sql, [$fax_sq]);
        $row = $query->getRowArray();

        $sql = "UPDATE fax_imgs" .
            " SET stat_cd = '20', charger='" . $usr_id . "', dept1_sq='" . $dept1_sq . "', dept2_sq='" . $dept2_sq . "'" .
            " WHERE fax_sq = '" . $row['fax_sq'] . "'";
        $this->db->query($sql);

        $this->db->transComplete();

        return $row;
    }


    public function get_send_yn($type)
    {
        $sql = "SELECT stop_yn
				FROM v2_stop_api_chg_stat
				WHERE TYPE = ?
				ORDER BY pk DESC 
				LIMIT 1";
        $date = [
            $type
        ];
        $query = $this->db->query($sql, $date);
        $return = $query->getRowArray();

        return $return;
    }

    // 거주여부 & DB활용동의여부 만 UPDATE
    public function updateResDB($val1, $val2, $sq)
    {
        $data = [
            'res_yn' => $val1,
            'dbUsageAgrYn' => $val2
        ];

        log_message('debug', 'm703_model::updateResDB: 1');

        $builder = $this->db->table('result')->where('rcpt_sq', $sq);
        $ok = $builder->update($data);

        log_message('debug', $this->db->getLastQuery());
    }

    // 매물정보와 FAX를 연결해 준다.
    public function saveArticleFAX($memo, $fax_sq, $vr_sq, $atcl_no, $work_type, $result_d11, $comment_d11, $fax_conf_yn_1, $fax_conf_yn_2, $fax_conf_yn_3, $fax_conf_info_1, $fax_conf_info_2, $fax_conf_info_3, $stat_cd = '')
    {
        // 1. 매물정보 저장 fax_imgs
        // 2.1 확인결과 저장 v2_confirms
        // 2.2 확인정보 체크 v2_check_list
        // 3.1 검증요청 상태변경 v2_vrfc_req
        // 3.2 상태변경 저장 v2_chg_stat
        // 4. 첨부파일 저장 v2_files
        // 5. 변경이력 저장 v2_chg_history
        // 6. kiso 전송하기

        $this->db->transStart();

        $article = NULL;
        $current_tm = date('Y-m-d H:i:s');
        $insert_user = session('usr_sq');
        $insert_id = session('usr_id');
        $update_user = $insert_user;


        switch ($work_type) {
            case "1": // 현장확인매물
                $article = $this->getArticleInfo1($atcl_no, $vr_sq);

                // 1. 매물정보 저장 fax_imgs
                $this->saveFaxImgs($fax_sq, $work_type, $vr_sq, $atcl_no, $article['cpid'], $article['realtor_nm'], '35', $current_tm, $article['address_code'], $article['address2']);

                // 2.1 확인결과 저장 v2_confirm
                if ($result_d11 == '10000' && $fax_conf_yn_1 == 'Y' && $fax_conf_yn_2 == 'Y' && $fax_conf_yn_3 == 'Y') {
                    $success = TRUE;
                } else {
                    $success = FALSE;

                    $result_tm = $this->getUpdateFailTime($vr_sq);
                    $update_tm = $result_tm['insert_tm'];
                    $ten_ago = date("Y-m-d H:i:s", mktime(date("H"), date("i") - 10, date("s"), date("m"), date("d"), date("Y")));

                    if ($update_tm > $ten_ago) {
                        // 수정한 시간이 현재시간10분전 보다 클 경우 수정불가능

                        // $this->session->set_flashdata('alert', '이미 불일치 처리 된 매물입니다.');
                        $this->db->transComplete();

                        return [
                            'success' => false,
                            'msg' => ' 이미 불일치 처리 된 매물입니다.',
                        ];
                    }
                }

                $fax = $this->getDetail($fax_sq);
                $this->saveV2Confirm($vr_sq, 'D', $success, '1', $fax['charger'], $current_tm, $insert_user, $update_user, $work_type);

                // 2.2 확인정보 체크 v2_check_list
                if (is_array($comment_d11)) {
                    $comment = implode('|', $comment_d11);
                } else {
                    $comment = $comment_d11;
                }

                $this->saveV2CheckList($vr_sq, 'D', 'D11', $result_d11, $comment, $insert_user);

                if ($fax_conf_yn_1 == 'Y') {
                    $fax_conf_yn_1 = '10000';
                } else {
                    $fax_conf_yn_1 = '20000';
                }
                $this->saveV2CheckList($vr_sq, 'D', 'D12', $fax_conf_yn_1, $fax_conf_info_1, $insert_user);

                if ($fax_conf_yn_2 == 'Y') {
                    $fax_conf_yn_2 = '10000';
                } else {
                    $fax_conf_yn_2 = '20000';
                }
                $this->saveV2CheckList($vr_sq, 'D', 'D13', $fax_conf_yn_2, $fax_conf_info_2, $insert_user);

                if ($fax_conf_yn_3 == 'Y') {
                    $fax_conf_yn_3 = '10000';
                } else {
                    $fax_conf_yn_3 = '20000';
                }
                $this->saveV2CheckList($vr_sq, 'D', 'D14', $fax_conf_yn_3, $fax_conf_info_3, $insert_user);


                $this->saveChangedHistory($vr_sq, '35', 'C9', $insert_id, '현장확인 매물');


                $faxModel = new FaxModel();
                $fax = $faxModel->selectFax($fax_sq); // fax 이미지 파일 가져오기
                $receipt = $this->selectReceiptOne($vr_sq);	// 매물정보 가져오기

                // 40: 촬영, 70: 검수지연... 상태가 촬용 이전 또는 검수지연 상태일 경우에만 홍보확인서를 등록한다.
                if (substr($receipt['rcpt_stat'], 0, 2) <= '40' || substr($receipt['rcpt_stat'], 0, 2) == '70') {
                    $arrImagePath = array(
                        '/home/confirms/test-admin.confirms.co.kr/upload/',
                        '/home/confirms/upload/',
                        '/home/www/admin.confirms.co.kr/upload/',
                        '/home/www/upload/',
                        '/image/confirms_upload/',
                        '/misc/image/confirms_upload/',
                        '/storage/web/admin.confirms.co.kr/src/upload/',
                        '/storage/web/admin.confirms.co.kr/upload/',
                        $_SERVER['DOCUMENT_ROOT'] . '/upload/',
                    );

                    $image_path = str_replace($arrImagePath, '/upload/', $fax['file_path']);

                    $receiptModel = new ReceiptModel();
                    $receiptModel->saveFaxImage($fax_sq, $receipt['rcpt_sq'], $receipt['rsrv_sq'], 'I1', $image_path, $fax['file_name'], '.jpg', $fax['img_size'], $fax['img_width'], $fax['img_height'], $receipt);
                }

                break;
            case "2": // 일반확인매물
                $article = $this->getArticleInfo2($atcl_no, $vr_sq);

                $try_cnt = $article['try_cnt'];		// 0 -> 1 차시도, 1 -> 2 차시도
                $try_cnt = $try_cnt + 1;

                //memo 저장
                $this->updateMemo($vr_sq, $memo);
                $stat_cd = "30";	// 전화/서류 확인 중

                if ($result_d11 == '10000' && $fax_conf_yn_1 == 'Y' && $fax_conf_yn_2 == 'Y' && $fax_conf_yn_3 == 'Y') {
                    $success = TRUE;	// 전화/서류 확인 성공
                } else {
                    $success = FALSE;	// 전화/서류 확인 실패

                    $result_tm = $this->getUpdateFailTime($vr_sq);
                    $update_tm = $result_tm['insert_tm'];
                    $ten_ago = date("Y-m-d H:i:s", mktime(date("H"), date("i") - 10, date("s"), date("m"), date("d"), date("Y")));

                    if ($update_tm > $ten_ago) {
                        // 수정한 시간이 현재시간10분전 보다 클 경우 수정불가능

                        // $this->session->set_flashdata('alert', '이미 불일치 처리 된 매물입니다.');
                        $this->db->transComplete();

                        return [
                            'success' => false,
                            'msg' => ' 이미 불일치 처리 된 매물입니다.',
                        ];
                    }
                }

                // 1. 매물정보 저장 fax_imgs
                $this->saveFaxImgs($fax_sq, $work_type, $article['vr_sq'], $article['atcl_no'], $article['cpid'], $article['realtor_nm'], $stat_cd, $current_tm, $article['address_code'], $article['address2']);

                // 2.1 확인결과 저장 v2_confirm
                $fax = $this->getDetail($fax_sq);
                $this->saveV2Confirm($vr_sq, 'D', $success, $try_cnt, $fax['charger'], $current_tm, $insert_user, $update_user, $work_type);

                if (is_array($comment_d11)) {
                    $comment = implode('|', $comment_d11);
                } else {
                    $comment = $comment_d11;
                }

                $this->saveV2CheckList($vr_sq, 'D', 'D11', $result_d11, $comment, $insert_user);

                if ($fax_conf_yn_1 == 'Y') {
                    $fax_conf_yn_1 = '10000';
                } else {
                    $fax_conf_yn_1 = '20000';
                }
                $this->saveV2CheckList($vr_sq, 'D', 'D12', $fax_conf_yn_1, $fax_conf_info_1, $insert_user);

                if ($fax_conf_yn_2 == 'Y') {
                    $fax_conf_yn_2 = '10000';
                } else {
                    $fax_conf_yn_2 = '20000';
                }
                $this->saveV2CheckList($vr_sq, 'D', 'D13', $fax_conf_yn_2, $fax_conf_info_2, $insert_user);

                if ($fax_conf_yn_3 == 'Y') {
                    $fax_conf_yn_3 = '10000';
                } else {
                    $fax_conf_yn_3 = '20000';
                }
                $this->saveV2CheckList($vr_sq, 'D', 'D14', $fax_conf_yn_3, $fax_conf_info_3, $insert_user);

                if ($success == TRUE) {
                    $stat_cd = '35';	// 서류확인완료
                    $this->saveV2ChgStat($vr_sq, $stat_cd, $insert_user);

                    $rgbk_confirm = $this->getRgbk_confirm($vr_sq);
                    if (empty($rgbk_confirm)) {
                        // 등기부등본 확인이 불필요할 경우
                        $stat_cd = '60';	// 등기부등본 확인 중
                        $this->saveV2ChgStat($vr_sq, $stat_cd, $insert_user);
                    } else {
                        // 등기부등본 확인이 필요할 경우
                        if ($this->check_chg_stat49($vr_sq)) {
                            $stat_cd = '40';	// 등기부등본 확인 중
                            $this->saveV2ChgStat($vr_sq, $stat_cd, $insert_user);
                        }

                    }
                } else {
                    $stat_cd = '39';	// 서류확인 불일치
                    $this->saveV2ChgStat($vr_sq, $stat_cd, $insert_user);
                }

                // 3.1 검증요청 상태변경 v2_vrfc_req
                $this->saveV2VrfcReq($vr_sq, $stat_cd);

                // 4. 첨부파일 저장 v2_files
                $pos = strpos($fax['file_name'], '.');
                if ($pos === false) {
                    $file_ext = '';
                } else {
                    $file_ext = substr($fax['file_name'], $pos);
                }
                $this->saveV2Files($vr_sq, $fax['file_path'], $fax['file_name'], $file_ext, $fax['img_size'], $fax['img_width'], $fax['img_height'], $insert_user);

                // 5. 변경이력 저장 v2_chg_history
                $memo = '';
                $this->saveChangedHistory($vr_sq, $stat_cd, 'C9', $insert_id, $memo);

                break;
            default:
                break;
        }

        $this->db->transComplete();

        $return = array(
            'code' => $this->db->_error_number(),
            'message' => $this->db->_error_message(),
        );

        return $return;

    }


    public function getUpdateFailTime($vr_sq)
    {
        $sql = "select vr_sq, stat_cd, insert_user, insert_tm " .
            "from v2_chg_stat " .
            "where vr_sq = ? and stat_cd = '39' " .
            "order by insert_tm desc " .
            "limit 1";
        $data = [$vr_sq];
        $query = $this->db->query($sql, $data);
        $row = $query->getRowArray();

        return $row;

    }


    // 검증결과 저장하기
    public function saveV2Confirm($vr_sq, $vrfc_type, $success, $type, $charger, $date, $insert_user, $update_user, $work_type = '2')
    {
        $insert_user = session('usr_sq');
        $insert_id = session('usr_id');
        $update_user = $insert_user;

        // DB에서 변경되지 전 값을 읽어온다.
        $sql = "select success, vrfc_type, type, charger, date from v2_confirm" .
            " where vr_sq = ?" .
            " and vrfc_type = ?";
        $data = [
            $vr_sq,
            $vrfc_type
        ];
        $query = $this->db->query($sql, $data);
        $data_table = $query->getRowArray();

        $date = str_replace(array(' ', '-', ':'), '', $date);

        $sql = "INSERT INTO v2_confirm" .
            " (vr_sq, vrfc_type, success, type, charger, date, insert_user, insert_tm, update_user, update_tm, work_type)" .
            " VALUES" .
            " (?, ?, ?, ?, ?, ?, ?, now(), ?, now(), ?)" .
            " ON DUPLICATE KEY UPDATE" .
            " success=values(success), type=values(type), charger=values(charger), date=values(date), update_user=values(update_user), update_tm=values(update_tm), work_type=values(work_type)";

        $data = [
            'vr_sq' => $vr_sq,
            'vrfc_type' => $vrfc_type,
            'success' => $success,
            'type' => $type,
            'charger' => $charger,
            'date' => $date,
            'insert_user' => $insert_user,
            'update_user' => $update_user,
            'work_type' => $work_type
        ];


        if (!empty($data_table)) {
            $memo = "검증방식 : " . $data_table['vrfc_type'] . ' => ' . $vrfc_type;
            $this->saveChangedHistory($vr_sq, '30', 'C27', $insert_id, $memo);
        }

    }


    // 확인정보 저장하기
    public function saveV2CheckList($vr_sq, $vrfc_type, $type, $code, $comment, $insert_user)
    {
        $insert_id = session('usr_id');

        $sql = "select code, vrfc_type, comment from v2_check_list" .
            " where vr_sq = ?" .
            " and type = ?";
        $data = [
            $vr_sq,
            $type
        ];
        $query = $this->db->query($sql, $data);
        $data_table = $query->getRowArray();

        $sql = "INSERT INTO v2_check_list" .
            " (vr_sq, vrfc_type, type, code, comment, insert_user, insert_tm)" .
            " VALUES" .
            " (?, ?, ?, ?, ?, ?, now())" .
            " ON DUPLICATE KEY UPDATE" .
            " vr_sq=values(vr_sq), vrfc_type=values(vrfc_type), type=values(type), code=values(code), comment=values(comment), insert_user=values(insert_user), insert_tm=values(insert_tm)";
        $data = [
            'vr_sq' => $vr_sq,
            'vrfc_type' => $vrfc_type,
            'type' => $type,
            'code' => $code,
            'comment' => $comment,
            'insert_user' => $insert_user
        ];

        $this->db->query($sql, $data);

        if (!empty($data_table)) {
            $memo = "검증방식 : " . $data_table['vrfc_type'] . ' => ' . $vrfc_type;
            $this->saveChangedHistory($vr_sq, '30', 'C27', $insert_id, $memo);
        }
    }

    // FAX 내용중 하나만 가져오기
    public function selectFax($faxSq)
    {
        $sql = "SELECT mid, caller_no, recv_time, fax_sq, file_path, file_name, thumbnail, img_width, img_height, img_size" .
            " FROM fax_imgs" .
            " WHERE fax_sq = ?";
        $data = [$faxSq];
        $query = $this->db->query($sql, $data);
        return $query->getRowArray();
    }

    // receipt 에서 지정한 1건만 가져온다.
    public function selectReceiptOne($rcpt_sq)
    {
        $sql = "SELECT a.rcpt_sq,a.comp_sq,a.rcpt_rating,a.rcpt_key,a.rcpt_atclno,a.rcpt_type,a.rcpt_product,a.rcpt_product_nm,a.rcpt_product_area,a.rcpt_product_price,a.rcpt_product_info1,a.rcpt_product_info2,a.rcpt_product_info3,a.rcpt_product_info4,a.rcpt_product_info5,a.rcpt_office,a.rcpt_agent,a.rcpt_sido,a.rcpt_gugun,a.rcpt_dong,a.rcpt_hscp_nm,a.rcpt_dtl_addr,a.rcpt_floor,a.rcpt_bunji,a.rcpt_ho,a.rcpt_tm,a.rcpt_stat,a.rcpt_x,a.rcpt_y,a.rcpt_living_yn,a.cust_nm,a.cust_tel1,a.cust_tel2,a.cust_zip,a.cust_addr1,a.cust_addr2,a.remark,a.agent_id,a.agent_nm,a.agent_head,a.agent_head_tel,a.agent_contact,a.agent_contact_tel,a.agent_fax,a.rsrv_date,a.rsrv_tm_ap,a.insert_usr,a.insert_tm,a.update_usr,a.update_tm,a.svc_type1,a.svc_type2,a.reconf_yn,a.rcpt_exps_type" .
            ", b.region_nm" .
            ", c.rsrv_sq" .
            " FROM receipt a" .
            " LEFT JOIN region_codes b ON b.region_cd = a.rcpt_dong" .
            " LEFT JOIN result c on c.rcpt_sq = a.rcpt_sq" .
            " WHERE a.rcpt_sq = ?" .
            " limit 1";
        $data = [$rcpt_sq];
        $query = $this->db->query($sql, $data);

        return $query->getRowArray();
    }

    // 메모저장
    public function updateMemo($vr_sq, $memo)
    {
        $sql = "UPDATE v2_vrfc_req" .
            " SET memo = ? " .
            " WHERE vr_sq = ?";

        $data = [
            $memo,
            $vr_sq
        ];

        $res = $this->db->query($sql, $data);
    }

    /**
     * 검증요청 v2_vrfc_req의 상태 stat_cd를 업데이트한다.
     */
    public function saveV2VrfcReq($vr_sq, $stat_cd)
    {

        $sql = "update v2_vrfc_req" .
            " set stat_cd = ?" .
            " where vr_sq = ?";
        $data = [$stat_cd, $vr_sq];

        $res = $this->db->query($sql, $data);
        log_message('debug', $this->db->getLastQuery());
        log_message('debug', $res);
    }

    /**
     * 상태변경시간 등록
     */
    public function saveV2ChgStat($vr_sq, $stat_cd, $insert_user)
    {
        $sql = "INSERT INTO v2_chg_stat" .
            " (vr_sq, stat_cd, insert_user, insert_tm)" .
            " VALUES" .
            " (?, ?, ?, now())" .
            " ON DUPLICATE KEY UPDATE" .
            " insert_user=VALUES(insert_user), insert_tm=VALUES(insert_tm)";
        $data = [$vr_sq, $stat_cd, $insert_user];
        $this->db->query($sql, $data);
        log_message('debug', $this->db->getLastQuery());
    }

    /**
     * 홍보확인서를 매물정보에 등록한다.
     */
    public function saveV2Files($vr_sq, $file_path, $file_name, $file_ext, $file_size, $img_width, $img_height, $insert_user)
    {
        $arrImagePath = [
            '/home/confirms/test-admin.confirms.co.kr/upload/',
            '/home/confirms/upload/',
            '/home/www/admin.confirms.co.kr/upload/',
            '/home/www/upload/',
            '/image/confirms_upload/',
            '/misc/image/confirms_upload/',
            '/storage/web/admin.confirms.co.kr/src/upload/',
            '/storage/web/admin.confirms.co.kr/upload/',
            $_SERVER['DOCUMENT_ROOT'] . '/upload/',
        ];

        $file_path = str_replace($arrImagePath, '/upload/', $file_path);
        $file_type = '1'; // 홍보확인서

        // 1. 홍보확이서 등록여부 확인
        $sql = "SELECT count(*) file_cnt FROM v2_files" .
            " WHERE vr_sq = ?" .
            " AND file_type = ?" .
            " AND file_path = ?" .
            " AND file_name = ?" .
            " AND use_yn = 'Y'";
        $data = [
            $vr_sq,
            $file_type,
            $file_path,
            $file_name
        ];

        $query = $this->db->query($sql, $data);
        $row = $query->getRowArray();

        if (empty($row['file_cnt'])) {
            // 2. 다른파일로 등록된 경우를 위해서 업데이트
            $sql = "UPDATE v2_files SET use_yn = 'N' WHERE vr_sq = ? AND file_type = ?";
            $data = [$vr_sq, $file_type];
            $this->db->query($sql, $data);

            // 3. 등록
            $sql = "INSERT INTO v2_files " .
                " (vr_sq, use_yn, file_type, view_odr, file_path, file_name, file_ext, file_size, img_width, img_height, insert_user, insert_tm)" .
                " VALUES" .
                " (?, 'Y', ?, '1', ?, ?, ?, ?, ?, ?, ?, NOW())";

            $data = [$vr_sq, $file_type, $file_path, $file_name, $file_ext, $file_size, $img_width, $img_height, $insert_user];
            $this->db->query($sql, $data);
        }

    }


    /**
     * 담당자를 지정해준다.
     */
    public function InsCharger($vr_sq)
    {
        $usr_id = session('usr_id');

        $sql = "UPDATE v2_article_info" .
            " SET charger = ?" .
            " WHERE vr_sq = ?";

        $data = [
            $usr_id,
            $vr_sq
        ];

        $res = $this->db->query($sql, $data);
    }


    /**
     * 검증결과 전송 API를 위한 데이터 조회..
     */
    public function getDataConfirmAPI($vr_sq)
    {
        // 요청정보
        $sql = "SELECT vr_sq, atcl_no, step, cpid, cp_atcl_id, trade_type, realtor_nm, realtor_tel_no, seller_tel_no, vrfc_type, rgbk_confirm, req_type, rdate, stat_cd, try_cnt, insert_user, insert_tm" .
            " FROM v2_vrfc_req where vr_sq = ?";
        $data = [$vr_sq];
        $query = $this->db->query($sql, $data);
        $row_vrfc_req = $query->getRowArray();

        log_message('debug', $this->db->getLastQuery());

        // 매물정보
        $sql = "SELECT vr_sq, atcl_no, cpid, cp_atcl_id, rlet_type_cd, trade_type, address_code, address1, address2, address3, sply_spc, excls_spc, tot_spc, grnd_spc, bldg_spc, deal_amt, wrrnt_amt, lease_amt, isale_amt, prem_amt, sise, floor, rdate, seller_tel_no, seller_nm, realtor_nm, realtor_tel_no, hscp_no, hscp_nm, ptp_no, ptp_nm, charger, req_price_yn, reg_charger, dept1_sq, dept2_sq, reg_dept1_sq, reg_dept2_sq, floor2" .
            " FROM v2_article_info where vr_sq = ?";
        $data = [$vr_sq];
        $query = $this->db->query($sql, $data);
        $row_article_info = $query->getRowArray();

        log_message('debug', $this->db->getLastQuery());

        // 수정정보
        //$sql = "SELECT vr_sq, bildNo, bild_nm, rm_no, floor, address_code, address2, address3, address4, trade_type, deal_amt, wrrnt_amt, lease_amt, isale_amt, prem_amt, sply_spc, excls_spc, tot_spc, grnd_spc, bldg_spc, hscp_no, hscp_nm, ptp_no, ptp_nm, modify_yn, floor2 FROM v2_modify_info where vr_sq = ?";
        $sql = "SELECT vr_sq, bild_nm, rm_no, floor, address_code, address2, address3, address4, trade_type, deal_amt, wrrnt_amt, lease_amt, isale_amt, prem_amt, sply_spc, excls_spc, tot_spc, grnd_spc, bldg_spc, hscp_no, hscp_nm, ptp_no, ptp_nm, modify_yn, floor2 FROM v2_modify_info where vr_sq = ?";
        $data = [$vr_sq];
        $query = $this->db->query($sql, $data);
        $row_modify_info = $query->getRowArray();

        log_message('debug', $this->db->getLastQuery());

        // 검증결과
        $sql = "SELECT vr_sq, vrfc_type, success, type, charger, date, insert_user, insert_tm, update_user, update_tm, work_type" .
            " FROM v2_confirm where vr_sq = ? and vrfc_type = ?";
        $data = [$vr_sq, $row_vrfc_req['vrfc_type']];
        $query = $this->db->query($sql, $data);
        $row_confirm = $query->getRowArray();

        log_message('debug', $this->db->getLastQuery());

        // 확인정보
        $sql = "SELECT type, code, comment, ownerNm, ownerBirth FROM v2_check_list where vr_sq = ? and vrfc_type = ? and type like concat(vrfc_type, '%')";
        $data = [$vr_sq, $row_vrfc_req['vrfc_type']];
        $query = $this->db->query($sql, $data);
        $res_check_list = $query->getResultArray();

        log_message('debug', $this->db->getLastQuery());

        log_message('debug', implode(', ', $row_confirm));

        $atclNo = $row_vrfc_req['atcl_no'];
        $success = empty($row_confirm['success']) ? FALSE : TRUE;
        $charger = $row_confirm['charger'];
        $date = $row_confirm['date'];
        $try_cnt = $row_vrfc_req['try_cnt'];

        $checkList = [];
        foreach ($res_check_list as $row) {
            $checkList[] = [
                'type' => $row['type'],
                'code' => $row['code'],
                'comment' => $row['comment'],
                'ownerNm' => $row['ownerNm'],
                'ownerBirth' => $row['ownerBirth'],
            ];
        }

        $modifyInfo = [];
        if ($row_modify_info['modify_yn'] == 'Y') {
            if (!empty($row_modify_info['hscp_no'])) {
                // 공동주택
                $modifyInfo = [
                    'hscpNo' => $row_modify_info['hscp_no'],
                    'ptpNo' => $row_modify_info['ptp_no'],
                    'bildNm' => $row_modify_info['address2'],
                    'rmNo' => $row_modify_info['address3'],
                    'tradeType' => $row_modify_info['trade_type'],
                    'dealAmt' => $row_modify_info['deal_amt'],
                    'wrrntAmt' => $row_modify_info['wrrnt_amt'],
                    'leaseAmt' => $row_modify_info['lease_amt'],
                    'isaleAmt' => $row_modify_info['isale_amt'],
                    'premAmt' => $row_modify_info['prem_amt'],
                    'floor' => $row_modify_info['floor'],
                ];
            } else {
                // 비공동주택
                $modifyInfo = [
                    'addressCode' => $row_modify_info['address_code'],
                    'address2' => $row_modify_info['address2'],
                    'address3' => $row_modify_info['address3'],
                    'tradeType' => $row_modify_info['trade_type'],
                    'dealAmt' => $row_modify_info['deal_amt'],
                    'wrrntAmt' => $row_modify_info['wrrnt_amt'],
                    'leaseAmt' => $row_modify_info['lease_amt'],
                    'splySpc' => $row_modify_info['sply_spc'],
                    'exclsSpc' => $row_modify_info['excls_spc'],
                    'totSpc' => $row_modify_info['tot_spc'],
                    'grndSpc' => $row_modify_info['grnd_spc'],
                    'bldgSpc' => $row_modify_info['bldg_spc'],
                    'floor' => $row_modify_info['floor'],
                    'floor2' => $row_modify_info['floor2'],
                ];
            }

            return [
                'atclNo' => $atclNo,
                'success' => $success,
                'checkList' => $checkList,
                'charger' => $charger,
                'modifyInfo' => $modifyInfo,
                'date' => $date,
                'try_cnt' => $try_cnt,
            ];
        } else {
            return [
                'atclNo' => $atclNo,
                'success' => $success,
                'checkList' => $checkList,
                'charger' => $charger,
                'date' => $date,
                'try_cnt' => $try_cnt,
            ];
        }

    }

    /**
     * 값을 실패횟수 값을 증가시킨다.
     */
    public function increseTryCnt($vr_sq)
    {
        $sql = "update v2_vrfc_req set try_cnt = ifnull(try_cnt,0) +1 where vr_sq = ?";
        $data = [$vr_sq];
        $this->db->query($sql, $data);
    }

    /**
     * 일자별 통계데이터에 값 집어 넣기...
     * 반환값 없음.
     * @param date $sd_date 날짜 값이 없을경우 현재날짜로 입력됨.
     * @param string $cpid CPID
     * @param string $gbn_cd 코드값 (category='STATISTICS_DAILY3')
     * @param int $cnt 더할 숫자..
     * @param string $cnt_type 숫자를 더할것인지.. 아니변 변경할것인지.
     */
    public function set_v2_st_daily($st_date, $cpid, $gbn_cd, $cnt, $cnt_type = 'add')
    {
        /**
         * insert into v2_st_daily (sd_date, cpid, gbn_cd, cnt) values ($sd_date, $cpid, $gbn_cd, $cnt) 
         * on duplicate key update cnt = values(cnt);			// $cnt_type='change'
         * on duplicate key update cnt = cnt + $cnt;	// $cnt_type='add'
         */
        if (empty($cnt))
            $cnt = '0';

        $sql_dup = "";
        switch (strtolower($cnt_type)) {
            case 'add':
                $sql_dup = "on duplicate key update cnt = cnt + " . $cnt;
                break;

            case 'change':
                $sql_dup = "on duplicate key update cnt = values(cnt)";
                break;
        }
        if (empty($st_date)) {
            $sql = "insert into v2_st_daily (st_date, cpid, gbn_cd, cnt) values (now(), ?, ?, ?)" . $sql_dup;
            $data = [
                $cpid,
                $gbn_cd,
                $cnt
            ];
        } else {
            $sql = "insert into v2_st_daily (st_date, cpid, gbn_cd, cnt) values (?, ?, ?, ?)" . $sql_dup;
            $data = [
                $st_date,
                $cpid,
                $gbn_cd,
                $cnt
            ];
        }
        $this->db->query($sql, $data);

        $return['error_number'] = $this->db->_error_number();
        $return['error_message'] = $this->db->_error_message();

        return $return;
    }

    /**
     * 지정한 매물의 요청번호를 이용하여 요청내역을 가져온다.
     */
    public function get_v2_vrfc_req($vr_sq)
    {
        $sql = "SELECT 
                    vr_sq,atcl_no,step,cpid,cp_atcl_id,trade_type,realtor_nm,realtor_tel_no,seller_tel_no,vrfc_type,rgbk_confirm,req_type,rdate,stat_cd,try_cnt,insert_user,insert_tm,memo,contact_fail_cnt,sync_yn,reg_try_cnt
                FROM v2_vrfc_req
                WHERE vr_sq = ?    
                ";

        $query = $this->db->query($sql, [$vr_sq]);

        return $query->getRowArray();
    }

    /**
     * 상태를 변경한다.
     */
    public function saveChangeStep($fax_sq, $vr_sq, $stat_cd)
    {
        $insert_user = session('usr_sq');
        $insert_id = session('usr_id');

        $this->db->transStart();

        // 1. 검증요청 상태변경 v2_vrfc_req
        $this->saveV2VrfcReq($vr_sq, $stat_cd);

        // 2. 상태변경 저장 v2_chg_stat
        $this->saveV2ChgStat($vr_sq, $stat_cd, $insert_user);

        // 3. 변경이력 저장 v2_chg_history
        $this->saveChangedHistory($vr_sq, $stat_cd, 'C9', $insert_id, "");

        // 4. FAX에 최종 저장시 상태값 저장
        $this->saveFaxImgsAfterSend($fax_sq, $vr_sq, $stat_cd, $send_tm = '');

        $this->db->transComplete();

        $return = array(
            'code' => $this->db->_error_number(),
            'message' => $this->db->_error_message(),
        );

        return $return;
    }

    public function getRgbk_confirm($vr_sq)
    {
        $sql = "SELECT rgbk_confirm FROM v2_vrfc_req WHERE vr_sq = ?";
        $data = [$vr_sq];
        $query = $this->db->query($sql, $data);
        $row = $query->getRowArray();
        return $row['rgbk_confirm'];
    }

    public function check_chg_stat49($vr_sq)
    {
        $sql = "SELECT vr_sq FROM v2_chg_stat WHERE vr_sq = ? AND stat_cd = '49' LIMIT 1";

        // 쿼리 실행 및 vr_sq 값을 바인딩 배열로 전달
        $query = $this->db->query($sql, [$vr_sq]);

        // 결과 행의 개수가 0보다 크면 TRUE (존재함)
        if (($query->getNumRows() > 0) == true) {
            return true;
        } else {
            return false;
        }
    }

    public function saveApiErr($err_sq, $err_code, $err_nm, $err_time, $err_no, $err_server = '')
    {

        $sql = "INSERT INTO err_api (err_sq, err_code, err_nm, err_time, err_no, err_server)" .
            " VALUES (?, ?, ?, ?, ?, ?);";

        $data = [
            $err_sq,
            $err_code,
            $err_nm,
            $err_time,
            $err_no,
            $err_server
        ];
        $res = $this->db->query($sql, $data);
    }

    // 홍보확인서 확인
    public function getOneFax()
    {
        $this->db->transStart();

        $usr_id = session('usr_id');
        $usr_sq = session('usr_sq');
        $h_y = $this->get_send_yn('H');

        $sql = "SELECT 
                    a.fax_sq, a.mid, a.file_name, a.file_path, a.thumbnail, a.img_width, a.img_height, a.img_size, a.img_sq, a.remark, a.work_type, a.atcl_no, a.cpid, a.realtor_nm, a.stat_cd, a.proc_tm, a.send_tm, a.address_code, a.address2, a.charger, a.reg_charger
                FROM     
                    fax_imgs a
                WHERE 
                    a.recv_time > DATE_ADD(NOW(), INTERVAL -7 DAY)
                    AND a.stat_cd = '10'
                    AND not exists ( SELECT 'x' from v2_vrfc_req v2 where a.vr_sq = v2.vr_sq AND v2.stat_cd = '40' )
                ";

        if ($h_y['stop_yn'] != 'N') {
            $sql .= "AND a.recv_time < date_format(curdate( ), '%Y-%m-%d 17:30:00') ";
        }

        $sql .= "AND a.fax_sq > '' ";

        $sql .= "ORDER BY a.fax_sq ASC LIMIT 1 FOR UPDATE SKIP LOCKED ";

        $query = $this->db->query($sql);
        $row = $query->getRowArray();

        $row_dept = $this->getDepartmentPath($usr_sq);
        $dept1_sq = '';
        $dept2_sq = '';
        if (!empty($row_dept)) {
            $dept1_sq = $row_dept['dept1_sq'];
            $dept2_sq = $row_dept['dept2_sq'];
        }

        if (!empty($row)) {
            $sql = "UPDATE fax_imgs SET 
                    stat_cd = '20', charger = '{$usr_id}', dept1_sq = '{$dept1_sq}', dept2_sq = '{$dept2_sq}'
                    WHERE fax_sq = {$row['fax_sq']}
                    ";

            $this->db->query($sql);
        }

        $this->db->transComplete();

        return $row;
    }
}