<?php
namespace App\Models\article;

use CodeIgniter\Model;

class RecordModel 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)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');

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

    $builder->select("COUNT(*) AS cnt", false);

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'inner');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd', 'inner');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left');
    $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left');

    $builder->where('a.rcpt_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);
    if (in_array($usr_level, ['4', '40'])) {
      if (!empty($child_dept)) {
        $builder->whereIn('b.dept_sq', $child_dept);
      } else {
        $builder->where('b.usr_sq', $usr_sq);
      }
    }

    $builder->where('b.req_rec_yn', 'Y');

    if (!empty($data['rcpt_atclno'])) {
      $builder->where('a.rcpt_atclno', $data['rcpt_atclno']);
    } else {

      // 접수기간
      if (!empty($data['sdate'])) {
        $builder->where('a.insert_tm >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('a.insert_tm <=', $data['edate'] . ' 23:59:59');
      }

      //
      if (!empty($data['photo_sdate'])) {
        $builder->where('b.photo_save_dt >=', $data['photo_sdate'] . ' 00:00:00');
      }

      if (!empty($data['photo_edate'])) {
        $builder->where('b.photo_save_dt <=', $data['photo_edate'] . ' 23:59:59');
      }

      if (!empty($data['record_sdate'])) {
        $builder->where('b.record_cplt_dt >=', $data['record_sdate'] . ' 00:00:00');
      }

      if (!empty($data['record_edate'])) {
        $builder->where('b.record_cplt_dt <=', $data['record_edate'] . ' 23:59:59');
      }

      // 녹취완료여부
      if (!empty($data['rec_yn'])) {
        if ($data['rec_yn'] == "Y") {
          $builder->where('b.rec_yn', $data['rec_yn']);
          $builder->whereNotIn('b.result_cd1', [40, 70]);
        } else {
          $builder->where('b.rec_yn', $data['rec_yn']);
          $builder->whereIn('b.result_cd1', [40, 70]);
        }
      }


      // 지역
      if (!empty($data['dong'])) {
        $builder->where('a.rcpt_dong', $data['dong']);
      } else {
        if (!empty($data['gugun'])) {
          $builder->like('a.rcpt_gugun', substr($data['gugun'], 0, 5), 'after');
        } else {
          if (!empty($data['sido'])) {
            $builder->like('a.rcpt_gugun', substr($data['sido'], 0, 2), 'after');
          }
        }
      }

      // 관할조직
      if (!empty($data['bonbu'])) {
        $builder->where('d.pdept_sq', $data['bonbu']);
      }

      if (!empty($data['team'])) {
        $builder->where('d.dept_sq', $data['team']);
      }

      if (!empty($data['user'])) {
        $builder->where('d.usr_sq', $data['user']);
      }

      // 검색어
      if (!empty($data['srchTxt'])) {
        if ($data['srchType'] == "1") {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();
        } else if ($data['srchType'] == "2") {
          $builder->groupStart()
            ->like('b.rec_nm', $data['srchTxt'])
            ->groupEnd();
        } else if ($data['srchType'] == "3") {
          $builder->groupStart()
            ->like('b.rec_tel', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->orLike('b.rec_nm', $data['srchTxt'])
            ->orLike('b.rec_tel', $data['srchTxt'])
            ->groupEnd();
        }
      }

    }


    $row = $builder->get()->getRowArray();
    return (int) ($row['cnt'] ?? 0);

  }

  public function getResultList($start, $end, $data)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');


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

    $builder->select("a.rcpt_sq
			         ,a.comp_sq
			         ,a.rcpt_rating
			         ,a.rcpt_key
			   	  ,a.rcpt_atclno
			         ,a.rcpt_type
			         ,a.rcpt_product
			         ,a.rcpt_product_nm
			         ,a.rcpt_product_area
			         ,a.rcpt_product_price
			         ,a.rcpt_product_info1
			         ,a.rcpt_product_info2
			         ,a.rcpt_product_info3
			         ,a.rcpt_product_info4
			         ,a.rcpt_product_info5
			         ,a.rcpt_office
			         ,(CASE WHEN a.rcpt_agent IS NULL THEN 'N' ELSE 'Y' END) as rcpt_agent
			         ,a.rcpt_sido
			         ,a.rcpt_gugun
			         ,a.rcpt_dong
			         ,a.rcpt_hscp_nm
			   	  ,a.rcpt_floor
			         ,a.rcpt_tm
			         ,a.rcpt_stat
			         ,a.rcpt_x
			         ,a.rcpt_y
			         ,a.cust_nm
			         ,a.cust_tel1
			         ,a.cust_tel2
			         ,a.cust_zip
			         ,a.cust_addr1
			         ,a.cust_addr2
			         ,a.remark
			         ,a.agent_id
			         ,a.agent_nm
			         ,a.agent_head
			         ,a.agent_head_tel
			         ,a.agent_contact
			         ,a.agent_contact_tel
			         ,a.agent_fax
			         ,DATE_FORMAT(COALESCE(b.rsrv_date, a.rsrv_date), '%Y-%m-%d') AS rsrv_date
			         ,COALESCE(b.rsrv_tm_ap, a.rsrv_tm_ap) as rsrv_tm_ap
			         ,a.insert_usr
			         ,a.insert_tm
			         ,a.update_usr
			         ,a.update_tm
			         ,a.svc_type1
			         ,a.svc_type2
			         ,a.reconf_yn
			         ,b.rsrv_sq
			   	  ,b.dept_sq
			         ,b.usr_sq
			   	  ,b.req_rec_yn
			   	  ,b.rec_yn
			         ,b.rsrv_tm_hour
			         ,b.result_cd1
			         ,b.result_cd2
			   	  ,b.result_cd3
			   	  ,b.rec_nm
			   	  ,b.rec_tel
			         ,b.result_msg
			   	  ,b.photo_save_dt
			   	  ,b.rsrv_delay_dt
			   	  ,b.rsrv_cplt_dt
			   	  ,b.check_dt
			   	  ,b.check_cplt_dt
			   	  ,b.record_cplt_dt
		       	  ,get_code_name('RECEIPT_STATUS1', substring(a.rcpt_stat, 1, 2)) AS rcpt_stat_nm
		       	  ,c.region_nm as addr
			         ,b.result_save_dt
			   	  ,u.usr_nm
			         ,d.dept_nm", false);

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'inner');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd', 'inner');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left');
    $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left');

    $builder->where('a.rcpt_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);
    if (in_array($usr_level, ['4', '40'])) {
      if (!empty($child_dept)) {
        $builder->whereIn('b.dept_sq', $child_dept);
      } else {
        $builder->where('b.usr_sq', $usr_sq);
      }
    }

    $builder->where('b.req_rec_yn', 'Y');

    if (!empty($data['rcpt_atclno'])) {
      $builder->where('a.rcpt_atclno', $data['rcpt_atclno']);
    } else {

      // 접수기간
      if (!empty($data['sdate'])) {
        $builder->where('a.insert_tm >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('a.insert_tm <=', $data['edate'] . ' 23:59:59');
      }

      //
      if (!empty($data['photo_sdate'])) {
        $builder->where('b.photo_save_dt >=', $data['photo_sdate'] . ' 00:00:00');
      }

      if (!empty($data['photo_edate'])) {
        $builder->where('b.photo_save_dt <=', $data['photo_edate'] . ' 23:59:59');
      }

      if (!empty($data['record_sdate'])) {
        $builder->where('b.record_cplt_dt >=', $data['record_sdate'] . ' 00:00:00');
      }

      if (!empty($data['record_edate'])) {
        $builder->where('b.record_cplt_dt <=', $data['record_edate'] . ' 23:59:59');
      }

      // 녹취완료여부
      if (!empty($data['rec_yn'])) {
        if ($data['rec_yn'] == "Y") {
          $builder->where('b.rec_yn', $data['rec_yn']);
          $builder->whereNotIn('b.result_cd1', [40, 70]);
        } else {
          $builder->where('b.rec_yn', $data['rec_yn']);
          $builder->whereIn('b.result_cd1', [40, 70]);
        }
      }


      // 지역
      if (!empty($data['dong'])) {
        $builder->where('a.rcpt_dong', $data['dong']);
      } else {
        if (!empty($data['gugun'])) {
          $builder->like('a.rcpt_gugun', substr($data['gugun'], 0, 5), 'after');
        } else {
          if (!empty($data['sido'])) {
            $builder->like('a.rcpt_gugun', substr($data['sido'], 0, 2), 'after');
          }
        }
      }

      // 관할조직
      if (!empty($data['bonbu'])) {
        $builder->where('d.pdept_sq', $data['bonbu']);
      }

      if (!empty($data['team'])) {
        $builder->where('d.dept_sq', $data['team']);
      }

      if (!empty($data['user'])) {
        $builder->where('d.usr_sq', $data['user']);
      }

      // 검색어
      if (!empty($data['srchTxt'])) {
        if ($data['srchType'] == "1") {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();
        } else if ($data['srchType'] == "2") {
          $builder->groupStart()
            ->like('b.rec_nm', $data['srchTxt'])
            ->groupEnd();
        } else if ($data['srchType'] == "3") {
          $builder->groupStart()
            ->like('b.rec_tel', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->orLike('b.rec_nm', $data['srchTxt'])
            ->orLike('b.rec_tel', $data['srchTxt'])
            ->groupEnd();
        }
      }

    }

    $builder->orderBy('a.rcpt_atclno DESC');

    $builder->limit($end, $start);

    $rows = $builder->get()->getResultArray();

    return $rows;
  }


  // 엑셀다운로드
  public function getExcelList($data)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');

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

    $builder->select("
                                get_code_name('RECEIPT_STATUS1', b.result_cd1)	AS '현재상태',
                                CASE WHEN b.result_cd1 = '90' THEN get_code_name('RECEIPT_STATUS2', b.result_cd2) ELSE '' END AS '매물ID',
                                CASE WHEN b.result_cd1 = '90' THEN get_code_name('RECEIPT_STATUS3', b.result_cd3) ELSE '' END AS '접수(등록)일자',
                                a.rcpt_atclno AS '예약일자',
                                a.insert_tm  '방문희망시간',
                                CONCAT(b.rsrv_date, ' ', b.rsrv_tm_ap) AS '촬영완료일자',
                                b.rsrv_tm_hour AS '중개사명',
                                b.photo_save_dt AS '대표전화',
                                '' AS '담당자전화',
                                a.agent_head_tel AS '연락가능전화',
                                '' AS '중개사ID',
                                a.rcpt_cpid  'CP ID',
                                CASE
                                    WHEN IFNULL(a.rcpt_jibun_addr, '') = '' THEN
                                        CASE
                                            WHEN IFNULL(a.rcpt_hscp_nm, '') = '' THEN
                                                CONCAT(c.region_nm, ' ', a.rcpt_dtl_addr, ' ', a.rcpt_ho)
                                            ELSE
                                                CONCAT(c.region_nm, ' ', a.rcpt_hscp_nm, ' ', a.rcpt_dtl_addr, ' ', a.rcpt_ho)
                                        END
                                    ELSE
                                        CASE
                                            WHEN IFNULL(a.rcpt_li_addr, '') != '' THEN
                                                CONCAT(c.region_nm, ' ', a.rcpt_li_addr, ' ', a.rcpt_jibun_addr, ' ', a.rcpt_etc_addr)
                                            ELSE
                                                CONCAT(c.region_nm, ' ', a.rcpt_jibun_addr, ' ', a.rcpt_etc_addr)
                                        END
                                END AS '주소',
                                CONCAT(a.rcpt_floor, '/', a.rcpt_floor2) AS '층',
                                a.rcpt_product_nm AS '매물종류',
                                a.rcpt_product_info1 AS '거래구분',
                                d.dept_nm AS '관할조직(팀)',
                                u.usr_nm AS '방문담당',
                                a.rcpt_exps_type AS '노출옵션',
                                CASE (SELECT COUNT(1) FROM result_imgs WHERE rsrv_sq = b.rsrv_sq AND img_type = 'I1' AND use_yn = 'Y')
                                                                        WHEN 0 THEN 'N' ELSE 'Y' END AS '홍보확인서',
                                a.exp_movie_yn AS '동영상촬영',
                                a.exp_spc_yn AS '면적확인',
                                b.resYn AS '거주여부',
                                (CASE (SELECT 'x' FROM result_record WHERE rsrv_sq = b.rsrv_sq AND use_yn = 'Y')
                                                                        WHEN 'x' THEN 'Y' ELSE 'N' END) AS '녹취여부',
                                a.excls_spc AS '전용면적',
                                a.sply_spc AS '공급면적',
                                a.cupnNo AS '쿠폰번호',
                                a.image_360_yn AS '360촬영여부',
                                a.rcpt_y AS '경도',
                                a.rcpt_y AS '위도',
                                a.check_list_img_yn AS '체크리스트',
                                ", false);

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'inner');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd', 'inner');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left');
    $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left');


    $login_dept_info = $this->getDeptDetail($dept_sq);	// 로그인 사용자 소속부서정보
    $child_dept = [];													// 하위조직 목록
    if (strcmp($usr_level, '40') == 0) {
      $child = $this->getChildDept($login_dept_info);
      if (!empty($child)) {
        foreach ($child as $child) {
          $child_dept[] = $child['dept_sq'];
        }
      }
    }

    if ((int) $usr_level >= 4 && $usr_level != '45') {
      if (!empty($child_dept)) {
        $builder->whereIn('b.dept_sq', $child_dept);
      } else {
        $builder->where('b.usr_sq', $usr_sq);
      }
    }

    $builder->where('a.rcpt_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);

    if (!empty($data['rcpt_atclno'])) {
      $builder->where('a.rcpt_atclno', $data['rcpt_atclno']);
    } else {
      if ($data['schDateGb'] == '1') {
        $builder->where('a.rcpt_tm >=', $data['sdate'] . ' 00:00:00');
        $builder->where('a.rcpt_tm <=', $data['edate'] . ' 23:59:59');
      } else if ($data['schDateGb'] == '2') {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
        $builder->where('b.rsrv_date <=', $data['edate'] . ' 23:59:59');
      }

      // 지역
      if (!empty($data['dong'])) {
        $builder->where('a.rcpt_dong', $data['dong']);
      } else {
        if (!empty($data['gugun'])) {
          $builder->like('a.rcpt_gugun', substr($data['gugun'], 0, 5), 'after');
        } else {
          if (!empty($data['sido'])) {
            $builder->like('a.rcpt_gugun', substr($data['sido'], 0, 2), 'after');
          }
        }
      }

      // 관할조직
      if (!empty($data['bonbu'])) {
        $builder->where('d.pdept_sq', $data['bonbu']);
      }

      if (!empty($data['team'])) {
        $builder->where('d.dept_sq', $data['team']);
      }

      if (!empty($data['user'])) {
        $builder->where('d.usr_sq', $data['user']);
      }

      // 거래구분
      if (!empty($data['rcpt_product_info1'])) {
        $builder->where('a.rcpt_product_info1', $data['rcpt_product_info1']);
      }

      // 현재상태
      if (!empty($data['rcpt_stat1'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat1'], 'after');
      }

      if (!empty($data['rcpt_stat2'])) {
        $builder->like('a.rcpt_stat', $data['rcpt_stat2'], 'after');
      }

      if (!empty($data['rcpt_stat3'])) {
        $builder->where('a.rcpt_stat', $data['rcpt_stat3']);
      }

      // 중개사명
      if (!empty($data['agent_nm'])) {
        $builder->like('a.agent_nm', $data['agent_nm'], 'both');
      }

      // 동영상촬영여부
      if (!empty($data['exp_movie_yn'])) {
        $builder->where('a.exp_movie_yn', $data['exp_movie_yn']);
      }

      // 홍보확인서여부
      if ($data['conf_img_yn'] == 'Y') {
        $builder->where('e.rsrv_sq IS NOT NULL', null, false);
      } else if ($data['conf_img_yn'] == 'N') {
        $builder->where('e.rsrv_sq IS NULL', null, false);
      }

      // 분양권
      if ($data['parcel_out_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['parcel_out_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // CP ID
      if (!empty($data['rcpt_cpid'])) {
        if (strcmp($data['rcpt_cpid'], 'naver') == 0) {
          $builder->where('a.rcpt_cpid =', '');
        } else if (strcmp($data['rcpt_cpid'], 'cleancente') == 0) {
          $builder->where("a.rcpt_cpid !=", "");
        } else {
          $builder->where('a.rcpt_cpid', $data['rcpt_cpid']);
        }
      }

      // 매물종류
      if (!empty($data['rcpt_product'])) {
        $builder->where('a.parcel_out_yn', $data['rcpt_product']);
      }

      // 면적확인
      if ($data['exp_spc_yn'] == 'Y') {
        $builder->where('a.parcel_out_yn', 'Y');
      } else if ($data['exp_spc_yn'] == 'N') {
        $builder->where('a.parcel_out_yn', 'N');
      }

      // 체크리스트
      if ($data['check_list_img_yn'] == 'Y') {
        $builder->where('a.check_list_img_yn', 'Y');
      } else if ($data['check_list_img_yn'] == 'N') {
        $builder->where('a.check_list_img_yn', 'N');
      }

      // 평면도유무
      if ($data['ground_plan_yn'] == 'Y') {
        $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      } else if ($data['ground_plan_yn'] == 'N') {
        $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I5\' and imgs.use_yn=\'Y\')', NULL, FALSE);
      }

      // 평면도요청
      if (!empty($data['ground_plan'])) {
        $builder->where('a.ground_plan', $data['ground_plan']);
      }

      // 직거래
      if ($data['direct_trad_yn'] == "Y") {
        $builder->where('a.direct_trad_yn', 'Y');
      } else if ($data['direct_trad_yn'] == "N") {
        $builder->where('a.direct_trad_yn', 'N');
      }

      // 360촬영여부
      if ($data['image_360_yn'] == "Y") {
        $builder->where('a.image_360_yn', 'Y');
      } else if ($data['image_360_yn'] == "N") {
        $builder->where('a.image_360_yn', 'N');
      }

      if (!empty($data['srchTxt'])) {
        // 중개사
        if ($data['srchType'] == '1') {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          // 주소                        
        } else if ($data['srchType'] == '2') {
          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          // 사업자번호        
        } else if ($data['srchType'] == '3') {
          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          $builder->groupStart()
            ->like('a.rcpt_dtl_addr', $data['srchTxt'])
            ->orLike('a.rcpt_hscp_nm', $data['srchTxt'])
            ->orLike('a.rcpt_jibun_addr', $data['srchTxt'])
            ->groupEnd();

          $builder->like('a.image_360_yn', $data['srchTxt'], 'both');
        }
      }

    }


    $builder->orderBy('a.rcpt_atclno', 'DESC');

    return $builder->get()->getResultArray();
  }

  // 상세
  public function getDetail($id)
  {

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

    $builder->select("
                                a.rcpt_sq
			   	                ,a.comp_sq
			   	                ,a.excls_spc
			                    ,a.rcpt_rating
			                    ,a.rcpt_key
			   	                ,a.rcpt_atclno
			                    ,a.rcpt_type
			                    ,a.rcpt_product
			                    ,a.rcpt_product_nm
			                    ,a.rcpt_product_area
			                    ,a.rcpt_product_price
			   	                , a.rcpt_deal_type
			                    ,a.rcpt_product_info1
			                    ,a.rcpt_product_info2
			                    ,a.rcpt_product_info3
			                    ,a.rcpt_product_info4
			                    ,a.rcpt_product_info5
			                    ,a.rcpt_office
			                    ,(CASE WHEN a.rcpt_agent IS NULL THEN 'N' ELSE 'Y' END) as rcpt_agent
			                    ,a.rcpt_sido
			                    ,a.rcpt_gugun
			                    ,a.rcpt_dong
			                    ,a.rcpt_dtl_addr
			                    ,a.rcpt_li_addr
			                    ,a.rcpt_jibun_addr
			                    ,a.rcpt_etc_addr
			                    ,a.rcpt_ref_addr
			                    ,a.rcpt_ho
			                    ,a.rcpt_hscp_nm
			   	                ,a.rcpt_floor
			   	                ,a.rcpt_floor2
			   	                ,a.chg_floor_yn
			                    ,a.rcpt_tm
			                    ,a.rcpt_stat
			                    ,a.rcpt_x
			                    ,a.rcpt_y
			   	                ,a.rcpt_living_yn
			                    ,a.cust_nm
			                    ,a.cust_tel1
			                    ,a.cust_tel2
			                    ,a.cust_zip
			                    ,a.cust_addr1
			                    ,a.cust_addr2
			                    ,a.remark rcpt_remark
			   	                , a.rcpt_cpid
			                    ,a.agent_id
			                    ,a.agent_nm
			                    ,a.agent_head
			                    ,a.agent_head_tel
			                    ,a.agent_contact
			                    ,a.agent_contact_tel
			                    ,a.agent_fax
			                    ,a.agent_tel
			                    ,a.excls_spc
			                    ,a.excls_spc1
			                    ,a.excls_spc2
			                    ,a.sply_spc
			                    ,a.share_spc
			                    ,a.share_spc1
			                    ,a.share_spc2
			                    ,a.share_spc3
			                    ,a.share_spc4
			                    ,a.share_spc5
			                    ,a.room_cnt
			                    ,a.tot_spc
			                    ,a.tot_spc1
			                    ,a.tot_spc2
			                    ,a.grnd_spc
			                    ,a.grnd_spc1
			                    ,a.grnd_spc2
			                    ,a.grnd_spc3
			                    ,a.grnd_spc4
			                    ,a.grnd_spc5
			                    ,a.spc_stat
			                    ,a.exp_spc_yn
			                    ,DATE_FORMAT(COALESCE(b.rsrv_date, a.rsrv_date), '%Y-%m-%d') AS rsrv_date
			                    ,COALESCE(b.rsrv_tm_ap, a.rsrv_tm_ap) as rsrv_tm_ap
			                    ,a.insert_usr
			                    ,a.insert_tm
			                    ,a.update_usr
			                    ,a.update_tm
			                    ,a.svc_type1
			                    ,a.svc_type2
			                    ,a.reconf_yn
			                    ,a.cupnNo
			                    ,b.rsrv_sq
			   	                ,b.dept_sq
			                    ,b.usr_sq
			   	                ,b.req_rec_yn
			   	                ,b.rec_yn
			   	                ,b.rec_tel
			   	                ,b.rec_nm
			   	                ,b.remark
			                    ,b.rsrv_tm_hour
			                    ,b.result_cd1
			   	                ,get_code_name('RECEIPT_STATUS1', b.result_cd1) AS result_cd1_nm
			                    ,b.result_cd2
			   	                ,get_code_name('RECEIPT_STATUS2', b.result_cd2) AS result_cd2_nm
			   	                ,b.result_cd3
			   	                ,get_code_name('RECEIPT_STATUS3', b.result_cd3) AS result_cd3_nm
			                    ,b.result_msg
			   	                ,b.rsrv_save_dt
			   	                ,b.photo_save_dt
			   	                ,DATE_FORMAT(b.photo_save_dt, '%Y-%m-%d') as photo_save_dt_dt
			   	                ,DATE_FORMAT(b.photo_save_dt, '%H:%i:%s') as photo_save_dt_tm
			   	                ,b.assign_save_dt
			   	                ,b.result_save_dt
			   	                ,b.request_msg
			   	                ,b.rsrv_delay_dt
			   	                ,DATE_FORMAT(b.rsrv_delay_dt, '%Y-%m-%d') as rsrv_delay_dt_dt
			   	                ,DATE_FORMAT(b.rsrv_delay_dt, '%H:%i:%s') as rsrv_delay_dt_tm
			   	                ,b.rsrv_cplt_dt
			   	                ,DATE_FORMAT(b.rsrv_cplt_dt, '%Y-%m-%d') as rsrv_cplt_dt_dt
			   	                ,DATE_FORMAT(b.rsrv_cplt_dt, '%H:%i:%s') as rsrv_cplt_dt_tm
			   	                ,b.check_dt
			   	                ,DATE_FORMAT(b.check_dt, '%Y-%m-%d') as check_dt_dt
			   	                ,DATE_FORMAT(b.check_dt, '%H:%i:%s') as check_dt_tm
			   	                ,b.check_cplt_dt
			   	                ,DATE_FORMAT(b.check_cplt_dt, '%Y-%m-%d') as check_cplt_dt_dt
			   	                ,DATE_FORMAT(b.check_cplt_dt, '%H:%i:%s') as check_cplt_dt_tm
			   	                ,b.cancel_dt
			   	                ,DATE_FORMAT(b.cancel_dt, '%Y-%m-%d') as cancel_dt_dt
			   	                ,DATE_FORMAT(b.cancel_dt, '%H:%i:%s') as cancel_dt_tm
			   	                ,b.check_delay_dt
			   	                ,DATE_FORMAT(b.check_delay_dt, '%Y-%m-%d') as check_delay_dt_dt
			   	                ,DATE_FORMAT(b.check_delay_dt, '%H:%i:%s') as check_delay_dt_tm
			   	                ,b.check_fail_dt
			   	                ,DATE_FORMAT(b.check_fail_dt, '%Y-%m-%d') as check_fail_dt_dt
			   	                ,DATE_FORMAT(b.check_fail_dt, '%H:%i:%s') as check_fail_dt_tm
			                    ,get_code_name('RECEIPT_STATUS3', a.rcpt_stat) AS rcpt_stat_nm
			                    ,DATE_FORMAT(a.insert_tm, '%Y년 %m월 %d일') as insert_tm2
			                    ,DATE_FORMAT(a.rsrv_date, '%Y-%m-%d') as rsrv_date2	
			                    ,c.region_nm as addr
			                    ,c.dept_sq as region_dept_sq
			   	                ,c.usr_sq as region_usr_sq
			   	                ,d.pdept_sq
			   	                ,d.dept_nm
			   	                ,a.rcpt_exps_type
			   	                ,a.exp_photo_yn
			   	                ,a.exp_movie_yn
			   	                ,b.resYn
			   	                ,DATE_ADD(a.insert_tm, INTERVAL +3 MONTH) as months
			   	                ,b.dbUsageAgrYn
			   	                ,a.trade_type
			   	                , a.rcpt_hscp_no
			   	                , a.rcpt_ptp_nm
			   	                , a.rcpt_ptp_no
			   	                , a.modify_yn
			   	                , a.ground_plan
			   	                ,a.direct_trad_yn
			   	                ,a.sellr_nm
			   	                ,a.sellr_tel_no
			   	                ,a.virAddr_yn
			   	                ,a.isSiteVRVerification
			   	                ,a.isPromotionApply
			   	                ,DATE_FORMAT(b.vr_check_cplt_dt, '%Y-%m-%d') as vr_check_cplt_dt_dt
			   	                ,DATE_FORMAT(b.vr_check_cplt_dt, '%H:%i:%s') as vr_check_cplt_dt_dm
                                ", false);

    $builder->join('result b', 'b.rcpt_sq = a.rcpt_sq', 'inner');
    $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd', 'inner');
    $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left');

    $builder->where('a.rcpt_key', $id);
    $builder->where('a.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', NULL, FALSE);


    return $builder->get()->getRowArray();
  }

  // 정보변경이력
  public function getHistory($id)
  {
    $sql = "SELECT seq" .
      "      ,rcpt_sq" .
      "      ,rcpt_stat" .
      "      ,get_code_name('RECEIPT_STATUS3', rcpt_stat) AS rcpt_stat_nm" .
      "      ,rcpt_stat" .
      "      ,get_code_name('CHANGED_TYPE', changed_type) AS changed_type_nm" .
      "      ,changed_type" .
      "      ,changed_id" .
      "      ,remark" .
      "      ,DATE_FORMAT(changed_tm, '%Y.%m.%d %H:%i:%s') as changed_tm" .
      "  FROM changed_history" .
      " WHERE rcpt_sq = ?" .
      " ORDER BY changed_tm DESC";

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

    return $query->getResultArray();
  }

  // 시간대별통계
  public function getUsrRsrvDateTmCount($id)
  {
    $sql = "SELECT b.usr_sq, b.rsrv_date FROM receipt a INNER JOIN result b ON a.rcpt_sq = b.rcpt_sq WHERE a.rcpt_key = ?";
    $data = [$id];
    $query = $this->db->query($sql, $data);
    $row = $query->getRowArray();

    if (!empty($row['usr_sq'])) {
      $sql2 = "SELECT usr_sq, rsrv_tm_ap, rsrv_tm_hour, COUNT(rsrv_tm_hour) as cnt" .
        "  FROM result" .
        " WHERE rsrv_date = ?" .
        "   AND usr_sq = ?" .
        " GROUP BY usr_sq, rsrv_tm_ap, rsrv_tm_hour" .
        " ORDER BY rsrv_tm_ap, rsrv_tm_hour";

      $data2 = [$row['rsrv_date'], $row['usr_sq']];
    } else {
      $sql2 = "SELECT usr_sq, rsrv_tm_ap, rsrv_tm_hour, COUNT(rsrv_tm_hour) as cnt" .
        "  FROM result" .
        " WHERE rsrv_date = ?" .
        "   AND usr_sq = (SELECT b.usr_sq FROM receipt a, region_codes b WHERE a.rcpt_dong = b.region_cd AND a.rcpt_key = ?)" .
        " GROUP BY usr_sq, rsrv_tm_ap, rsrv_tm_hour" .
        " ORDER BY rsrv_tm_ap, rsrv_tm_hour";

      $data2 = [$row['rsrv_date'], $id];
    }

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

    return $query2->getResultArray();
  }

  public function getAptGround($rcpt_dong)
  {

    $sql = "SELECT                           ";
    $sql .= "*                                ";
    $sql .= "FROM apt_ground                  ";
    $sql .= "WHERE region_cd = ?              ";

    $data = [$rcpt_dong];

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

    return $query->getResultArray();

  }
}