<?php
namespace App\Models\v2;

use CodeIgniter\Model;

class M709Model 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 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 getTotalCount($data)
    {
        $sql = "SELECT
                    COUNT(*) AS cnt
                FROM			
                    fax_imgs_mobile tbl
                JOIN fax_imgs a ON a.fax_sq = tbl.fax_sq
                LEFT JOIN v2_vrfc_req f2 ON f2.vr_sq = tbl.vr_sq AND f2.vrfc_type = 'M'
                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 v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39'

                WHERE
                    tbl.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -2 MONTH)
                    AND a.work_type = '2' ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";

            // 발신팩스번호
        } else if (!empty($data['caller_no'])) {
            $sql .= "EXISTS (SELECT 'x'
										FROM fax_imgs b
										WHERE b.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)
										AND b.RECV_TIME >= '" . $data['receipt_sdate'] . "' AND b.RECV_TIME <= '" . $data['receipt_edate'] . "'
										AND b.caller_no LIKE CONCAT('%', '" . $data['caller_no'] . "', '%')
										AND b.fax_sq = a.fax_sq
										) ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND b.stat_cd = '{$data['stat_cd']}' ";
            }

            // 매물번호입력
            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 tbl.RECV_TIME >= '{$data['receipt_sdate']} 00:00:00' ";
            }

            if (!empty($data['receipt_edate'])) {
                $sql .= "AND tbl.RECV_TIME <= '{$data['receipt_edate']} 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 (!empty($data['srcSido'])) {
                $sql .= "a.address_code LIKE " . substr($data['srcSido'], 0, 2) . "% ";
            }

            if (!empty($data['srcGugun'])) {
                $chk_gugun = substr($data['srcGugun'], 0, 2);
                if ($chk_gugun == '36') {
                    $sql .= "AND a.address_code = '{$data['srcGugun']}' ";
                } else {
                    $sql .= "AND a.address_code LIKE " . substr($data['srcGugun'], 0, 5) . "% ";
                }
            }

            if (!empty($data['srcDong'])) {
                $sql .= "AND a.address_code = '{$data['srcDong']}' ";
            }

            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND a.work_type = '1' ";
                $sql .= "EXISTS(SELECT 1 FROM receipt z WHERE z.rcpt_sq = a.vr_sq AND z.rcpt_stat LIKE '{$data['stat_cd']}%') ";
            }

            // 매물종류
            if (!empty($data['rlet_type_cd'])) {
                $sql .= "AND f1.rcpt_product = '{$data['rlet_type_cd']}' ";
            }

            // 담당자
            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['target_yn'])) {
                switch ($data['target_yn']) {
                    case "1":
                        $sql .= "AND (a.work_type = '1' and a.send_yn = 'Y') ";
                        break;
                    case "E":
                        $sql .= "AND a.work_type ='E' ";
                        break;
                    case "3":
                        $sql .= "AND (a.work_type = '1' and a.bunyang_yn = 'Y') ";
                        break;
                    case "A":
                        $sql .= "AND (a.work_type = '1' and a.send_yn = 'N') ";
                        break;
                }
            }

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

            // 검증방식
            if (!empty($data['rcpt_v2'])) {
                $sql .= "AND f1.isSiteVRVerification = '{$data['rcpt_v2']}' ";
            }

        }


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


        $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
                    , case 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.send_yn, f2.vrfc_type
                    , a.address_code, a.address2, a.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, f2.stat_cd as stat_cd2
                FROM			
                    fax_imgs_mobile tbl
                JOIN fax_imgs a ON a.fax_sq = tbl.fax_sq
                LEFT JOIN v2_vrfc_req f2 ON f2.vr_sq = tbl.vr_sq AND f2.vrfc_type = 'M'
                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 v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39'

                WHERE
                    tbl.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -2 MONTH)
                    AND a.work_type = '2' ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";

            // 발신팩스번호
        } else if (!empty($data['caller_no'])) {
            $sql .= "EXISTS (SELECT 'x'
										FROM fax_imgs b
										WHERE b.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)
										AND b.RECV_TIME >= '" . $data['receipt_sdate'] . "' AND b.RECV_TIME <= '" . $data['receipt_edate'] . "'
										AND b.caller_no LIKE CONCAT('%', '" . $data['caller_no'] . "', '%')
										AND b.fax_sq = a.fax_sq
										) ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND b.stat_cd = '{$data['stat_cd']}' ";
            }

            // 매물번호입력
            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 tbl.RECV_TIME >= '{$data['receipt_sdate']} 00:00:00' ";
            }

            if (!empty($data['receipt_edate'])) {
                $sql .= "AND tbl.RECV_TIME <= '{$data['receipt_edate']} 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 (!empty($data['srcSido'])) {
                $sql .= "a.address_code LIKE " . substr($data['srcSido'], 0, 2) . "% ";
            }

            if (!empty($data['srcGugun'])) {
                $chk_gugun = substr($data['srcGugun'], 0, 2);
                if ($chk_gugun == '36') {
                    $sql .= "AND a.address_code = '{$data['srcGugun']}' ";
                } else {
                    $sql .= "AND a.address_code LIKE " . substr($data['srcGugun'], 0, 5) . "% ";
                }
            }

            if (!empty($data['srcDong'])) {
                $sql .= "AND a.address_code = '{$data['srcDong']}' ";
            }

            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND a.work_type = '1' ";
                $sql .= "EXISTS(SELECT 1 FROM receipt z WHERE z.rcpt_sq = a.vr_sq AND z.rcpt_stat LIKE '{$data['stat_cd']}%') ";
            }

            // 매물종류
            if (!empty($data['rlet_type_cd'])) {
                $sql .= "AND f1.rcpt_product = '{$data['rlet_type_cd']}' ";
            }

            // 담당자
            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['target_yn'])) {
                switch ($data['target_yn']) {
                    case "1":
                        $sql .= "AND (a.work_type = '1' and a.send_yn = 'Y') ";
                        break;
                    case "E":
                        $sql .= "AND a.work_type ='E' ";
                        break;
                    case "3":
                        $sql .= "AND (a.work_type = '1' and a.bunyang_yn = 'Y') ";
                        break;
                    case "A":
                        $sql .= "AND (a.work_type = '1' and a.send_yn = 'N') ";
                        break;
                }
            }

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

            // 검증방식
            if (!empty($data['rcpt_v2'])) {
                $sql .= "AND f1.isSiteVRVerification = '{$data['rcpt_v2']}' ";
            }

        }


        $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
                    a.atcl_no AS '매물번호',
                    (SELECT cd_nm FROM codes WHERE cd = f2.stat_cd AND category = 'STEP_VERIFICATION') AS '현재상태',
                    CASE 
                        WHEN a.work_type = '1' AND a.send_yn = 'Y' THEN '홍보확인서'	
                        WHEN a.work_type = '3' THEN '분양권'	
                        WHEN a.work_type = 'E' THEN '홍보확인서 아님'	
                        WHEN a.work_type = '1' AND a.send_yn = 'N' THEN '미처리'
                    END AS '홍보확인서여부',
                    a.RECV_TIME AS '수신시간',
                    a.CALLER_NO AS '발신번호',
                    c.region_nm AS '주소',
                    IFNULL(a.address2, '') AS '상세주소',					
                    a.cpid AS '매체사',
                    a.realtor_nm AS '중개소',
                    d.usr_nm AS '서류/전화 담당자',
                    IFNULL(a.proc_tm, d2.insert_tm) AS '서류/전화 확인시간',	
                    e.usr_nm AS '등기부등본 담당자
                FROM			
                    fax_imgs_mobile tbl
                JOIN fax_imgs a ON a.fax_sq = tbl.fax_sq
                LEFT JOIN v2_vrfc_req f2 ON f2.vr_sq = tbl.vr_sq AND f2.vrfc_type = 'M'
                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 v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39'

                WHERE
                    tbl.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -2 MONTH)
                    AND a.work_type = '2' ";


        // 매물번호
        if (!empty($data['atcl_no'])) {
            $sql .= "AND a.atcl = '{$data['atcl_no']}' ";

            // 발신팩스번호
        } else if (!empty($data['caller_no'])) {
            $sql .= "EXISTS (SELECT 'x'
										FROM fax_imgs b
										WHERE b.RECV_TIME >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)
										AND b.RECV_TIME >= '" . $data['receipt_sdate'] . "' AND b.RECV_TIME <= '" . $data['receipt_edate'] . "'
										AND b.caller_no LIKE CONCAT('%', '" . $data['caller_no'] . "', '%')
										AND b.fax_sq = a.fax_sq
										) ";
        } else {
            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND b.stat_cd = '{$data['stat_cd']}' ";
            }

            // 매물번호입력
            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 tbl.RECV_TIME >= '{$data['receipt_sdate']} 00:00:00' ";
            }

            if (!empty($data['receipt_edate'])) {
                $sql .= "AND tbl.RECV_TIME <= '{$data['receipt_edate']} 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 (!empty($data['srcSido'])) {
                $sql .= "a.address_code LIKE " . substr($data['srcSido'], 0, 2) . "% ";
            }

            if (!empty($data['srcGugun'])) {
                $chk_gugun = substr($data['srcGugun'], 0, 2);
                if ($chk_gugun == '36') {
                    $sql .= "AND a.address_code = '{$data['srcGugun']}' ";
                } else {
                    $sql .= "AND a.address_code LIKE " . substr($data['srcGugun'], 0, 5) . "% ";
                }
            }

            if (!empty($data['srcDong'])) {
                $sql .= "AND a.address_code = '{$data['srcDong']}' ";
            }

            // 현재상태
            if (!empty($data['stat_cd'])) {
                $sql .= "AND a.work_type = '1' ";
                $sql .= "EXISTS(SELECT 1 FROM receipt z WHERE z.rcpt_sq = a.vr_sq AND z.rcpt_stat LIKE '{$data['stat_cd']}%') ";
            }

            // 매물종류
            if (!empty($data['rlet_type_cd'])) {
                $sql .= "AND f1.rcpt_product = '{$data['rlet_type_cd']}' ";
            }

            // 담당자
            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['target_yn'])) {
                switch ($data['target_yn']) {
                    case "1":
                        $sql .= "AND (a.work_type = '1' and a.send_yn = 'Y') ";
                        break;
                    case "E":
                        $sql .= "AND a.work_type ='E' ";
                        break;
                    case "3":
                        $sql .= "AND (a.work_type = '1' and a.bunyang_yn = 'Y') ";
                        break;
                    case "A":
                        $sql .= "AND (a.work_type = '1' and a.send_yn = 'N') ";
                        break;
                }
            }

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

            // 검증방식
            if (!empty($data['rcpt_v2'])) {
                $sql .= "AND f1.isSiteVRVerification = '{$data['rcpt_v2']}' ";
            }

        }


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

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

        return $query->getResultArray();
    }


    // 상세화면
    public function getDetail($fax_sq)
    {
        $this->db->transStart();

        $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.charger, a.caller_no
                FROM
                    fax_imgs a
                WHERE
                    fax_sq =  ?";

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

        $row = $query->getRowArray();

        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 getMemo($fax_sq)
    {
        $sql = "SELECT memo FROM v2_vrfc_req where vr_sq = ?";

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

        return $query->getRowArray();
    }

    // 매물검색
    public function getArticleInfo($atcl_no)
    {
        $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
                FROM
                    fax_imgs a
                WHERE
                    a.atcl_no = " . $atcl_no;

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

        $row = $query->getRowArray();

        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 = "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, b.rlet_type_cd, b.address_code, f.bild_nm as address1, f.address2, f.address3, 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
                , (SELECT cd_nm FROM codes WHERE category = 'STEP_VERIFICATION' AND cd = a.stat_cd) AS current_stat
                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)
				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 g on g.category = 'STEP_VERIFICATION' AND g.cd = a.stat_cd
				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 ";

        if (!empty($vr_sq)) {
            $sql .= "AND a.vr_sq = ?";
        } else {
            $sql .= "AND a.atcl_no = ?";
        }


        $sql .= "ORDER BY a.vr_sq DESC
				LIMIT 1";

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

        return $query->getRowArray();
    }

    // 변경이력 조회
    public function getHistory($id)
    {
        $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, [$id]);

        return $query->getResultArray();
    }

    // 홍보확인서 아님 저장
    public function saveNotArticle($fax_sq)
    {
        $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 
                work_type = 'E', proc_tm = NOW(), stat_cd = '69', charger = ?, dept1_sq = ?, dept2_sq = ? WHERE fax_sq = ?
                ";

        $data = [
            $usr_id,
            $dept1_sq,
            $dept2_sq,
            $fax_sq
        ];

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

        return [
            'success' => true
        ];
    }

    // 중복으로 저장
    public function saveDuplImgs($fax_sq, $atcl_no, $vr_sq)
    {
        $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']);

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

    // 정보저장
    public function saveAddress($data)
    {
        $rcpt_sq = $this->getRcptSq($data['atcl_no']);

        $data = [
            'rcpt_dtl_addr' => $data['address2'],
            'rcpt_ho' => $data['address3'],
            'trade_type' => $data['trade_type'],
            'rcpt_floor' => $data['floor'],
            'rcpt_floor2' => $data['floor2'],
        ];

        $builder = $this->db->table('receipt')->where('rcpt_sq', $rcpt_sq['rcpt_sq']);
        $ok = $builder->update($data);

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

        return [
            'success' => true,
        ];

    }

    public function getRcptSq($rcpt_atclno)
    {
        $sql = "select rcpt_sq from receipt
				where rcpt_atclno = ?";
        $data = array($rcpt_atclno);
        $query = $this->db->query($sql, $data);
        $row = $query->getRowArray();

        return $row;
    }

    // 확인결과 저장
    public function saveImageArticle($data)
    {
        $this->db->transStart();

        $usr_id = session('usr_id');
        $stat_cd = "";
        $current_tm = date('Y-m-d H:i:s');

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

        if ($this->db->query($sql, [$usr_id, $data['vr_sq']]) === false) {
            return [
                'success' => false,
                'msg' => '담당자 저장 실패',
            ];
        } else {

            $fax = $this->getFaxImgs($data['fax_sq']);

            if (!empty($fax)) {
                $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/',
                );

                $file_path = str_replace($arrImagePath, '/upload/', $fax['file_path']);
                // 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 = [
                    $data['vr_sq'],
                    $fax['file_type'],
                    $file_path,
                    $fax['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 = ?";
                    $this->db->query($sql, [$data['vr_sq'], $fax['file_type']]);
                }

                // 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 = [$data['vr_sq'], $fax['file_type'], $file_path, $fax['file_name'], $fax['file_ext'], $fax['file_size'], $fax['img_width'], $fax['img_height'], $usr_id];
                $this->db->query($sql, $data);

                $article = $this->getArticleInfo2('', $data['vr_sq']);

                //4.매물과 팩스를 이어준다
                $this->saveFaxImgs($data['fax_sq'], '2', $article['vr_sq'], $article['atcl_no'], $article['cpid'], $article['realtor_nm'], $stat_cd, $current_tm, $article['address_code'], $article['address2'], 'Y');
            }

        }


        $this->db->transComplete();
    }

    // 다음매물조회
    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'];
        }


        $sql = "SELECT a.fax_sq FROM fax_imgs a
                WHERE 
                    a.recv_time > DATE_ADD(NOW(), INTERVAL -7 DAY) AND a.stat_cd = '20' AND a.work_type = '1' AND a.chk_con = 'N'
                    AND a.fax_sq > ?
                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 . "', chk_con='Y'" .
            " WHERE fax_sq = '" . $row['fax_sq'] . "'";
        $this->db->query($sql);

        $this->db->transComplete();

        return $row;
    }


    public function getFaxImgs($fax_sq)
    {
        $sql = "SELECT 
                    img_size, file_path, file_name, img_width, img_height
                FROM
                    fax_imgs
                WHERE fax_sq = ?";

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

        return $query->getRowArray();
    }

    public function saveFaxImgs($fax_sq, $work_type, $vr_sq, $atcl_no, $cpid, $realtor_nm, $stat_cd, $proc_tm, $address_code, $address2, $send_yn)
    {
        $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,
            'send_yn' => $send_yn,
        ];

        // 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,
        ];
    }

}