<?php

namespace App\Models\Entities;

use CodeIgniter\Model;

class ReceiptModel extends Model
{
    protected $table      = 'receipt';
    protected $primaryKey = 'rcpt_sq';

    // insert를 위해 이 줄을 추가해 주세요. (제공해주신 스키마 기반 주요 필드)
    protected $allowedFields = [
        'comp_sq', 'rcpt_rating', 'rcpt_key', 'rcpt_atclno', 'rcpt_type', 
        'rcpt_product', 'rcpt_product_nm', 'rcpt_product_info1', 'rcpt_product_info2',
        'rcpt_product_info3', 'rcpt_office', 'rcpt_agent', 'rcpt_sido', 'rcpt_hscp_nm', 
        'rcpt_dtl_addr', 'rcpt_etc_addr', 'rcpt_floor', 'rcpt_floor2', 'rcpt_tm', 
        'rcpt_stat', 'rcpt_x', 'rcpt_y', 'agent_nm', 'agent_head_tel', 'rsrv_date', 
        'insert_tm', 'rcpt_cpid', 'room_cnt', 'isSiteVRVerification'
    ];

    public function getReceiptList($params, $pageNum = 1, $pageSize = 20, $total = false)
    {
        $builder = $this->db->table('receipt a');

        // 1. SELECT 문 구성
        $builder->select("
            a.rcpt_sq, a.comp_sq, a.rcpt_rating, ... (중략) ...,
            DATE_FORMAT(COALESCE(b.rsrv_date, a.rsrv_date), '%Y-%m-%d') AS rsrv_date,
            get_code_name('RECEIPT_STATUS1', LEFT(a.rcpt_stat, 2)) AS rcpt_stat_nm,
            CASE WHEN imgs.has_I1 = 1 THEN 'Y' ELSE 'N' END AS conf_img_yn
        ", false);

        // 2. JOIN 설정
        $builder->join('result b', 'a.rcpt_sq = b.rcpt_sq', 'left outer');
        $builder->join('region_codes c', 'a.rcpt_dong = c.region_cd', 'inner');
        $builder->join('departments d', 'b.dept_sq = d.dept_sq', 'left outer');
        $builder->join('users u', 'b.usr_sq = u.usr_sq', 'left outer');
        
        // 서브쿼리 조인 (imgs)
        $subQuery = $this->db->table('result_imgs')
            ->select("rsrv_sq")
            ->selectMax("CASE WHEN img_type = 'I5' AND use_yn = 'Y' THEN 1 ELSE 0 END", "has_I5")
            ->selectMax("CASE WHEN img_type = 'I1' AND use_yn = 'Y' THEN 1 ELSE 0 END", "has_I1")
            ->groupBy("rsrv_sq")
            ->getCompiledSelect();

        $builder->join("($subQuery) imgs", "imgs.rsrv_sq = b.rsrv_sq", "left", false);

        // 3. WHERE 조건 (권한 및 기본 필터)
        if (in_array($params['usr_level'], ['4', '40'])) {
            if (!empty($params['child_dept'])) {
                $builder->whereIn('b.dept_sq', $params['child_dept']);
            } else {
                $builder->where('b.usr_sq', $params['usr_sq']);
            }
        }

        // 기본 3개월 데이터 제한
        $builder->where('a.insert_tm >= DATE_ADD(CURDATE(), INTERVAL -3 MONTH)', null, false);

        // 4. 검색 조건 동적 생성
        if (!empty($params['rcpt_atclno'])) {
            $builder->where('a.rcpt_atclno', $params['rcpt_atclno']);
        } else {
            if (!empty($params['sdate'])) {
                $builder->where('a.insert_tm >=', $params['sdate'] . ' 00:00:00');
                $builder->where('a.insert_tm <', date('Y-m-d', strtotime($params['edate'] . ' +1 day')));
            }
            
            // 중개사/매도자 통합 검색 (Group Start/End 사용)
            if (!empty($params['agent_nm'])) {
                $builder->groupStart()
                        ->like('a.agent_nm', $params['agent_nm'])
                        ->orLike('a.sellr_nm', $params['agent_nm'])
                        ->groupEnd();
            }
            
            // 상태(Status) 다중 체크
            if ($params['stat_all'] !== 'Y' && !empty($params['stat_arr'])) {
                $builder->groupStart();
                foreach ($params['stat_arr'] as $stat) {
                    $builder->orLike('a.rcpt_stat', $stat, 'after');
                }
                $builder->groupEnd();
            }
        }

        // 5. 정렬 및 페이징
        $builder->orderBy('a.rcpt_atclno', 'desc');
        
        // 데이터 수 조회를 위해 복제 또는 countAllResults 활용
        $totalCount = 0;
        if ($total) {
            $countBuilder = clone $builder;
            $totalCount = $countBuilder->countAllResults(false);
        }

        $offset = ($pageNum - 1) * $pageSize;
        $result = $builder->get($pageSize, $offset)->getResultArray();

        return [
            'data'  => $result,
            'total' => $totalCount
        ];
    }
}