<?php
namespace App\Models\v2;

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

class M704Model 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
                    v2_article_info a
                JOIN v2_vrfc_req b FORCE INDEX (insert_tm) ON a.vr_sq = b.vr_sq
                JOIN v2_modify_info c ON a.vr_sq = c.vr_sq
                JOIN v2_article_info_etc c1 ON c1.vr_sq = a.vr_sq
                LEFT JOIN region_codes f ON a.address_code = f.region_cd
                LEFT JOIN v2_chg_stat d ON a.vr_sq = d.vr_sq AND d.stat_cd = 35
                LEFT JOIN v2_chg_stat e ON a.vr_sq = e.vr_sq AND e.stat_cd = 60
                LEFT JOIN codes g ON b.stat_cd = g.cd AND g.category = 'STEP_VERIFICATION'
                LEFT JOIN codes h ON b.vrfc_type = h.cd AND h.category = 'VRFCREQ_WAY'
                LEFT JOIN users i ON a.charger = i.usr_id
                LEFT JOIN users j ON a.reg_charger = j.usr_id
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = 39 ";

        if (!empty($data['stat_complete_date'])) {
            $sql .= "LEFT JOIN v2_chg_stat z1 ON z1.vr_sq = a.vr_sq AND z1.stat_cd = '{$data['stat_complete_date']}' ";
        }

        $sql .= "WHERE 
                    1=1
                    AND b.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -2 MONTH) ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND b.stat_cd = '{$data['stat_cd']}' ";
            }

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

            // 매물구분
            if (!empty($data['rlet_type_cd'])) {
                $sql .= "AND a.rlet_type_cd = '{$data['rlet_type_cd']}' ";
            }


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

            if (!empty($data['receipt_edate'])) {
                $sql .= "AND b.insert_tm <= '{$data['receipt_edate']} 23:59:59' ";
            }

            // 진행상태별시간
            if (!empty($data['stat_complete_date'])) {
                if (!empty($data['complete_sdate'])) {
                    $sql .= "AND z1.insert_tm >= '{$data['complete_sdate']} 00:00:00' ";
                }

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

            // 검증방식
            if (!empty($data['vrfcreq_way'])) {
                $sql .= "AND b.vrfc_type = '{$data['vrfcreq_way']}' ";
            }

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

            // 지역구분
            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']}' ";
                }
            }

        }

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


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

    public function getResultList($start, $end, $data)
    {
        $sql = "SELECT
                    a.vr_sq,
					a.atcl_no,
					a.cpid,
					a.cp_atcl_id,
					a.rlet_type_cd,
					a.address1,
					a.sise,
					a.rdate,
					a.seller_tel_no,
					a.seller_nm,
					a.realtor_nm,
					a.realtor_tel_no,
					a.rlet_type_cd,
					a.charger,
					b.insert_tm,
					b.tel_fail_cause,
					b.stat_cd,
					c.bild_nm,
					b.contact_fail_cnt,
					b.vrfc_type,
					b.memo,
					c.rm_no,
					c.floor,
					c.address_code,
					c.address2,
                    c1.address2a,
                    c1.address2b,
					c.address3,
					c.trade_type,
					c.deal_amt,
					c.wrrnt_amt,
					c.lease_amt,
					c.isale_amt,
					c.prem_amt,
					c.sply_spc,
					c.excls_spc,
					c.tot_spc,
					c.grnd_spc,
					c.bldg_spc,
					c.hscp_no,
					c.ptp_no,
					d.insert_tm as update_res_tm,
					e.insert_tm as result_tm,
					f.region_nm,
					g.cd_nm as pre_stat,
					h.cd_nm as vrfc_type,
					i.usr_nm,
					j.usr_nm as reg_charger,
					d2.insert_tm as stat_39_tm
                FROM
                    v2_article_info a
                JOIN v2_vrfc_req b FORCE INDEX (insert_tm) ON a.vr_sq = b.vr_sq
                JOIN v2_modify_info c ON a.vr_sq = c.vr_sq
                JOIN v2_article_info_etc c1 ON c1.vr_sq = a.vr_sq
                LEFT JOIN region_codes f ON a.address_code = f.region_cd
                LEFT JOIN v2_chg_stat d ON a.vr_sq = d.vr_sq AND d.stat_cd = 35
                LEFT JOIN v2_chg_stat e ON a.vr_sq = e.vr_sq AND e.stat_cd = 60
                LEFT JOIN codes g ON b.stat_cd = g.cd AND g.category = 'STEP_VERIFICATION'
                LEFT JOIN codes h ON b.vrfc_type = h.cd AND h.category = 'VRFCREQ_WAY'
                LEFT JOIN users i ON a.charger = i.usr_id
                LEFT JOIN users j ON a.reg_charger = j.usr_id
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = 39 ";

        if (!empty($data['stat_complete_date'])) {
            $sql .= "LEFT JOIN v2_chg_stat z1 ON z1.vr_sq = a.vr_sq AND z1.stat_cd = '{$data['stat_complete_date']}' ";
        }


        $sql .= "WHERE 
                    1=1
                    AND b.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -2 MONTH) ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND b.stat_cd = '{$data['stat_cd']}' ";
            }

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

            // 매물구분
            if (!empty($data['rlet_type_cd'])) {
                $sql .= "AND a.rlet_type_cd = '{$data['rlet_type_cd']}' ";
            }


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

            if (!empty($data['receipt_edate'])) {
                $sql .= "AND b.insert_tm <= '{$data['receipt_edate']} 23:59:59' ";
            }

            // 진행상태별시간
            if (!empty($data['stat_complete_date'])) {
                if (!empty($data['complete_sdate'])) {
                    $sql .= "AND z1.insert_tm >= '{$data['complete_sdate']} 00:00:00' ";
                }

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


            // 검증방식
            if (!empty($data['vrfcreq_way'])) {
                $sql .= "AND b.vrfc_type = '{$data['vrfcreq_way']}' ";
            }

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

            // 지역구분
            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']}' ";
                }
            }

        }

        $sql .= "ORDER BY b.vr_sq DESC, b.insert_tm DESC ";

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

        // print ($sql);

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

        return $query->getResultArray();
    }


    // 엑셀다운로드
    public function getExcelList($data)
    {
        $sql = "SELECT
                    a.atcl_no AS '매물번호'
                    , g.cd_nm AS '진행상태'
                    , CASE WHEN b.tel_fail_cause IS NULL THEN '관련없음' ELSE 
	                    (SELECT cd_nm FROM codes WHERE category = 'TEL_FAIL_CAUSE' AND cd = b.tel_fail_cause) END AS '중개업소 어뷰징 의심'
                    , b.contact_fail_cnt AS '통화실패횟수'
                    , a.seller_tel_no AS '의뢰인(매도자) 전화번호'
                    , b.insert_tm AS '접수시간'
                    , h.cd_nm AS '검증방식'
                    , CONCAT(f.region_nm, ' ', c.rm_no) AS '주소'
                    , CONCAT(c.address2, ' ', c.address3) AS '상세주소'
                    , a.cpid AS '매체사'
                    , a.realtor_nm AS '중개소'
                    , IFNULL(d.insert_tm, d2.insert_tm) AS '서류/전화 확인시간'
                    , i.usr_nm AS '담당자'
                    , e.insert_tm AS '검증완료일시'
                    , b.memo AS '메모'
                FROM
                    v2_article_info a
                JOIN v2_vrfc_req b FORCE INDEX (insert_tm) ON a.vr_sq = b.vr_sq
                JOIN v2_modify_info c ON a.vr_sq = c.vr_sq
                JOIN v2_article_info_etc c1 ON c1.vr_sq = a.vr_sq
                LEFT JOIN region_codes f ON a.address_code = f.region_cd
                LEFT JOIN v2_chg_stat d ON a.vr_sq = d.vr_sq AND d.stat_cd = 35
                LEFT JOIN v2_chg_stat e ON a.vr_sq = e.vr_sq AND e.stat_cd = 60
                LEFT JOIN codes g ON b.stat_cd = g.cd AND g.category = 'STEP_VERIFICATION'
                LEFT JOIN codes h ON b.vrfc_type = h.cd AND h.category = 'VRFCREQ_WAY'
                LEFT JOIN users i ON a.charger = i.usr_id
                LEFT JOIN users j ON a.reg_charger = j.usr_id
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = 39 ";

        if (!empty($data['stat_complete_date'])) {
            $sql .= "LEFT JOIN v2_chg_stat z1 ON z1.vr_sq = a.vr_sq AND z1.stat_cd = '{$data['stat_complete_date']}' ";
        }


        $sql .= "WHERE 
                    1=1
                    AND b.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -2 MONTH) ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND b.stat_cd = '{$data['stat_cd']}' ";
            }

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

            // 매물구분
            if (!empty($data['rlet_type_cd'])) {
                $sql .= "AND a.rlet_type_cd = '{$data['rlet_type_cd']}' ";
            }


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

            if (!empty($data['receipt_edate'])) {
                $sql .= "AND b.insert_tm <= '{$data['receipt_edate']} 23:59:59' ";
            }

            // 진행상태별시간
            if (!empty($data['stat_complete_date'])) {
                if (!empty($data['complete_sdate'])) {
                    $sql .= "AND z1.insert_tm >= '{$data['complete_sdate']} 00:00:00' ";
                }

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


            // 검증방식
            if (!empty($data['vrfcreq_way'])) {
                $sql .= "AND b.vrfc_type = '{$data['vrfcreq_way']}' ";
            }

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

            // 지역구분
            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']}' ";
                }
            }

        }

        $sql .= "ORDER BY b.vr_sq DESC, b.insert_tm DESC ";

        // print ($sql);

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

        return $query->getResultArray();
    }


    // 상세내용 조회
    public function getDetail($vr_sq)
    {
        $sql = "SELECT
                    a.vr_sq,
					b.tel_fail_cause,
					a.atcl_no,
					a.cpid,
					a.cp_atcl_id,
					a.rlet_type_cd,
					a.address1,
					b.try_cnt,
					b.reg_try_cnt,
					a.sise,
					a.rdate,
					a.seller_tel_no,
					a.seller_nm,
					a.realtor_nm,
					a.realtor_tel_no,
					a.charger,
					a.chg_trade_type,
					a.chg_address2,
					a.chg_address3,
					a.chg_seller_tel,
					a.chg_amt,
					b.stat_cd,
					b.insert_tm,
					b.contact_fail_cnt,
					a.reg_charger,
					i2.usr_nm as reg_charger_nm,
					c.bild_nm,
					b.vrfc_type as vrfc_type_cd,
					b.memo,
					b.req_type,
					c.rm_no,
					c.floor,
					c.floor2,
					c.address_code,
					c.address2,
                    c1.address2a,
                    c1.address2b,
					c.address3,
					c.address4,
					c.trade_type as trade_type_cd,
					c.deal_amt,
					c.wrrnt_amt,
					c.lease_amt,
					c.isale_amt,
					c.prem_amt,
					c.sply_spc,
					c.excls_spc,
					c.tot_spc,
					c.grnd_spc,
					c.bldg_spc,
					c.hscp_no,
					c.ptp_no,
					d.insert_tm as update_res_tm,
					e.insert_tm as result_tm,
					f.region_nm,
					g.cd_nm as pre_stat,
					g.cd as pre_stat_cd,
					h.cd_nm as vrfc_type,
					i.usr_nm,
					j.cd_nm as trade_type,
					c.hscp_nm, 
					c.ptp_nm,
					l.success,
					k.cd_nm as atcl_nm,
					m.code as result_d11,
					m.comment,
					n.code as fax_conf_yn_2,
					o.code as fax_conf_yn_3,
					p.code as fax_conf_yn_4,
					n.comment as fax_conf_yn_info_2,
					o.comment as fax_conf_yn_info_3,
					p.comment as fax_conf_yn_info_4,
					v.success AS tel_suc, 
					r.code AS tel_agree,
					s.code AS tel_conf_yn_2, 
					t.code AS tel_conf_yn_3, 
					u.code AS tel_conf_yn_4,
					z.code AS tel_conf_yn_5,
					s.comment AS tel_conf_yn_info_2, 
					t.comment AS tel_conf_yn_info_3,
					u.comment AS tel_conf_yn_info_4,
					w.success AS reg_conf_yn_1,
					x.code AS reg_conf_yn_2,
					y.code AS reg_conf_yn_3,
					x.comment AS reg_conf_yn_info_2,
					y.comment AS reg_conf_yn_info_3,
					b.rgbk_confirm,
					c1.vir_addr_yn,
					a.ownerNm
                FROM v2_article_info a
                JOIN v2_vrfc_req b ON a.vr_sq = b.vr_sq
                JOIN v2_modify_info c ON a.vr_sq = c.vr_sq
                JOIN v2_article_info_etc c1 ON c1.vr_sq = a.vr_sq
                LEFT JOIN region_codes f ON a.address_code = f.region_cd
                LEFT JOIN v2_chg_stat d ON a.vr_sq = d.vr_sq AND d.stat_cd = 35
                LEFT JOIN v2_chg_stat e ON a.vr_sq = e.vr_sq AND e.stat_cd = 60
                LEFT JOIN codes g ON b.stat_cd = g.cd AND g.category = 'STEP_VERIFICATION'
                LEFT JOIN codes h ON b.vrfc_type = h.cd AND h.category = 'VRFCREQ_WAY'
                LEFT JOIN codes j ON c.trade_type = j.cd AND j.category = 'TRADE_TYPE'
                LEFT JOIN codes k ON a.rlet_type_cd = k.cd AND k.category = 'ARTICLE_TYPE'
                LEFT JOIN v2_confirm l ON a.vr_sq = l.vr_sq AND l.vrfc_type = 'D'
                LEFT JOIN v2_check_list m ON a.vr_sq = m.vr_sq AND m.type = 'D11'
                LEFT JOIN v2_check_list n ON a.vr_sq = n.vr_sq AND n.type = 'D12'
                LEFT JOIN v2_check_list o ON a.vr_sq = o.vr_sq AND o.type = 'D13'
                LEFT JOIN v2_check_list p ON a.vr_sq = p.vr_sq AND p.type = 'D14'
                LEFT JOIN v2_confirm v ON a.vr_sq = v.vr_sq AND v.vrfc_type = 'T'
                LEFT JOIN v2_check_list r ON a.vr_sq = r.vr_sq AND r.type = 'T11'
                LEFT JOIN v2_check_list s ON a.vr_sq = s.vr_sq AND s.type = 'T12'
                LEFT JOIN v2_check_list t ON a.vr_sq = t.vr_sq AND t.type = 'T13'
                LEFT JOIN v2_check_list u ON a.vr_sq = u.vr_sq AND u.type = 'T14'
                LEFT JOIN v2_check_list z ON a.vr_sq = z.vr_sq AND z.type = 'T15'
                LEFT JOIN v2_confirm w ON a.vr_sq = w.vr_sq AND w.vrfc_type = 'R'
                LEFT JOIN v2_check_list x ON a.vr_sq = x.vr_sq AND x.type = '21'
                LEFT JOIN v2_check_list y ON a.vr_sq = y.vr_sq AND y.type = '22'
                LEFT JOIN users i ON a.charger = i.usr_id
                LEFT JOIN users i2 ON a.reg_charger = i2.usr_id
                    
                WHERE a.vr_sq = " . $vr_sq;


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

        return $query->getRowArray();
    }

    /* 매물정보를 수정 */
    //public function saveModifyInfo($atcl_vr_sq, $atcl_hscp_nm, $atcl_ptp_nm, $atcl_vrfc_type, $trade_type, $atcl_addr1, $atcl_addr1a, $atcl_addr1b, $atcl_addr2, $atcl_hscp_no, $atcl_ptp_no, $atcl_amt1, $atcl_amt2, $atcl_amt3, $atcl_floor, $atcl_floor2, $atcl_amt4, $isale_amt, $prem_amt){
    public function saveModifyInfo($atcl_vr_sq, $atcl_hscp_nm, $atcl_ptp_nm, $atcl_vrfc_type, $trade_type, $atcl_addr1, $atcl_addr1a, $atcl_addr1b, $atcl_addr2, $atcl_hscp_no, $atcl_ptp_no, $atcl_amt1, $atcl_amt2, $atcl_amt3, $atcl_floor, $atcl_floor2, $atcl_amt4, $isale_amt, $prem_amt)
    {
        $usr_id = session('usr_id');

        $list = $this->getDetail($atcl_vr_sq); // 변경된 내용 비교를 위해.

        if ($trade_type != 'B2') {
            // 월세가 아닐경우에는 월세가에 0으로 ....
            $atcl_amt3 = '0';
            $data['lease_amt'] = $atcl_amt3;
        }

        $data = [];
        if (!empty($trade_type))
            $data['trade_type'] = $trade_type;
        if (!empty($atcl_hscp_nm))
            $data['hscp_nm'] = $atcl_hscp_nm;
        if (!empty($atcl_ptp_nm))
            $data['ptp_nm'] = $atcl_ptp_nm;
        if (!empty($atcl_addr1))
            $data['address2'] = $atcl_addr1;  // 폐기 예정
        if (!empty($atcl_addr1a))
            $data['address2a'] = $atcl_addr1a;
        if (!empty($atcl_addr1b))
            $data['address2b'] = $atcl_addr1b;
        if (!empty($atcl_addr2))
            $data['address3'] = $atcl_addr2;
        if (!empty($atcl_hscp_no))
            $data['hscp_no'] = $atcl_hscp_no;
        if (!empty($atcl_ptp_no))
            $data['ptp_no'] = $atcl_ptp_no;
        if (!empty($atcl_amt1))
            $data['deal_amt'] = $atcl_amt1;
        if (!empty($atcl_amt2))
            $data['wrrnt_amt'] = $atcl_amt2;
        if (!empty($atcl_amt3))
            $data['lease_amt'] = $atcl_amt3;
        if (!empty($atcl_amt4))
            $data['deal_amt'] = $atcl_amt4;
        if (!empty($isale_amt))
            $data['isale_amt'] = $isale_amt;
        if (!empty($prem_amt))
            $data['prem_amt'] = $prem_amt;
        if (!empty($atcl_floor))
            $data['floor'] = $atcl_floor;
        if (!empty($atcl_floor2))
            $data['floor2'] = $atcl_floor2;

        $data['modify_yn'] = 'Y';

        $this->db->transStart();

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

        $last_query = $this->db->getLastQuery();
        $current_url = current_url();
        log_message('debug', "{$current_url} :: {$last_query}");

        $data['trade_type_cd'] = $trade_type;
        $error = $this->db->error();
        $return['error_number'] = $error['code'];
        $return['error_message'] = $error['message'];

        if (empty($return['error_number'])) {
            // 로그를 남긴다.
            if ($this->db->affectedRows() > 0) {
                $changed = $this->whatIsChanged($list, $data, $atcl_vr_sq);
                if (!empty($changed)) {
                    $this->saveChangedHistory($list['vr_sq'], $list['pre_stat_cd'], 'C25', $usr_id, $changed);
                }
            }
        }

        $this->db->transComplete();

        // 홍보확인서인 경우 주소 변경시 FAX 이미지의 정보도 함께 변경한다.
        $faxModel = new FaxModel();
        $faxModel->updateAddress($atcl_vr_sq, $list['address_code'], $data['address2'] ?? '', $data['address3'] ?? '', $data['hscp_no'] ?? '', $data['hscp_nm'] ?? '');

        return $return;
    }

    public function saveModifyVrfc($atcl_vr_sq, $atcl_vrfc_type)
    {
        $usr_id = session('usr_id');

        $list = $this->getDetail($atcl_vr_sq); // 변경된 내용 비교를 위해.

        $data = [];
        $data['vrfc_type'] = $atcl_vrfc_type;

        $this->db->transStart();

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

        $last_query = $this->db->getLastQuery();
        $current_url = current_url();
        log_message('debug', "{$current_url} :: {$last_query}");

        $data['vrfc_type_cd'] = $atcl_vrfc_type;

        $error = $this->db->error();
        $return['error_number'] = $error['code'];
        $return['error_message'] = $error['message'];

        if (empty($return['error_number'])) {
            // 로그를 남긁다.
            if ($this->db->affectedRows() > 0) {
                $changed = $this->whatIsChanged($list, $data, $atcl_vr_sq);
                if (!empty($changed)) {
                    $this->saveChangedHistory($list['vr_sq'], $list['pre_stat_cd'], 'C25', $usr_id, $changed);
                }
            }
        }

        $this->db->transComplete();

        return $return;
    }

    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 = array(
            $err_sq,
            $err_code,
            $err_nm,
            $err_time,
            $err_no,
            $err_server
        );
        $this->db->query($sql, $data);
    }

    // 메모조회
    public function getMemo($vr_sq)
    {
        $sql = "SELECT memo FROM v2_vrfc_req where vr_sq = ?";

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

        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 oneGetRecordInfo($vr_sq, $file_type)
    {
        $sql = "SELECT seq, vr_sq, use_yn, file_type, view_odr, file_path, file_name, file_ext, file_size, img_width, img_height, meta_data, insert_user, insert_tm " .
            " FROM v2_files" .
            " WHERE vr_sq = ?" .
            " AND use_yn = 'Y'" .
            " AND file_type = ?";

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

        return $query->getRowArray();
    }

    // 주택임대사업자번호 리스트
    public function getPhoneNumber()
    {
        $sql = " select phone_number
  				   from dupl_phone_list
 				  where use_yn = 'Y'";

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

        return $query->getResultArray();
    }

    // 녹취파일
    public function getRecordInfo($vr_sq, $file_type)
    {
        $sql = "SELECT seq, vr_sq, use_yn, file_type, view_odr, file_path, file_name, file_ext, file_size, img_width, img_height, meta_data, insert_user, insert_tm " .
            " FROM v2_files" .
            " WHERE vr_sq = ?" .
            " AND use_yn = 'Y'" .
            " AND file_type = ?";
        $data = [
            $vr_sq,
            $file_type
        ];

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

        return $query->getRowArray();
    }

    // 파일정보 저장
    public function saveFileInfo($data)
    {
        $sql = "INSERT INTO v2_files
                (vr_sq, file_type, view_odr, file_path, file_name, file_ext, file_size, insert_user, insert_tm, cloud_upload_yn)
                VALUES
                (?, '3', 0, ?, ?, ?, ?, ?, NOW(), 'Y')
                ";

        $param = [
            $data['vr_sq'],
            $data['file_path'],
            $data['new_name'],
            $data['ext'],
            $data['size'],
            $data['usr_id'],
        ];


        if ($this->db->query($sql, $param)) {
            return [
                'success' => false,
                'msg' => '파일정보 저장 실패',
            ];
        }

        return [
            'success' => true
        ];
    }

    // 정보변경 이력 저장
    public function saveChangedHistory($vr_sq, $stat_cd, $chg_type, $usr_id, $memo)
    {
        $sql = "INSERT INTO v2_chg_history" .
            " (vr_sq, stat_cd, chg_type, insert_id, insert_tm, memo)" .
            " VALUES" .
            " (?, ?, ?, ?, now(), ?)";

        $data = [
            $vr_sq,
            $stat_cd,
            $chg_type,
            $usr_id,
            $memo
        ];

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

    // 메모저장
    public function saveMemo($data)
    {
        $usr_id = session('usr_id');

        $sql = "UPDATE v2_vrfc_req SET
                memo = ?
                WHERE vr_sq = ?";

        if ($this->db->query($sql, $data) === false) {
            return [
                'success' => false,
                'msg' => '파일정보 저장 실패',
            ];
        }

        $row = $this->getDetail($data[1]);

        $memo = "메모변경 : " . $row['memo'] . " => " . $data[0];
        $this->saveChangedHistory($data[1], $row['pre_stat_cd'], 'C19', $usr_id, $memo);

        return [
            'success' => true
        ];
    }

    // 전화실패
    public function saveContactFail($vr_sq)
    {
        $usr_id = session('usr_id');

        $sql = "update v2_vrfc_req set contact_fail_cnt = ifnull(contact_fail_cnt, 0) +1 where vr_sq = ?";
        $data = array($vr_sq);

        if ($this->db->query($sql, $data) === false) {
            return [
                'success' => false,
                'msg' => '통화실패 처리중 오류가 발생했습니다.',
            ];
        }

        $row = $this->getDetail($vr_sq);

        $this->saveChangedHistory($vr_sq, $row['data']['stat_cd'], 'C29', $usr_id, '통화실패');

        return [
            'success' => true
        ];
    }

    // 다음 전화매물 가져오기
    public function getNextTelInfo($vr_sq)
    {
        $this->db->transStart();
        $usr_id = session('usr_id');

        $sql = "SELECT a.vr_sq FROM v2_article_info a " .
            "JOIN v2_vrfc_req b ON a.vr_sq = b.vr_sq " .
            "WHERE b.stat_cd = '30' and b.insert_tm > DATE_ADD(NOW(), INTERVAL -7 day) " .
            "AND a.rdate < date_format(curdate(), '%Y-%m-%d 17:29:00') " .
            "AND b.vrfc_type ='T' " .
            "AND a.vr_sq > ? " .
            "AND a.charger='admin' " .
            "ORDER BY a.vr_sq asc " .
            "LIMIT 1 " .
            "FOR UPDATE SKIP LOCKED";

        $data = [$vr_sq];


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

        $sql = "UPDATE v2_article_info " .
            "SET charger = '" . $usr_id . "' " .
            "WHERE vr_sq ='" . $row['vr_sq'] . "'";
        $this->db->query($sql);

        $this->db->transComplete();

        return $row;
    }

    /* 현재 상태 확인 */
    public function chkStat($vr_sq)
    {
        $sql = "SELECT stat_cd FROM v2_vrfc_req WHERE vr_sq = ?";
        $data = array(
            $vr_sq
        );
        $query = $this->db->query($sql, $data);
        return $query->getRowArray();
    }

    public function InsCharger($atcl_vr_sq)
    {
        $usr_id = session('usr_id');

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

        $data = array(
            $usr_id,
            $atcl_vr_sq
        );

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

    public function chkTryCnt($atcl_vr_sq)
    {
        // 1차 검증인지 2차 검증인지 확인.
        $sql = "SELECT try_cnt FROM v2_vrfc_req WHERE vr_sq = ?";

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

        return $query->getRowArray();
    }

    /*
     * 등기부등본 확인중의 상태인 적이 있었는지 확인
     */
    public function chkHistoryStat($atcl_vr_sq)
    {
        $sql = "select count(a.stat_cd) from v2_chg_history a " .
            "where vr_sq = ? and stat_cd = 40 " .
            "order by vr_sq desc;";
        $data = array(
            $atcl_vr_sq
        );
        $query = $this->db->query($sql, $data);
        return $query->getRowArray();
    }

    public function chkConfirm($atcl_vr_sq, $reg_yn = null)
    {
        $builder = $this->db->table('v2_confirm');
        $builder->select('vr_sq');
        $builder->where('vr_sq', $atcl_vr_sq);

        if ($reg_yn) {
            $builder->where('vrfc_type', $reg_yn);
        }

        $query = $builder->get();
        return $query->getNumRows();
    }

    public function insertConfirm($vr_sq, $vrfc_type, $success, $type)
    {	//v2_confirm INSERT

        $usr_sq = session('usr_sq');
        $usr_id = session('usr_id');

        $sql = "INSERT INTO v2_confirm" .
            "(vr_sq, vrfc_type, success, type, charger, date, insert_user, insert_tm, update_user, update_tm)" .
            "VALUES" .
            "(?, ?, ?, ?, ?, '" . date('YmdHis') . "', ?, NOW(), ?, NOW())";

        $data = array(
            $vr_sq,
            $vrfc_type,
            $success,
            $type,
            $usr_id,
            $usr_sq,
            $usr_sq
        );

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

    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 = array($vr_sq);
        $query = $this->db->query($sql, $data);
        $row = $query->getRowArray();

        return $row;
    }

    public function updateConfirm($vr_sq, $vrfc_type, $success)
    {
        $data = [
            'success' => $success
        ];

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

        $error = $this->db->error();
        $return['error_number'] = $error['code'];
        $return['error_message'] = $error['message'];

        return $return;
    }

    public function chgStat($vr_sq, $stat_cd, $insert_tm)
    {
        // 상태변경 TABLE INSERT
        $usr_sq = session('usr_sq');
        $usr_id = session('usr_id');

        $list = $this->getDetail($vr_sq);

        $sql = "INSERT INTO v2_chg_stat (vr_sq, stat_cd, insert_user, insert_tm)" .
            "VALUES (?, ?, ?, ?)" .
            "ON DUPLICATE KEY " .
            "UPDATE vr_sq=VALUES(vr_sq), stat_cd=VALUES(stat_cd), insert_user=VALUES(insert_user), insert_tm=VALUES(insert_tm)";

        $data = [
            $vr_sq,
            $stat_cd,
            $usr_sq,
            $insert_tm
        ];

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

        $error = $this->db->error();
        $return['error_number'] = $error['code'];
        $return['error_message'] = $error['message'];

        if (empty($return['error_number'])) {
            // 로그를 남긴다.
            if ($this->db->affectedRows() > 0) {
                $changed = "전화확인 정보 저장";
                if (!empty($changed)) {
                    $this->saveChangedHistory($list['vr_sq'], $stat_cd, 'C9', $usr_id, $changed);
                }
            }
        }

        $this->db->transComplete();

        return $return;
    }

    public function chgStatVrfc($vr_sq, $stat_cd)
    {
        $data = ['stat_cd' => $stat_cd];

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

        $error = $this->db->error();
        $return['error_number'] = $error['code'];
        $return['error_message'] = $error['message'];

        return $return;
    }

    public function chgStatFax($vr_sq, $stat_cd)
    {
        $data = ['stat_cd' => $stat_cd];

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

        $error = $this->db->error();
        $return['error_number'] = $error['code'];
        $return['error_message'] = $error['message'];

        return $return;
    }

    public function chgRegTryCnt($vr_sq, $reg_try_cnt)
    {
        $sql = "UPDATE v2_vrfc_req" .
            " SET reg_try_cnt = ?" .
            " WHERE vr_sq = ?";

        $data = array(
            $reg_try_cnt,
            $vr_sq
        );

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

    public function chgTryCnt($vr_sq, $try_cnt)
    { 	//v2_vrfc_req try_cnt 값 변경.
        $sql = "UPDATE v2_vrfc_req" .
            " SET try_cnt = ?" .
            " WHERE vr_sq = ?";

        $data = array(
            $try_cnt,
            $vr_sq
        );

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

    public function insertChkList($vr_sq, $vrfc_type, $type, $code, $comment)
    {	//v2_check_list INSERT

        $usr_sq = session('usr_sq');

        $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 = array(
            $vr_sq,
            $vrfc_type,
            $type,
            $code,
            $comment,
            $usr_sq
        );

        $res = $this->db->query($sql, $data);
        $log_v = $this->db->getLastQuery();
        log_message('debug', "704 => " . $log_v);

    }

    public function deleteChkList($vr_sq, $vrfc_type, $type)
    {
        $sql = "delete from v2_check_list where vr_sq = ? and vrfc_type = ? and type = ?";
        $data = array(
            $vr_sq,
            $vrfc_type,
            $type
        );
        $this->db->query($sql, $data);
    }

    public function up_tel_fail_cause($vr_sq, $tel_fail_cause)
    {
        $sql = "UPDATE v2_vrfc_req" .
            " SET tel_fail_cause = ? " .
            " WHERE vr_sq = ?";

        $data = array(
            $tel_fail_cause,
            $vr_sq
        );

        $res = $this->db->query($sql, $data);
        echo $this->db->getLastQuery();
        $return['error_number'] = $this->db->_error_number();
        $return['error_message'] = $this->db->_error_message();

        return $return;
    }

    /* 검증결과 전송 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, 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 cl_sq, vr_sq, vrfc_type, type, code, comment, ownerNm, ownerBirth insert_user, insert_tm " .
            " 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'];

        $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' => '',
            ];
        } else {
            return array(
                'atclNo' => $atclNo,
                'success' => $success,
                'checkList' => $checkList,
                'charger' => $charger,
                'date' => $date,
            );
        }

    }
}