<?php
namespace App\Models\article;

use CodeIgniter\Model;

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

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

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

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

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

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

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

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


        return $query->getResultArray();
    }


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

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


        return $query->getResultArray();
    }

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

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


        return $query->getResultArray();
    }

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

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

        return $query->getResultArray();
    }

    public function getTotalCount($data)
    {
        $sql = "SELECT COUNT(*) AS cnt 
                FROM apt_ground AS a
                LEFT JOIN apt_ground_photo AS gp ON gp.pho_no = (SELECT p.pho_no
                    FROM apt_ground_photo p
                    WHERE p.rcpt_no = a.rcpt_no
                    ORDER BY p.pho_no DESC
                    LIMIT 1)
                LEFT JOIN users b ON a.charger = b.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq
                LEFT JOIN codes f ON a.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON a.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON a.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['hscp_no'])) {
            $sql .= "AND a.hscp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else {

            if (!empty($data['hscp_no'])) {
                $sql .= "AND a.part_no LIKE CONCAT('%', '{$data['part_no']}', '%') ";
            }

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

            // 법정동코드로 지역구분
            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['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 a.apt_step IN ({$statList}) ";
            }

        }


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


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

    public function getAptLists($start, $end, $data)
    {
        $sql = "SELECT
                    a.rcpt_no, a.hscp_no, a.part_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,
                    a.charger, a.memo, a.write_complete_yn, a.gpho_up_yn, a.vdo_up_ynx, a.apt_step, a.video_target, a.all_no_pho, a.send_end_tm,
                    a.dept_sq, a.vdo_up_tm, a.not_vdo_tm, a.check_tm, a.write_complete_tm,
                    b.usr_nm, i.dept_nm, j.changed_tm, gp.pho_no, gp.filenm, gp.filenm_up, gp.file_path, gp.file_ext, gp.cloud_upload_yn, gp.insert_tm	
                FROM
                    apt_ground AS a
                LEFT JOIN apt_ground_photo AS gp ON gp.pho_no = (SELECT p.pho_no
                    FROM apt_ground_photo p
                    WHERE p.rcpt_no = a.rcpt_no
                    ORDER BY p.pho_no DESC
                    LIMIT 1)
                LEFT JOIN users b ON a.charger = b.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq
                LEFT JOIN codes f ON a.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON a.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON a.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['hscp_no'])) {
            $sql .= "AND a.hscp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else {

            if (!empty($data['hscp_no'])) {
                $sql .= "AND a.part_no LIKE CONCAT('%', '{$data['part_no']}', '%') ";
            }

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

            // 법정동코드로 지역구분
            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['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 a.apt_step IN ({$statList}) ";
            }

        }


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

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

        return $query->getResultArray();
    }


    // 조직별 통계
    public function getDeptStatistics($data)
    {
        $sql = "SELECT
                    a.dept_sq, IFNULL(f.dept_nm, '') AS bonbu_nm, IFNULL(i.dept_nm, '미지정') AS team_nm, COUNT(a.dept_sq) as cnt
                FROM
                    apt_ground a
                LEFT JOIN apt_ground_photo AS gp ON gp.pho_no = (SELECT p.pho_no
                                    FROM apt_ground_photo p
                                    WHERE p.rcpt_no = a.rcpt_no
                                    ORDER BY p.pho_no DESC
                                    LIMIT 1)
                LEFT JOIN users c ON a.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq
                LEFT JOIN departments f ON i.dept_sq = f.dept_sq ";

        $sql .= "WHERE 1=1 ";

        if (!empty($data['hscp_no'])) {
            $sql .= "AND a.hscp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else {

            if (!empty($data['hscp_no'])) {
                $sql .= "AND a.part_no LIKE CONCAT('%', '{$data['part_no']}', '%') ";
            }

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

            // 법정동코드로 지역구분
            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['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 a.apt_step IN ({$statList}) ";
            }

        }

        $sql .= "GROUP BY a.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_ground a
                LEFT JOIN apt_ground_photo gp ON a.rcpt_no = gp.rcpt_no
                LEFT JOIN users c ON a.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq ";

        $sql .= "WHERE 1=1 ";

        if (!empty($data['hscp_no'])) {
            $sql .= "AND a.hscp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else {

            if (!empty($data['hscp_no'])) {
                $sql .= "AND a.part_no LIKE CONCAT('%', '{$data['part_no']}', '%') ";
            }

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

            // 법정동코드로 지역구분
            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['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 a.apt_step IN ({$statList}) ";
            }

        }

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

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

        return $query->getResultArray();
    }

    // 엑셀 업로드 저장
    public function saveExcelUploadData($params)
    {
        $this->db->transStart();

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

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

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

        $this->saveHistory($rcpt_no, $params['apt_step'], 'U', 'U1', session('usr_id'));

        $this->db->transComplete();

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

    // 엑셀 다운로드
    public function getExcelList($data)
    {
        $sql = "SELECT
                    a.part_no AS '구분코드',
                    a.hscp_no AS '단지코드',
                    SUBSTRING_INDEX(a.addr, ' ', 1) AS '시도',
                    SUBSTRING_INDEX(a.addr, ' ', 2) AS '시군구',
                    SUBSTRING_INDEX(a.addr, ' ', 3) AS '읍면동',
                    a.addr2 AS '지번',
                    a.rcpt_hscp_nm AS '단지명',
                    a.apt_cate_nm AS '단지유형',
                    a.pyeong_cnt AS '평형',
                    i.dept_nm AS '방문팀',
                    b.usr_nm AS '담당자',
                    gp.insert_tm AS '촬영일자',
                    a.rcpt_x AS '단지X좌표',
					a.rcpt_y AS '단지Y좌표'	
                FROM
                    apt_ground AS a
                LEFT JOIN apt_ground_photo AS gp ON gp.pho_no = (SELECT p.pho_no
                    FROM apt_ground_photo p
                    WHERE p.rcpt_no = a.rcpt_no
                    ORDER BY p.pho_no DESC
                    LIMIT 1)
                LEFT JOIN users b ON a.charger = b.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq
                LEFT JOIN codes f ON a.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON a.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON a.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['hscp_no'])) {
            $sql .= "AND a.hscp_no LIKE CONCAT('%', '{$data['hscp_no']}', '%') ";
        } else {

            if (!empty($data['hscp_no'])) {
                $sql .= "AND a.part_no LIKE CONCAT('%', '{$data['part_no']}', '%') ";
            }

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

            // 법정동코드로 지역구분
            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['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 a.apt_step IN ({$statList}) ";
            }

        }

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

        return $query->getResultArray();
    }

    // 지도 마커 조회
    public function getDeptMapList($deptSq)
    {
        $sql = "SELECT
                    a.hscp_no, a.rcpt_hscp_nm, a.rcpt_no, a.dept_sq, a.rcpt_x, a.rcpt_y
                    , a.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
                FROM
                    apt_ground a
                LEFT JOIN apt_ground_photo AS gp ON gp.pho_no = (SELECT p.pho_no
                                    FROM apt_ground_photo p
                                    WHERE p.rcpt_no = a.rcpt_no
                                    ORDER BY p.pho_no DESC
                                    LIMIT 1)
                LEFT JOIN users c ON a.charger = c.usr_id
                LEFT JOIN region_codes e ON a.region_cd = e.region_cd
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq
                LEFT JOIN codes f ON a.write_complete_yn = f.cd AND f.category = 'PHO_YN'
                LEFT JOIN codes h ON a.vdo_up_ynx = h.cd AND h.category = 'VDO_YN'
                LEFT JOIN codes g ON a.apt_step = g.cd AND g.category = 'APT_STEP' ";

        $sql .= "WHERE 1=1 ";

        if (!empty($deptSq)) {
            $datas = "'" . implode("','", $deptSq) . "'";
            $sql .= " AND a.dept_sq IN ({$datas}) ";
        }

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

        return $query->getResultArray();
    }

    // 아파트 담당자 정보변경
    public function updateAptDamdang($params)
    {
        $sql = "UPDATE apt_ground 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 getDetail($rcpt_no, $hscp_no)
    {
        $sql = "SELECT
                    a.rcpt_no, a.hscp_no, a.part_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.vdo_up_tm, DATE_FORMAT(a.vdo_up_tm, '%Y-%m-%d') as rdate_dt_vdo ,DATE_FORMAT(a.vdo_up_tm, '%H:%i:%s') as rdate_tm_vdo	   	    
                    ,a.check_tm, DATE_FORMAT(a.check_tm, '%Y-%m-%d') as rdate_dt_chk ,DATE_FORMAT(a.check_tm, '%H:%i:%s') as rdate_tm_chk
                    ,a.memo, a.note, a.video_target, a.vdo_up_ynx, a.not_vdo_reson, a.apt_step, a.check_yn, a.resend_yn, a.write_complete_yn, a.all_no_pho
                    ,a.write_complete_tm, DATE_FORMAT(a.write_complete_tm, '%Y-%m-%d') as rdate_dt_cmpl ,DATE_FORMAT(a.write_complete_tm, '%H:%i:%s') as rdate_tm_cmpl
                    ,a.charger, a.dept_sq ,(SELECT pdept_sq FROM departments WHERE dept_sq = a.dept_sq) bonbu
                    ,a.send_end_tm, a.supply_no_tm
                    ,d.pho_cate2, d.pho_explain, d.pho_up_nu
                    ,gp.pho_no ,gp.filenm_up, gp.file_path, gp.thumb_nm, gp.cloud_upload_yn, gp.insert_tm
                FROM
                    apt_ground a
                LEFT JOIN apt_category d ON a.rcpt_no = d.rcpt_no
                LEFT JOIN apt_ground_photo gp ON gp.pho_no = (SELECT p.pho_no
                                    FROM apt_ground_photo p
                                    WHERE p.rcpt_no = a.rcpt_no
                                    ORDER BY p.pho_no DESC
                                    LIMIT 1) AND gp.use_yn = 'Y'
                                    
                WHERE a.rcpt_no = {$rcpt_no} ";

        if (!empty($hscp_no)) {
            $sql .= "AND a.hscp_no = {$hscp_no}  ";
        }


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

        return $query->getRowArray();
    }

    // 동일단지
    public function getDetailLists($rcpt_no, $hscp_no)
    {
        $sql = "SELECT
                    a.rcpt_no, a.hscp_no, a.part_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.vdo_up_tm, DATE_FORMAT(a.vdo_up_tm, '%Y-%m-%d') as rdate_dt_vdo ,DATE_FORMAT(a.vdo_up_tm, '%H:%i:%s') as rdate_tm_vdo	   	    
                    ,a.check_tm, DATE_FORMAT(a.check_tm, '%Y-%m-%d') as rdate_dt_chk ,DATE_FORMAT(a.check_tm, '%H:%i:%s') as rdate_tm_chk
                    ,a.memo, a.note, a.video_target, a.vdo_up_ynx, a.not_vdo_reson, a.apt_step, a.check_yn, a.resend_yn, a.write_complete_yn, a.all_no_pho
                    ,a.write_complete_tm, DATE_FORMAT(a.write_complete_tm, '%Y-%m-%d') as rdate_dt_cmpl ,DATE_FORMAT(a.write_complete_tm, '%H:%i:%s') as rdate_tm_cmpl
                    ,a.charger, a.dept_sq ,(SELECT pdept_sq FROM departments WHERE dept_sq = a.dept_sq) bonbu, b.usr_nm, i.dept_nm
                    ,a.send_end_tm, a.supply_no_tm
                    ,d.pho_cate2, d.pho_explain, d.pho_up_nu
                    ,gp.pho_no, gp.filenm ,gp.filenm_up, gp.file_path, gp.thumb_nm, gp.cloud_upload_yn, gp.insert_tm
                FROM
                    apt_ground a
                LEFT JOIN apt_category d ON a.rcpt_no = d.rcpt_no
                LEFT JOIN apt_ground_photo gp ON gp.pho_no = (SELECT p.pho_no
                                    FROM apt_ground_photo p
                                    WHERE p.rcpt_no = a.rcpt_no
                                    ORDER BY p.pho_no DESC
                                    LIMIT 1) AND gp.use_yn = 'Y'
                LEFT JOIN users b ON a.charger = b.usr_id                    
                LEFT JOIN departments i ON a.dept_sq = i.dept_sq                    
                WHERE a.rcpt_no = {$rcpt_no} AND a.hscp_no != {$hscp_no} ";


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

        return $query->getResultArray();
    }

    // 정보변경이력
    public function getHistory($rcpt_no)
    {
        $sql = " SELECT seq," .
            "	rcpt_no, " .
            "	apt_step, get_code_name('APT_GROUND_STEP',apt_step) AS apt_step_nm, " .
            "	changed_type, get_code_name('APT_GROUND_CHANGED_TYPE',changed_type) AS changed_type_nm, " .
            "	changed_detail, get_code_name('APT_GROUND_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_ground_history" .
            " WHERE rcpt_no = ?" .
            " ORDER BY changed_tm DESC";



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

        return $query->getResultArray();
    }

    // 메모저장
    public function saveMemo($data)
    {
        $sql = "UPDATE apt_ground SET
                memo = '{$data['memo']}'
                WHERE rcpt_no = {$data['rcpt_no']}
                ";

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


        $row = $this->getDetail($data['rcpt_no'], "");
        $this->saveHistory($data['rcpt_no'], $row['apt_step'], 'C', 'A1', session('usr_id'));

        return [
            'success' => true,
        ];

    }

    // 담당자 변경
    public function saveKeeper($data)
    {
        $sql = "UPDATE apt_ground SET
                dept_sq = {$data['team']}, charger = '{$data['user']}'
                WHERE rcpt_no = {$data['rcpt_no']}
                ";

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

        $row = $this->getDetail($data['rcpt_no'], "");
        $this->saveHistory($data['rcpt_no'], $row['apt_step'], 'C', 'A1', session('usr_id'));

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

    // 단지상태변경
    public function statusChange($rcpt_no, $type)
    {
        $this->db->transStart();
        $data = [
            $rcpt_no
        ];


        if ($type === "phoX") {
            $detail = 'C1';


            $sql = "UPDATE apt_ground" .
                " SET gpho_up_yn = 'N'" .
                " ,apt_step = 'S01'" .
                " WHERE rcpt_no = ?";


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

            $sql = "delete from apt_ground_photo" .
                " WHERE rcpt_no = ?";

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


        } else if ($type === "phoY") {
            $detail = 'C3';

            $sql = "UPDATE apt_ground" .
                " SET gpho_up_yn = 'Y'" .
                " ,apt_step = 'S03'" .
                " WHERE rcpt_no = ?";

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

            $sql = "UPDATE apt_ground_photo" .
                " SET insert_tm = NOW()" .
                " WHERE rcpt_no = ?";

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

        } else if ($type === "sendE") {
            $detail = 'C4';

            $sql = "UPDATE apt_ground" .
                " SET send_end_tm = NOW()" .
                " ,supply_no_tm = NULL" .
                " ,apt_step = 'S04'" .
                " WHERE rcpt_no = ?";

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

        } else if ($type === "suppN") {
            $detail = 'C2';

            $sql = "UPDATE apt_ground" .
                " SET all_no_pho = 'Y'" .
                " ,apt_step = 'S02'" .
                " ,supply_no_tm = NOW()" .
                " ,send_end_tm = NULL" .
                " WHERE rcpt_no = ?";

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

        $row = $this->getDetail($rcpt_no, "");
        $this->saveHistory($rcpt_no, $row['apt_step'], 'E', $detail, session('usr_id'));

        $this->db->transComplete();

        return [
            'success' => true,
        ];

    }

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

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

        $row = $this->getDetail($data['rcpt_no'], "");
        $this->saveHistory($data['rcpt_no'], $row['apt_step'], 'C', 'D1', session('usr_id'));

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

    // 평면도 정보 저장
    public function saveImg($data)
    {
        $this->db->transStart();

        $sql = "INSERT INTO apt_ground_photo 
                (rcpt_no, filenm, filenm_up, file_ext, insert_tm, file_path, thumb_path, thumb_nm, use_yn, cloud_upload_yn)
                VALUES
                ({$data['rcpt_no']}, '{$data['origin_name']}', '{$data['file_name']}', '{$data['file_ext']}', NOW(), '{$data['upload_path']}', '{$data['upload_path']}'
                , '{$data['thumb_name']}', 'Y', 'Y')
                ";


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


        $sql = "UPDATE apt_ground SET
                gpho_up_yn = 'Y', apt_step = 'S03'
                WHERE rcpt_no = {$data['rcpt_no']}
                ";

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

        $this->db->transComplete();

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


    // 이력 저장
    public function saveHistory($rcpt_no, $apt_step, $changed_type, $changed_detail, $charged_id)
    {
        $sql = "INSERT INTO apt_ground_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);
    }

}