<?php
namespace App\Models\article;

use CodeIgniter\Model;

class AptModel 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 getDeptStatistics($data)
    {
        $sql = "SELECT
                    b.dept_sq
                    , IFNULL(f.dept_nm, '') AS bonbu_nm
                    , IFNULL(i.dept_nm, '미지정') AS team_nm
                    , COUNT(b.dept_sq) AS cnt
                FROM
                    apt_receipt a	
                JOIN
                    apt_result b ON b.rcpt_no = a.rcpt_no
                LEFT JOIN
                    users c ON b.charger = c.usr_id
                LEFT JOIN
                    region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN
                    departments i ON b.dept_sq = i.dept_sq
                LEFT JOIN
                    departments f ON i.dept_sq = f.dept_sq	
                WHERE 1=1 ";

        // 사진코드
        if (!empty($data['pho_no'])) {
            $sql .= "AND a.rcpt_no IN ( SELECT rcpt_no FROM apt_photo WHERE pho_no = {$data['pho_no']} AND use_yn = 'Y' AND pho_cate1 != 'V') ";

            // 단지코드    
        } else if (!empty(($data['hscp_no']))) {
            $sql .= "AND a.hasp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else if (!empty($data['rcpt_no'])) {
            $sql .= "AND a.rcpt_no = {$data['rcpt_no']}";
        } else {

            // 단지명
            if (!empty($data['rcpt_hscp_nm'])) {
                $sql .= "AND a.rcpt_hscp_nm LIKE CONCAT('%', '{$data['rcpt_hscp_nm']}', '%') ";
            }

            // 총세대수
            if (!empty($data['households_cnt1'])) {
                $sql .= "AND a.households_cnt >= {$data['households_cnt']} ";
            }

            if (!empty($data['households_cnt2'])) {
                $sql .= "AND a.households_cnt <= {$data['households_cnt2']} ";
            }


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


            //촬영일자  == 단지정보작성완료 일자
            if (!empty($data['sdate'])) {
                $sql .= "AND b.write_complete_tm >= '{$data['sdate']} 00:00:00' ";
            }

            if (!empty($data['edate'])) {
                $sql .= "AND b.write_complete_tm <= '{$data['edate']} 00:00:00' ";
            }

            // 총동수
            if (!empty($data['dong_cnt1'])) {
                $sql .= "AND a.dong_cnt >= {$data['dong_cnt1']} ";
            }

            if (!empty($data['dong_cnt2'])) {
                $sql .= "AND a.dong_cnt <= {$data['dong_cnt2']} ";
            }

            // 담당자
            if (!empty($data['damdang'])) {
                $sql .= "AND a.charger = '{$data['damdang']}' ";
            } else {
                if (!empty($data['team'])) {
                    $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt WHERE i.dept_sq = '{$data['team']}') ";
                } else {
                    if (!empty($data['bonbu'])) {
                        $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt	WHERE i.dept_sq = '{$data['bonbu']}') ";
                    }
                }
            }

            // 진행상태
            if (!empty($data['stat']) && is_array($data['stat'])) {
                $statList = "'" . implode("','", $data['stat']) . "'";
                $sql .= " AND b.apt_step IN ({$statList}) ";
            }
        }

        $sql .= "GROUP BY b.dept_sq
                ORDER BY bonbu_nm ASC, team_nm ASC ";


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

        return $query->getResultArray();
    }

    // 지역별 통계
    public function getStatistics($data)
    {
        $sql = "SELECT
                    a.addr AS addr , COUNT(a.addr) AS cnt
                FROM apt_receipt AS a	
                JOIN apt_result b ON a.rcpt_no = b.rcpt_no
                LEFT JOIN users c ON b.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON b.dept_sq = i.dept_sq
                WHERE 1=1 ";

        // 사진코드
        if (!empty($data['pho_no'])) {
            $sql .= "AND a.rcpt_no IN ( SELECT rcpt_no FROM apt_photo WHERE pho_no = {$data['pho_no']} AND use_yn = 'Y' AND pho_cate1 != 'V') ";

            // 단지코드    
        } else if (!empty(($data['hscp_no']))) {
            $sql .= "AND a.hasp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else if (!empty($data['rcpt_no'])) {
            $sql .= "AND a.rcpt_no = {$data['rcpt_no']}";
        } else {

            // 단지명
            if (!empty($data['rcpt_hscp_nm'])) {
                $sql .= "AND a.rcpt_hscp_nm LIKE CONCAT('%', '{$data['rcpt_hscp_nm']}', '%') ";
            }

            // 총세대수
            if (!empty($data['households_cnt1'])) {
                $sql .= "AND a.households_cnt >= {$data['households_cnt']} ";
            }

            if (!empty($data['households_cnt2'])) {
                $sql .= "AND a.households_cnt <= {$data['households_cnt2']} ";
            }


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


            //촬영일자  == 단지정보작성완료 일자
            if (!empty($data['sdate'])) {
                $sql .= "AND b.write_complete_tm >= '{$data['sdate']} 00:00:00' ";
            }

            if (!empty($data['edate'])) {
                $sql .= "AND b.write_complete_tm <= '{$data['edate']} 00:00:00' ";
            }

            // 총동수
            if (!empty($data['dong_cnt1'])) {
                $sql .= "AND a.dong_cnt >= {$data['dong_cnt1']} ";
            }

            if (!empty($data['dong_cnt2'])) {
                $sql .= "AND a.dong_cnt <= {$data['dong_cnt2']} ";
            }

            // 담당자
            if (!empty($data['damdang'])) {
                $sql .= "AND a.charger = '{$data['damdang']}' ";
            } else {
                if (!empty($data['team'])) {
                    $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt WHERE i.dept_sq = '{$data['team']}') ";
                } else {
                    if (!empty($data['bonbu'])) {
                        $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt	WHERE i.dept_sq = '{$data['bonbu']}') ";
                    }
                }
            }

            // 진행상태
            if (!empty($data['stat']) && is_array($data['stat'])) {
                $statList = "'" . implode("','", $data['stat']) . "'";
                $sql .= " AND b.apt_step IN ({$statList}) ";
            }
        }

        $sql .= "GROUP BY a.addr ORDER BY a.addr ASC ";

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

        return $query->getResultArray();
    }

    public function getTotalCount($data)
    {
        $sql = "SELECT
                    COUNT(*) AS cnt
                FROM apt_receipt a
                JOIN apt_result b ON b.rcpt_no = a.rcpt_no
                LEFT JOIN users c ON b.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON b.dept_sq = i.dept_sq
                LEFT JOIN codes f ON b.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON b.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON b.apt_step = g.cd AND g.category = 'APT_STEP'
                LEFT JOIN apt_history j ON a.rcpt_no = j.rcpt_no AND j.changed_detail = 'C2' AND NOT EXISTS (SELECT 'x' FROM apt_history WHERE changed_detail LIKE 'A%' AND rcpt_no = j.rcpt_no) ";

        $sql .= "WHERE 1=1 ";

        // 사진코드
        if (!empty($data['pho_no'])) {
            $sql .= "AND a.rcpt_no IN ( SELECT rcpt_no FROM apt_photo WHERE pho_no = {$data['pho_no']} AND use_yn = 'Y' AND pho_cate1 != 'V') ";

            // 단지코드    
        } else if (!empty(($data['hscp_no']))) {
            $sql .= "AND a.hasp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else if (!empty($data['rcpt_no'])) {
            $sql .= "AND a.rcpt_no = {$data['rcpt_no']}";
        } else {

            // 단지명
            if (!empty($data['rcpt_hscp_nm'])) {
                $sql .= "AND a.rcpt_hscp_nm LIKE CONCAT('%', '{$data['rcpt_hscp_nm']}', '%') ";
            }

            // 총세대수
            if (!empty($data['households_cnt1'])) {
                $sql .= "AND a.households_cnt >= {$data['households_cnt']} ";
            }

            if (!empty($data['households_cnt2'])) {
                $sql .= "AND a.households_cnt <= {$data['households_cnt2']} ";
            }


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


            //촬영일자  == 단지정보작성완료 일자
            if (!empty($data['sdate'])) {
                $sql .= "AND b.write_complete_tm >= '{$data['sdate']} 00:00:00' ";
            }

            if (!empty($data['edate'])) {
                $sql .= "AND b.write_complete_tm <= '{$data['edate']} 00:00:00' ";
            }

            // 총동수
            if (!empty($data['dong_cnt1'])) {
                $sql .= "AND a.dong_cnt >= {$data['dong_cnt1']} ";
            }

            if (!empty($data['dong_cnt2'])) {
                $sql .= "AND a.dong_cnt <= {$data['dong_cnt2']} ";
            }

            // 담당자
            if (!empty($data['damdang'])) {
                $sql .= "AND a.charger = '{$data['damdang']}' ";
            } else {
                if (!empty($data['team'])) {
                    $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt WHERE i.dept_sq = '{$data['team']}') ";
                } else {
                    if (!empty($data['bonbu'])) {
                        $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt	WHERE i.dept_sq = '{$data['bonbu']}') ";
                    }
                }
            }

            // 진행상태
            if (!empty($data['stat']) && is_array($data['stat'])) {
                $statList = "'" . implode("','", $data['stat']) . "'";
                $sql .= " AND b.apt_step IN ({$statList}) ";
            }
        }

        // print ($sql);

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

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

    // 아파트단지 조회
    public function getAptLists($start, $end, $data)
    {
        $sql = "SELECT
                    a.rcpt_no, a.hscp_no, a.addr, a.addr2, a.rcpt_hscp_nm, a.pyeong_cnt, a.households_cnt, a.dong_cnt, a.rcpt_hscp_nm, 
                    a.apt_cate_nm, a.rcpt_x, a.rcpt_y,
                    b.charger, b.memo, b.write_complete_yn, b.vdo_up_ynx, b.apt_step, b.video_target, b.all_no_pho,
                    b.dept_sq, b.vdo_up_tm, b.not_vdo_tm, b.check_tm, b.write_complete_tm,
                    c.usr_nm, i.dept_nm, j.changed_tm
                FROM apt_receipt a
                JOIN apt_result b ON b.rcpt_no = a.rcpt_no
                LEFT JOIN users c ON b.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON b.dept_sq = i.dept_sq
                LEFT JOIN codes f ON b.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON b.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON b.apt_step = g.cd AND g.category = 'APT_STEP'
                LEFT JOIN apt_history j ON a.rcpt_no = j.rcpt_no AND j.changed_detail = 'C2' AND NOT EXISTS (SELECT 'x' FROM apt_history WHERE changed_detail LIKE 'A%' AND rcpt_no = j.rcpt_no) ";

        $sql .= "WHERE 1=1 ";

        // 사진코드
        if (!empty($data['pho_no'])) {
            $sql .= "AND a.rcpt_no IN ( SELECT rcpt_no FROM apt_photo WHERE pho_no = {$data['pho_no']} AND use_yn = 'Y' AND pho_cate1 != 'V') ";

            // 단지코드    
        } else if (!empty(($data['hscp_no']))) {
            $sql .= "AND a.hasp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else if (!empty($data['rcpt_no'])) {
            $sql .= "AND a.rcpt_no = {$data['rcpt_no']}";
        } else {

            // 단지명
            if (!empty($data['rcpt_hscp_nm'])) {
                $sql .= "AND a.rcpt_hscp_nm LIKE CONCAT('%', '{$data['rcpt_hscp_nm']}', '%') ";
            }

            // 총세대수
            if (!empty($data['households_cnt1'])) {
                $sql .= "AND a.households_cnt >= {$data['households_cnt']} ";
            }

            if (!empty($data['households_cnt2'])) {
                $sql .= "AND a.households_cnt <= {$data['households_cnt2']} ";
            }


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


            //촬영일자  == 단지정보작성완료 일자
            if (!empty($data['sdate'])) {
                $sql .= "AND b.write_complete_tm >= '{$data['sdate']} 00:00:00' ";
            }

            if (!empty($data['edate'])) {
                $sql .= "AND b.write_complete_tm <= '{$data['edate']} 00:00:00' ";
            }

            // 총동수
            if (!empty($data['dong_cnt1'])) {
                $sql .= "AND a.dong_cnt >= {$data['dong_cnt1']} ";
            }

            if (!empty($data['dong_cnt2'])) {
                $sql .= "AND a.dong_cnt <= {$data['dong_cnt2']} ";
            }

            // 담당자
            if (!empty($data['damdang'])) {
                $sql .= "AND a.charger = '{$data['damdang']}' ";
            } else {
                if (!empty($data['team'])) {
                    $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt WHERE i.dept_sq = '{$data['team']}') ";
                } else {
                    if (!empty($data['bonbu'])) {
                        $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt	WHERE i.dept_sq = '{$data['bonbu']}') ";
                    }
                }
            }

            // 진행상태
            if (!empty($data['stat']) && is_array($data['stat'])) {
                $statList = "'" . implode("','", $data['stat']) . "'";
                $sql .= " AND b.apt_step IN ({$statList}) ";
            }
        }


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

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

        return $query->getResultArray();
    }

    // 전체촬영불가 단지 확인
    public function chkTakeAptPhotoCnt()
    {
        $sql = "SELECT 
                    COUNT(*) cnt
                FROM apt_result
                WHERE all_no_pho = 'x' ";

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

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


    public function getDeptMapList($dept_sq)
    {
        $columns = "
            b.hscp_no, b.rcpt_hscp_nm, b.rcpt_no, b.dept_sq, b.rcpt_x, b.rcpt_y,
            b.charger, i.dept_nm, i.pdept_sq, i.dept_desc,
            c.usr_nm, c.usr_id,
            (SELECT pdept_sq FROM departments WHERE dept_sq = i.dept_sq) bonbu
        ";

        $builder = $this->db->table('apt_receipt a');

        $builder->select($columns, false);
        $builder->join('apt_result b', 'b.rcpt_no = a.rcpt_no');
        $builder->join('users c', 'b.charger = c.usr_id', 'left');
        $builder->join('region_codes e', 'a.region_cd = e.region_cd', 'left');
        $builder->join('departments i', 'b.dept_sq = i.dept_sq', 'left');
        $builder->join('codes f', "b.write_complete_yn = f.cd AND f.category = 'PHO_YN'", 'left');
        $builder->join('codes h', "b.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'", 'left');
        $builder->join('codes g', "b.apt_step = g.cd AND g.category = 'APT_STEP'", 'left');

        $builder->whereIn('b.dept_sq', $dept_sq);
        $builder->orderBy('b.dept_sq', 'ASC');

        $query = $builder->get();

        return $query->getResultArray();

    }


    // 아파트단지정보저장
    public function saveAptMemo($params)
    {
        $sql = "UPDATE apt_result SET ";
        $sql .= "memo = '{$params['memo']}'";
        if (!empty($params['target'])) {
            $sql .= ", video_target = '{$params['target']}'";
        }

        $sql .= "WHERE rcpt_no = {$params['rcpt_no']} ";

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


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

        // 성공
        return [
            'success' => true,
        ];
    }

    // 아파트 담당자 정보 변경
    public function updateAptDamdang($params)
    {
        $sql = "UPDATE apt_result SET ";
        $sql .= "dept_sq = ?, charger = ? ";
        $sql .= "WHERE rcpt_no = ? ";

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


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

        // 성공
        return [
            'success' => true,
        ];
    }

    // 영상대상 정보 저장
    public function updateAptVideoTarget($params)
    {
        $sql = "UPDATE apt_result SET ";
        $sql .= "video_target = '{$params['target']}' WHERE rcpt_no = {$params['rcpt_no']} ";

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


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

        if ($params['target'] == 'Y') {
            $changed_type = "영상 촬영 대상 지정";
        } else {
            $changed_type = "영상 촬영 대상 제외('" . $params['target'] . "')";
        }

        // INSERT apt_history
        $this->saveHistory($params['rcpt_no'], $params['apt_step'], 'H', $changed_type, $params['usr_id']);

        // 성공
        return [
            'success' => true,
        ];
    }

    // 엑셀업로드 저장
    public function saveExcelUploadData($params)
    {

        $this->db->transStart();

        $builder = $this->db->table('apt_receipt');
        $res = $builder->insert($params);

        if ($res === false) {
            return [
                'success' => false,
                'msg' => "단지코드 : {$params['hscp_no']} 저장실패",
            ];
        }

        $rcpt_no = $this->db->insertID();

        $params2 = [
            'rcpt_no' => $rcpt_no,
            'hscp_no' => $params['hscp_no'],
            'region_cd' => $params['region_cd'],
            'charger' => '',
            'dept_sq' => '',
            'addr' => $params['addr'],
            'addr2' => $params['addr2'],
            'rcpt_hscp_nm' => $params['rcpt_hscp_nm'],
            'rcpt_x' => $params['rcpt_x'],
            'rcpt_y' => $params['rcpt_y'],
            'move_ym' => $params['move_ym'],
            'households_cnt' => $params['households_cnt'],
            'dong_cnt' => $params['dong_cnt'],
            'apt_cate_nm' => $params['apt_cate_nm'],
            'apt_step' => 'S01',
            'check_yn' => 'N',
            'resend_yn' => 'N',
            'memo' => '',
            'pho_up_yn' => 'N',
            'vdo_up_ynx' => 'N',
            'vdo_up_tm' => NULL,
            'video_target' => 'N',
            'not_vdo_reson' => '',
            'note' => '',
            'not_vdo_tm' => NULL,
            'check_tm' => NULL,
            'write_complete_yn' => 'N',
            'write_complete_tm' => NULL,
            'all_no_pho' => NULL,
            'syncid' => '',
            'sync_comp' => NULL,
            'sync_wait_cnt' => '0'
        ];

        $builder = $this->db->table('apt_result');
        $res = $builder->insert($params2);

        if ($res === false) {
            return [
                'success' => false,
                'msg' => "단지코드 : {$params['hscp_no']} 저장실패",
            ];
        }

        $this->db->transComplete();

        // 성공
        return [
            'success' => true,
        ];
    }

    // 엑셀 다운로드
    public function getExcelList($data)
    {
        $sql = "SELECT
                    (SELECT cd_nm FROM codes WHERE category = 'APT_STEP' AND cd = b.apt_step) AS '진행상태',
                    a.hscp_no AS '단지코드',
                    a.addr AS '주소', 
                    a.addr2 AS '상세주소',
                    a.rcpt_hscp_nm AS '단지구역명', 
                    a.households_cnt AS '총세대수', 
                    a.dong_cnt AS '총동수',
                    c.usr_nm AS '방문담당',
                    b.write_complete_yn AS '사진촬영',
                    CASE WHEN b.vdo_up_ynx = 'X' THEN '촬영불가' ELSE b.vdo_up_ynx END AS '영상촬영',
                    (SELECT cd_nm FROM codes WHERE category = 'VIDEO_TARGET' AND cd = b.video_target) AS '영상대상',
                    b.memo AS '메모',
                    b.write_complete_tm AS '사진업로드',
                    b.vdo_up_tm AS '영상업로드',
                    b.not_vdo_tm AS '촬영불가',
                    b.check_tm AS '검수',
                    b.all_no_pho AS '단지 전체 촬영불가'
                FROM apt_receipt a
                JOIN apt_result b ON b.rcpt_no = a.rcpt_no
                LEFT JOIN users c ON b.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON b.dept_sq = i.dept_sq
                LEFT JOIN codes f ON b.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON b.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON b.apt_step = g.cd AND g.category = 'APT_STEP'
                LEFT JOIN apt_history j ON a.rcpt_no = j.rcpt_no AND j.changed_detail = 'C2' AND NOT EXISTS (SELECT 'x' FROM apt_history WHERE changed_detail LIKE 'A%' AND rcpt_no = j.rcpt_no) ";

        $sql .= "WHERE 1=1 ";

        // 사진코드
        if (!empty($data['pho_no'])) {
            $sql .= "AND a.rcpt_no IN ( SELECT rcpt_no FROM apt_photo WHERE pho_no = {$data['pho_no']} AND use_yn = 'Y' AND pho_cate1 != 'V') ";

            // 단지코드    
        } else if (!empty(($data['hscp_no']))) {
            $sql .= "AND a.hasp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else if (!empty($data['rcpt_no'])) {
            $sql .= "AND a.rcpt_no = {$data['rcpt_no']}";
        } else {

            // 단지명
            if (!empty($data['rcpt_hscp_nm'])) {
                $sql .= "AND a.rcpt_hscp_nm LIKE CONCAT('%', '{$data['rcpt_hscp_nm']}', '%') ";
            }

            // 총세대수
            if (!empty($data['households_cnt1'])) {
                $sql .= "AND a.households_cnt >= {$data['households_cnt']} ";
            }

            if (!empty($data['households_cnt2'])) {
                $sql .= "AND a.households_cnt <= {$data['households_cnt2']} ";
            }


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


            //촬영일자  == 단지정보작성완료 일자
            if (!empty($data['sdate'])) {
                $sql .= "AND b.write_complete_tm >= '{$data['sdate']} 00:00:00' ";
            }

            if (!empty($data['edate'])) {
                $sql .= "AND b.write_complete_tm <= '{$data['edate']} 00:00:00' ";
            }

            // 총동수
            if (!empty($data['dong_cnt1'])) {
                $sql .= "AND a.dong_cnt >= {$data['dong_cnt1']} ";
            }

            if (!empty($data['dong_cnt2'])) {
                $sql .= "AND a.dong_cnt <= {$data['dong_cnt2']} ";
            }

            // 담당자
            if (!empty($data['damdang'])) {
                $sql .= "AND a.charger = '{$data['damdang']}' ";
            } else {
                if (!empty($data['team'])) {
                    $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt WHERE i.dept_sq = '{$data['team']}') ";
                } else {
                    if (!empty($data['bonbu'])) {
                        $sql .= "AND a.dept_sq IN (SELECT h.dept_sq FROM departments i INNER JOIN departments h ON h.lft >= i.lft AND h.lft <= i.rgt	WHERE i.dept_sq = '{$data['bonbu']}') ";
                    }
                }
            }

            // 진행상태
            if (!empty($data['stat']) && is_array($data['stat'])) {
                $statList = "'" . implode("','", $data['stat']) . "'";
                $sql .= " AND b.apt_step IN ({$statList}) ";
            }
        }

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

        return $query->getResultArray();
    }

    // 이력 저장
    public function saveHistory($rcpt_no, $apt_step, $changed_type, $changed_detail, $charged_id)
    {
        $sql = "INSERT INTO apt_history" .
            " (rcpt_no, apt_step, changed_type, changed_detail, charged_id, changed_tm)" .
            " VALUES (?, ?, ?, ?, ?, NOW())";
        $data = [
            $rcpt_no,
            $apt_step,
            $changed_type,
            $changed_detail,
            $charged_id
        ];
        $res = $this->db->query($sql, $data);
    }


    /**
     * 상세페이지
     */
    public function getDetail($rcpt_no)
    {
        $sql = "SELECT
                    a.rcpt_no, a.hscp_no, a.addr, a.addr2, a.rcpt_hscp_nm, a.move_ym, a.households_cnt, a.dong_cnt, a.pyeong_cnt, a.apt_cate_nm, a.region_cd, a.rcpt_x, a.rcpt_y, a.pho_exept_yn
                    ,a.rdate, DATE_FORMAT(a.rdate, '%Y-%m-%d') as rdate_dt ,DATE_FORMAT(a.rdate, '%H:%i:%s') as rdate_tm
                    ,b.vdo_up_tm, DATE_FORMAT(b.vdo_up_tm, '%Y-%m-%d') as rdate_dt_vdo ,DATE_FORMAT(b.vdo_up_tm, '%H:%i:%s') as rdate_tm_vdo
                    ,b.not_vdo_tm, DATE_FORMAT(b.not_vdo_tm, '%Y-%m-%d') as rdate_dt_nvdo ,DATE_FORMAT(b.not_vdo_tm, '%H:%i:%s') as rdate_tm_nvdo
                    ,b.check_tm, DATE_FORMAT(b.check_tm, '%Y-%m-%d') as rdate_dt_chk ,DATE_FORMAT(b.check_tm, '%H:%i:%s') as rdate_tm_chk
                    ,b.memo, b.note, b.video_target, b.vdo_up_ynx, b.not_vdo_reson, b.apt_step, b.not_vdo_tm, b.check_yn, b.resend_yn, b.write_complete_yn, b.all_no_pho
                    ,b.write_complete_tm, DATE_FORMAT(b.write_complete_tm, '%Y-%m-%d') as rdate_dt_cmpl ,DATE_FORMAT(b.write_complete_tm, '%H:%i:%s') as rdate_tm_cmpl
                    ,b.charger, b.dept_sq ,(SELECT pdept_sq FROM departments WHERE dept_sq = b.dept_sq) bonbu
                    ,IFNULL((SELECT CONCAT(file_path, '', filenm_up) FROM apt_photo WHERE rcpt_no = a.rcpt_no AND pho_cate1 = 'V' AND pho_cate2 = 'V01' ORDER BY pho_no DESC LIMIT 1), '') AS vdo_path
                FROM
                    apt_receipt a
                JOIN apt_result b ON a.rcpt_no = b.rcpt_no

                WHERE a.rcpt_no = ?";

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

        return $query->getRowArray();
    }

    // 이미지리스트
    public function getImgList($rcpt_no)
    {
        $sql = "SELECT pho_no,rcpt_no,pho_cate1,pho_cate2,pho_lati,pho_long,filenm,filenm_up,view_odr,pho_view_yn,pho_date,insert_tm,file_path,use_yn,thumb_path,thumb_nm,cloud_upload_yn" .
            " FROM apt_photo" .
            " WHERE rcpt_no = ?" .
            " AND use_yn = 'Y'";

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

        return $query->getResultArray();
    }

    // 이미지 총 개수
    public function cntAllPho($rcpt_no)
    {
        $sql = "SELECT COUNT(*) cnt " .
            " FROM apt_photo" .
            " WHERE rcpt_no= ?" .
            " AND use_yn = 'Y'" .
            " AND pho_cate1 != 'V'";

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

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

    // 동영상 리스트
    public function getVideoList($rcpt_no)
    {
        $sql = "SELECT pho_no,rcpt_no,pho_cate1,insert_tm,use_yn,file_path,filenm_up" .
            " FROM apt_photo" .
            " WHERE rcpt_no = ?" .
            " AND pho_cate1 = 'V'" .
            " AND use_yn = 'Y'";

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

        return $query->getRowArray();
    }

    // 사진및 설명정보의 카테고리 리스트
    public function getCateInfoList($rcpt_no)
    {
        $sql = "SELECT rcpt_no, pho_cate2, pho_explain, pho_up_nu" .
            " FROM apt_category" .
            " WHERE rcpt_no = ?";

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

        return $query->getResultArray();
    }

    // 정보변경이력
    public function getHistory($rcpt_no)
    {
        $sql = " SELECT seq," .
            "	rcpt_no, " .
            "	apt_step, get_code_name('APT_STEP',apt_step) AS apt_step_nm, " .
            "	changed_type, get_code_name('APT_CHANGED_TYPE',changed_type) AS changed_type_nm, " .
            "	changed_detail, get_code_name('APT_CHANGED_DETAIL',changed_detail) AS changed_detail_nm, " .
            "	charged_id, " .
            " 	changed_tm, DATE_FORMAT(changed_tm, '%Y-%m-%d') as rdate_dt, DATE_FORMAT(changed_tm, '%H:%i:%s') as rdate_tm" .
            " FROM apt_history" .
            " WHERE rcpt_no = ?" .
            " ORDER BY changed_tm DESC";

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

        return $query->getResultArray();
    }

    // 사진 카테고리 조회
    public function getCateJson($params)
    {
        $sql = "SELECT cd, cd_nm" .
            " FROM codes" .
            " WHERE cd LIKE CONCAT(?, '%')" .
            " AND category = 'PHO_CATE2'";

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


        return $query->getResultArray();
    }

    // 담당자정보저장
    public function saveKeeper($params)
    {
        $sql = "UPDATE apt_result SET
                dept_sq = {$params['team']}, charger = '{$params['user']}'
                WHERE rcpt_no = {$params['rcpt_no']}
                ";


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

        // 성공
        return [
            'success' => true,
        ];
    }

    // 지도 좌표저장
    public function saveCoordinate($params)
    {
        $sql = "UPDATE apt_receipt SET 
            rcpt_x = '{$params['rcpt_x']}',
            rcpt_y = '{$params['rcpt_y']}'
            WHERE rcpt_no = {$params['rcpt_no']}";

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

        $sql = "UPDATE apt_result SET
            rcpt_x = '{$params['rcpt_x']}',
            rcpt_y = '{$params['rcpt_y']}'
            WHERE rcpt_no = {$params['rcpt_no']}";

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

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

    // 단지 특이사항 저장
    public function saveNote($params)
    {
        $sql = "UPDATE apt_result SET 
            note = '{$params['note']}'
            WHERE rcpt_no = {$params['rcpt_no']}";

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

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

    // 동영상 촬영정보 저장
    public function saveVideoTarget($params)
    {
        $sql = "UPDATE apt_result SET
                video_target = '{$params['target']}'
                WHERE rcpt_no = {$params['rcpt_no']}
                ";


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

        $now = $this->getDetail($params['rcpt_no']);
        if ($params['target'] == 'Y') {
            $changed_type = "영상 촬영 대상 지정";
        } else {
            $changed_type = "영상 촬영 대상 제외('" . $params['target'] . "')";
        }

        $this->saveHistory($params['rcpt_no'], $now['apt_step'], 'H', $changed_type, session('usr_id'));

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

    // 촬영불가사유 저장
    public function saveVideoReason($params)
    {
        $sql = "UPDATE apt_result SET
                not_vdo_reason = '{$params['not_vdo_reason']}'
                , vdo_up_ynx = '{$params['vdo_up_ynx']}'
                , not_vdo_tm = NOW()
                , apt_step = CASE WHEN write_complete_yn = 'Y' THEN 'S04' ELSE 'S03' END
                WHERE rcpt_no = {$params['rcpt_no']}
                ";

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

        $now = $this->getDetail($params['rcpt_no']);
        $this->saveHistory($params['rcpt_no'], $now['apt_step'], 'G', 'G1', session('usr_id'));


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

    // 사진업로드 불가사유 저장
    public function savePhoReason($params)
    {
        $sql = "INSERT INTO apt_category
                (rcpt_no, pho_cate2, pho_up_nu, insert_tm, insert_tm, insert_user_id)
                VALUES 
                ({$params['rcpt_no']}, '{$params['pho_cate2']}', '{$params['pho_up_nu']}', NOW(), {$params['usr_id']})
                ";

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

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


    // 사진 카테고리 수정
    public function saveCate($params)
    {

        $data = [
            'pho_cate1' => $params['pho_cate1'],
            'pho_cate2' => $params['pho_cate2'],
        ];

        $phoNos = $params['pho_no'] ?? [];

        if (!is_array($phoNos)) {
            $phoNos = [$phoNos];
        }

        if (empty($phoNos)) {
            return [
                'success' => false,
                'msg' => '대상 pho_no가 없습니다.',
            ];
        }

        $builder = $this->db->table('apt_photo');

        $builder->whereIn('pho_no', $phoNos);
        $result = $builder->update($data);


        if ($result === false) {
            return [
                'success' => false,
                'msg' => 'DB 업데이트 실패',
            ];
        }

        $sql2 = " DELETE FROM apt_category" .	//2.조건에맞는거 = 해당카테고리에 사진이 없을때 삭제
            " WHERE rcpt_no =  {$params['rcpt_no']}" .
            " AND pho_cate2 =  '{$params['nowCate2']}'" .
            " AND NOT EXISTS ( SELECT 'x' FROM apt_photo b" .
            " WHERE b.rcpt_no = apt_category.rcpt_no" .
            " AND b.pho_cate2 = apt_category.pho_cate2" .
            " AND b.use_yn = 'Y')";

        if ($this->db->query($sql2) === false) {
            return [
                'success' => false,
                'msg' => '처리 실패',
            ];
        }

        $sql3 = " UPDATE apt_category" .	//3. 이동할 카테고리에 이미 불가사유가 있다면 불가사유 null로 업데이트
            " SET pho_up_nu = NULL" .
            " WHERE rcpt_no = {$params['rcpt_no']}" .
            " AND pho_cate2 = '{$params['pho_cate2']}'" .
            " AND pho_up_nu IS NOT NULL";


        if ($this->db->query($sql3) === false) {
            return [
                'success' => false,
                'msg' => '처리 실패',
            ];
        }

        $now = $this->getDetail($params['rcpt_no']);
        $this->saveHistory($params['rcpt_no'], $now['apt_step'], 'D', 'D1', session('usr_id'));

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

    // 사진 노출여부 수정
    public function savePhotoView($params)
    {
        $data = [
            'pho_view_yn' => $params['pho_view_yn'],
        ];

        $builder = $this->db->table('apt_photo');

        $builder->whereIn('pho_no', $params['pho_no']);
        // $builder->where('rcpt_no', $params['rcpt_no']);

        if (!$builder->update($data)) {
            return [
                'success' => false,
                'msg' => '처리 실패',
            ];
        }

        $now = $this->getDetail($params['rcpt_no']);
        if ($params['pho_view_yn'] === 'Y') {//노출시작
            $this->saveHistory($params['rcpt_no'], $now['apt_step'], 'E', 'E1', session('usr_id'));
        } else {//종료
            $this->saveHistory($params['rcpt_no'], $now['apt_step'], 'E', 'E2', session('usr_id'));
        }

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

    // 사진정보삭제
    public function removePhoto($params)
    {
        $data = [
            'use_yn' => 'N',
        ];

        $builder = $this->db->table('apt_photo');

        $builder->whereIn('pho_no', $params['pho_no']);
        $builder->where('rcpt_no', $params['rcpt_no']);

        if (!$builder->update()) {
            return [
                'success' => false,
                'msg' => '처리 실패',
            ];
        }

        $sql2 = "SELECT pho_cate2 FROM apt_photo
                WHERE rcpt_no = {$params['rcpt_no']} 
                AND pho_cate = '{$params['cate2_cd']}'
                AND use_yn = 'Y'
                ";

        $query2 = $this->db->query($sql2);

        if ($this->db->transStatus() == false) {
            return [
                'success' => false,
                'msg' => '처리 실패',
            ];
        }

        if ($query2->getNumRows() > 0) {
            $sql3 = "DELETE FROM apt_category 
                WHERE rcpt_no = {$params['rcpt_no']}
                AND pho_cate2 = '{$params['cate2_cd']}'
                    ";

            $query3 = $this->db->query($sql3);
        }

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


    // 사진설명 저장
    public function savePhoExplain($params)
    {
        $sql = "INSERT INTO apt_category 
                (rcpt_no, pho_cate2, pho_explain, insert_tm, insert_user_id)
                VALUES
                ({$params['rcpt_no']}, '{$params['pho_cate2']}', '{$params['pho_explain']}', NOW(), '{$params['usr_id']}')
                ";

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

        $now = $this->getDetail($params['rcpt_no']);
        $this->saveHistory($params['rcpt_no'], $now['apt_step'], 'D', '사진설명 작성', $params['usr_id']);

        // 성공
        return [
            'success' => true,
        ];
    }

    // 단지정보 작성완료
    public function saveWriteComplete($rcpt_no)
    {
        $sql = " UPDATE apt_result" .
            " SET write_complete_yn = 'Y'" .
            " ,apt_step = CASE WHEN vdo_up_ynx = 'N' THEN 'S02' ELSE 'S04' END" .
            " ,write_complete_tm = now()" .
            " WHERE rcpt_no = ? ";

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

        $now = $this->getDetail($rcpt_no);
        $this->saveHistory($rcpt_no, $now['apt_step'], 'C', 'C1', session('usr_id'));

        // 성공
        return [
            'success' => true,
        ];
    }


    // 단지실사 API 정보
    public function new_api_photo_send_data($rcpt_no)
    {
        $sql = "SELECT  c2.cd_nm as cate1_nm , c1.cd_nm cate2_nm  , c1.cd_naver cate2_cd , c2.cd_naver cate1_cd , ap.pho_no , ap.pho_view_yn FROM apt_category ac
					LEFT JOIN codes c1 ON ac.pho_cate2 = c1.cd AND c1.category = 'PHO_CATE2'
					LEFT JOIN codes c2 ON LEFT( c1.cd_naver , 2)  = LEFT ( c2.cd_naver , 2) AND c2.category = 'PHO_CATE1'
					LEFT  JOIN apt_photo ap ON c1.cd = ap.pho_cate2 AND ap.rcpt_no = ac.rcpt_no
				WHERE ac.rcpt_no = ?
						AND pho_no IS NOT NULL 
						group by c1.cd_naver ";

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

        return $query->getResultArray();
    }

    // 검수완료
    public function saveCheck($rcpt_no, $syncId)
    {
        $sql = "UPDATE apt_result" .
            " SET check_yn = 'Y'" .
            " 	 ,check_tm = NOW()" .
            " 	 ,apt_step = 'S05'" .
            "	 ,syncid = ?" .
            " WHERE rcpt_no = ? ";

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

        $this->saveHistory($rcpt_no, 'S05', 'I', 'I1', session('usr_id'));

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

    // 재전송
    public function saveResend($rcpt_no, $syncId)
    {
        $sql = " UPDATE apt_result" .
            " SET resend_yn = 'Y'" .
            " 	 ,check_tm = NOW()" .
            "	 ,syncid = ?" .
            " WHERE rcpt_no = ? ";


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

        $this->saveHistory($rcpt_no, 'S05', 'J', 'J1', session('usr_id'));

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


    // 업로드 파일정보 저장
    public function saveImg($params)
    {
        $sql = "INSERT INTO apt_photo 
                (rcpt_no, pho_lati, pho_long, filenm, filenm_up, pho_view_yn, pho_date, insert_tm, file_path, use_yn, thumb_path, thumb_nm, cloud_upload_yn)
                VALUES
                (
                    {$params['rcpt_no']},
                    '{$params['gps_lat']}',
                    '{$params['gps_lon']}',
                    '{$params['origin_name']}',
                    '{$params['file_name']}',
                    'Y',
                    '{$params['cam_date']}',
                    NOW(),
                    '{$params['upload_path']}',
                    'Y',
                    '{$params['upload_path']}',
                    '{$params['thumb_name']}',
                    'Y'                    
                )                                
                ";

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

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

    // 동영상 정보 저장
    public function saveVideo($params)
    {
        $sql = "INSERT INTO apt_photo 
                (rcpt_no, pho_cate1, pho_cate2, filenm, filenm_up, insert_tm, file_path, use_yn, cloud_upload_yn)
                VALUES
                (
                {$params['rcpt_no']},
                'V',
                'V01',
                '{$params['origin_name']}',
                '{$params['file_name']}',
                NOW(),
                '{$params['upload_path']}',
                'Y',
                'Y'
                )
                ";

        // print ($sql);

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

        $sql = "UPDATE apt_result" .
            " SET vdo_up_ynx = 'Y'" .
            "	,not_vdo_reson = ''" .
            "	,video_target = 'Y'" .
            "	,not_vdo_tm = NULL " .
            "	,vdo_up_tm = NOW() " .
            "	,apt_step = 'S03'" .
            " WHERE rcpt_no = {$params['rcpt_no']}";

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

        // print ($sql);

        //히스토리
        $this->saveHistory($params['rcpt_no'], 'S03', 'F', 'F1', session('usr_id'));

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


    // 업로드파일 일괄삭제
    public function removeAllPho($rcpt_no)
    {
        $sql = "UPDATE apt_photo" .
            " SET use_yn = 'N'" .
            " WHERE rcpt_no = ? ";

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

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

    // 선택파일 삭제
    public function removePho($params)
    {
        $builder = $this->db->table('apt_photo');

        $builder->whereIn('pho_no', $params);

        $result = $builder->update([
            'use_yn' => 'N',
        ]);

        if ($result === false) {
            return [
                'success' => false,
                'msg' => 'DB 업데이트 실패',
            ];
        }

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

    // 카테고리 지정
    public function updatePhoCate($data)
    {
        $sql = "UPDATE apt_photo SET 
                pho_cate1 = '{$data['code1']}',
                pho_cate2 = '{$data['code2']}'
                WHERE pho_no = {$data['pho_no']}
                ";

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

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