<?php
namespace App\Models\article;

use CodeIgniter\Model;

class DeptModel 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 getDeptDetail($dept_sq)
  {
    $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 dept_sq = ?";

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

    return $row;
  }

  // 조직별통계
  public function getDeptStatistics($data)
  {

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

    $builder->select("b.dept_sq, e.dept_nm as bonbu_nm, d.dept_nm as team_nm, COUNT(b.dept_sq) as cnt");

    $builder->join('result b', 'a.rcpt_sq = b.rcpt_sq', 'left');
    $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->join('departments e', 'd.pdept_sq = e.dept_sq', 'left');

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

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

      // $builder->where('a.isSiteVRVerification', 'N');

      // 접수일자
      /*
      if (!empty($data['sdate'])) {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('b.rsrv_date >=', $data['edate'] . ' 23:59:59');
      }
      */

      // if (!empty($data['rsrv_tm_ap'])) {
      //   $builder->where('b.rsrv_tm_ap', $data['rsrv_tm_ap']);
      // }

      // 예약일자
      if (!empty($data['rsrv_sdate'])) {
        $builder->where('b.rsrv_date >=', $data['rsrv_sdate'] . ' 00:00:00');
      }

      if (!empty($data['rsrv_edate'])) {
        $builder->where('b.rsrv_date <=', $data['rsrv_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 ($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');
      }

      // 상태
      if (!empty($data['stat'])) {
        $builder->whereIn('substring(a.rcpt_stat, 1, 2)', $data['stat']);
      }

      // 검색어
      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.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->orLike('a.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        }
      }

    }

    $builder->groupBy('b.dept_sq');
    $builder->orderBy('bonbu_nm ASC, team_nm ASC');


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

  // 지역별 통계
  public function getAreaStatistics($data)
  {
    $usr_sq = session('usr_sq');
    $usr_level = session('usr_level');
    $dept_sq = session('dept_sq');


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

    $builder->select("c.region_nm AS rcpt_dong, COUNT(a.rcpt_dong) AS cnt ");

    $builder->join('result b', 'a.rcpt_sq = b.rcpt_sq', 'left');
    $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');

    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('a.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);

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

      // $builder->where('a.isSiteVRVerification', 'N');

      // 접수일자
      /*
      if (!empty($data['sdate'])) {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('b.rsrv_date >=', $data['edate'] . ' 23:59:59');
      }
      */

      // if (!empty($data['rsrv_tm_ap'])) {
      //   $builder->where('b.rsrv_tm_ap', $data['rsrv_tm_ap']);
      // }

      // 예약일자
      if (!empty($data['rsrv_sdate'])) {
        $builder->where('b.rsrv_date >=', $data['rsrv_sdate'] . ' 00:00:00');
      }

      if (!empty($data['rsrv_edate'])) {
        $builder->where('b.rsrv_date <=', $data['rsrv_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 ($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');
      }

      // 상태
      if (!empty($data['stat'])) {
        $builder->whereIn('substring(a.rcpt_stat, 1, 2)', $data['stat']);
      }

      // 검색어
      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.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          $builder->groupStart()
            ->like('a.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        }
      }

    }

    $builder->groupBy('c.region_nm');
    $builder->orderBy('c.region_nm ASC');


    return $builder->get()->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");

    $builder->join('result b', 'a.rcpt_sq = b.rcpt_sq', 'left');
    $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->join('codes f', 'a.trade_type = f.cd AND f.category = \'TRADE_TYPE\'', 'left');

    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('a.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);

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

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

      // 접수일자
      /*
      if (!empty($data['sdate'])) {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('b.rsrv_date >=', $data['edate'] . ' 23:59:59');
      }
      */

      // if (!empty($data['rsrv_tm_ap'])) {
      //   $builder->where('b.rsrv_tm_ap', $data['rsrv_tm_ap']);
      // }

      // 예약일자
      if (!empty($data['rsrv_sdate'])) {
        $builder->where('b.rsrv_date >=', $data['rsrv_sdate'] . ' 00:00:00');
      }

      if (!empty($data['rsrv_edate'])) {
        $builder->where('b.rsrv_date <=', $data['rsrv_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 ($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');
      }

      // 검증방식
      if (!empty($data['isSiteVRVerification'])) {
        $builder->where('a.isSiteVRVerification', $data['isSiteVRVerification']);
      }

      // 홍보확인서 여부
      if (!empty($data['conf_img_yn'])) {
        if ($data['conf_img_yn'] == "Y") {
          $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I1\' and imgs.use_yn=\'Y\')', NULL, FALSE);
        } else if ($data['conf_img_yn'] == "N") {
          $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I1\' and imgs.use_yn=\'Y\')', NULL, FALSE);
        }
      }

      // 상태
      if (!empty($data['stat'])) {
        $builder->whereIn('substring(a.rcpt_stat, 1, 2)', $data['stat']);
      }

      // 검색어
      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.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->groupEnd();

          $builder->groupStart()
            ->like('a.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $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_ptp_nm
			         ,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
			         ,IFNULL(a.rcpt_hscp_nm, '') AS rcpt_hscp_nm
			   	  ,IFNULL(a.rcpt_ho, '') AS rcpt_ho
			   	  ,a.rcpt_dtl_addr
			   	  ,a.rcpt_li_addr
			   	  ,a.rcpt_jibun_addr
			   	  ,IFNULL(a.rcpt_etc_addr, '') AS rcpt_etc_addr
			   	  ,a.rcpt_floor
			         ,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
			         ,a.agent_id
			         ,a.agent_nm
			         ,a.agent_head
			         ,a.agent_head_tel
			         ,a.agent_contact
			         ,a.agent_contact_tel
			         ,IFNULL(a.agent_tel, '') AS agent_tel
			         ,a.sply_spc
			         ,a.excls_spc
			         ,a.room_cnt
			         ,a.exp_spc_yn
			         ,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
			         ,f.cd_nm as trade_type_nm
			         ,b.rsrv_sq
			   	  ,b.dept_sq
			         ,b.usr_sq
			         ,b.rsrv_tm_hour
			         ,b.result_cd1
			         ,b.result_cd2
			         ,b.result_msg
			   	  ,b.request_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
			   	  ,a.exp_photo_yn
			   	  ,a.ground_plan
			   	  ,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 conf_img_yn
			   	  ,CASE (SELECT COUNT(1) FROM result_imgs WHERE rsrv_sq=b.rsrv_sq AND img_type = 'I5' AND use_yn = 'Y') WHEN 0 THEN 'N' ELSE 'Y' END ground_plan_yn
			   	  ,a.exp_movie_yn
			   	  ,a.direct_trad_yn
			   	  ,a.sellr_nm
			   	  ,a.sellr_tel_no
			   	  ,a.isSiteVRVerification
			   	  ,a.isPromotionApply");

    $builder->join('result b', 'a.rcpt_sq = b.rcpt_sq', 'left');
    $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->join('codes f', 'a.trade_type = f.cd AND f.category = \'TRADE_TYPE\'', 'left');


    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('a.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);

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

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

      // 접수일자
      /*
      if (!empty($data['sdate'])) {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('b.rsrv_date >=', $data['edate'] . ' 23:59:59');
      }
      */

      // if (!empty($data['rsrv_tm_ap'])) {
      //   $builder->where('b.rsrv_tm_ap', $data['rsrv_tm_ap']);
      // }

      // 예약일자
      if (!empty($data['rsrv_sdate'])) {
        $builder->where('b.rsrv_date >=', $data['rsrv_sdate'] . ' 00:00:00');
      }

      if (!empty($data['rsrv_edate'])) {
        $builder->where('b.rsrv_date <=', $data['rsrv_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 ($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');
      }

      // 검증방식
      if (!empty($data['isSiteVRVerification'])) {
        $builder->where('a.isSiteVRVerification', $data['isSiteVRVerification']);
      }

      // 홍보확인서 여부
      if (!empty($data['conf_img_yn'])) {
        if ($data['conf_img_yn'] == "Y") {
          $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I1\' and imgs.use_yn=\'Y\')', NULL, FALSE);
        } else if ($data['conf_img_yn'] == "N") {
          $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I1\' and imgs.use_yn=\'Y\')', NULL, FALSE);
        }
      }

      // 상태
      if (!empty($data['stat'])) {
        $builder->whereIn('substring(a.rcpt_stat, 1, 2)', $data['stat']);
      }

      // 검색어
      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.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->orLike('a.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        }
      }

    }

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

    if (empty($data['type'])) {
      $builder->limit($end, $start);
    }

    // echo $builder->getCompiledSelect(false);
    $rows = $builder->get()->getResultArray();

    return $rows;
  }


  // 지도 정보 조회
  public function getDeptMapList($dept_sq)
  {


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

    $builder->select("b.dept_sq
				    ,b.usr_sq
				    ,b.rsrv_tm_ap
				    ,b.rsrv_tm_hour
				    ,a.rcpt_atclno
				    ,a.rcpt_x
				    ,a.rcpt_y
				    ,a.rcpt_product_nm
				    ,a.rcpt_key
				    ,a.rcpt_sq
				    ,c.dept_nm
				    ,d.usr_nm
				    ,(SELECT pdept_sq FROM departments WHERE dept_sq = b.dept_sq) bonbu
				    ,b.dept_sq
				    ,b.usr_sq
				    ,DATE_FORMAT(COALESCE(b.rsrv_date, a.rsrv_date), '%m월%d일') as rsrv_date
				    ,COALESCE(b.rsrv_tm_ap, a.rsrv_tm_ap) as rsrv_tm_ap
				    ,a.agent_nm
				    ,a.sellr_nm
				    ,a.direct_trad_yn
				    ,a.sellr_tel_no
				    ,a.isSiteVRVerification
			   	    ,a.isPromotionApply");

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

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

    $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("
                                CASE WHEN b.result_cd1 = '90' THEN get_code_name('RECEIPT_STATUS2', b.result_cd2) ELSE '' END AS '매물ID',
                                a.rcpt_atclno AS '예약일자',
                                b.rsrv_tm_hour AS '중개사명',
                                b.photo_save_dt AS '대표전화',
                                a.agent_contact_tel AS '담당자전화',
                                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 '주소',
                                a.rcpt_product_nm AS '매물종류',
                                a.rcpt_product_info1 AS '거래구분',
                                u.usr_nm AS '담당자',
                                b.request_msg AS '중개사 요청사항'");

    $builder->join('result b', 'a.rcpt_sq = b.rcpt_sq', 'left');
    $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->join('codes f', 'a.trade_type = f.cd AND f.category = \'TRADE_TYPE\'', 'left');


    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('a.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);

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

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

      // 접수일자
      /*
      if (!empty($data['sdate'])) {
        $builder->where('b.rsrv_date >=', $data['sdate'] . ' 00:00:00');
      }

      if (!empty($data['edate'])) {
        $builder->where('b.rsrv_date >=', $data['edate'] . ' 23:59:59');
      }
      */

      // if (!empty($data['rsrv_tm_ap'])) {
      //   $builder->where('b.rsrv_tm_ap', $data['rsrv_tm_ap']);
      // }

      // 예약일자
      if (!empty($data['rsrv_sdate'])) {
        $builder->where('b.rsrv_date >=', $data['rsrv_sdate'] . ' 00:00:00');
      }

      if (!empty($data['rsrv_edate'])) {
        $builder->where('b.rsrv_date <=', $data['rsrv_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 ($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');
      }

      // 검증방식
      if (!empty($data['isSiteVRVerification'])) {
        $builder->where('a.isSiteVRVerification', $data['isSiteVRVerification']);
      }

      // 홍보확인서 여부
      if (!empty($data['conf_img_yn'])) {
        if ($data['conf_img_yn'] == "Y") {
          $builder->where('exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I1\' and imgs.use_yn=\'Y\')', NULL, FALSE);
        } else if ($data['conf_img_yn'] == "N") {
          $builder->where('not exists (select \'x\' from result_imgs imgs where imgs.rsrv_sq = b.rsrv_sq and imgs.img_type = \'I1\' and imgs.use_yn=\'Y\')', NULL, FALSE);
        }
      }

      // 상태
      if (!empty($data['stat'])) {
        $builder->whereIn('substring(a.rcpt_stat, 1, 2)', $data['stat']);
      }

      // 검색어
      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.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        } else {
          $builder->groupStart()
            ->like('a.agent_nm', $data['srchTxt'])
            ->orLike('a.sellr_nm', $data['srchTxt'])
            ->orLike('a.agent_head_tel', $data['srchTxt'])
            ->orLike('a.sellr_tel_no', $data['srchTxt'])
            ->groupEnd();
        }
      }

    }

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

    // echo $builder->getCompiledSelect(false);
    $rows = $builder->get()->getResultArray();

    return $rows;
  }

  // 배정변경
  public function updateAssign($data)
  {
    $this->db->transStart();

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

    $sql = "UPDATE result SET 
            dept_sq = ?, usr_sq = ?, update_usr = ?
            WHERE rcpt_sq = ?
          ";

    $data = [
      $data['dept_sq'],
      $data['damdang'],
      $usr_sq,
      $data['rcpt_sq'],
    ];


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

    $memo = "배정변경";
    $this->saveChangedHistory($data['rcpt_sq'], '', 'C13', $usr_id, $memo);

    $this->db->transComplete();

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


  // 상세
  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.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', NULL, FALSE);
    $builder->where('a.rcpt_key', $id);


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

  // 시간대별통계
  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 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 saveChangedHistory($rcpt_sq, $rcpt_stat, $changed_type, $usr_id, $remark)
  {
    $sql = "INSERT INTO changed_history" .
      " (rcpt_sq, rcpt_stat, changed_type, changed_id, changed_tm, remark)" .
      " VALUES" .
      " (?, ?, ?, ?, now(), ?)";

    $data = [
      $rcpt_sq,
      $rcpt_stat,
      $changed_type,
      $usr_id,
      $remark
    ];

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