<?php
namespace App\Controllers\V2;

use App\Controllers\BaseController;
use App\Libraries\NaverApiClient;
use App\Models\common\CodeModel;
use App\Models\results\M415Model;
use App\Models\v2\M703Model;
use App\Models\v2\M710Model;

class M703 extends BaseController
{

    private $model, $codeModel;

    public function __construct()
    {
        $this->model = new M703Model();
        $this->codeModel = new CodeModel();
    }

    public function lists()
    {
        $codes = $this->codeModel->getCodeLists(['CP_ID', 'STEP_VERIFICATION', 'RECEIPT_STATUS3', 'FAX_CORP']); // 코드조회
        $sido = $this->model->getAreaList(); // 지역조회
        $bonbu = $this->model->getBonbuList();
        $team = $this->model->getTeamList();
        $user = $this->model->getUserList();

        $this->data['sido'] = $sido;
        $this->data['bonbu'] = $bonbu;
        $this->data['team'] = $team;
        $this->data['user'] = $user;
        $this->data['codes'] = $codes;


        return view("pages/v2/m703/lists", $this->data);
    }

    public function getResultList()
    {
        $start = (int) $this->request->getGet('start') ?: 0;
        $end = (int) $this->request->getGet('length') ?: 10;

        $data = [
            'atcl_no' => $this->request->getGet('atcl_no'), // 매물번호
            'chk_atcl_no' => $this->request->getGet('chk_atcl_no'), // 매물번호입력
            'caller_no' => $this->request->getGet('caller_no'), // 발신팩스번호
            'stat_cd' => $this->request->getGet('stat_cd'), // 현재상태
            'realtor_nm' => $this->request->getGet('realtor_nm'), // 중개소
            'charger_gbn' => $this->request->getGet('charger_gbn'), // 배정여부
            'assign_yn' => $this->request->getGet('assign_yn'), // 배정여부2
            'receipt_sdate' => $this->request->getGet('receipt_sdate'), // 접수기간1
            'receipt_edate' => $this->request->getGet('receipt_edate'), // 접수기간2
            'complete_sdate' => $this->request->getGet('complete_sdate'), // 완료기간1
            'complete_edate' => $this->request->getGet('complete_edate'), // 완료기간2
            'srcSido' => $this->request->getGet('srcSido'), // 시도
            'srcGugun' => $this->request->getGet('srcGugun'), // 시군구
            'srcDong' => $this->request->getGet('srcDong'), // 읍면동
            'bonbu' => $this->request->getGet('bonbu'), // 본부
            'team' => $this->request->getGet('team'), // 팀
            'damdang' => $this->request->getGet('damdang'), // 담당
            'vrfcreq_way' => $this->request->getGet('vrfcreq_way'), // 검증방식1
            'vrfc_type_sub' => $this->request->getGet('vrfc_type_sub'), // 검증방식2
            'target_yn' => $this->request->getGet('target_yn'), // 홍보확인서여부
            'rcpt_cpid' => $this->request->getGet('rcpt_cpid'), // 매체사
            'chk_rec' => $this->request->getGet('chk_rec'), // 동의서 유무
            'fax_corp' => $this->request->getGet('fax_corp'), // 팩스업체
        ];

        $totalCount = $this->model->getTotalCount($data);

        $datas = $this->model->getResultList($start, $end, $data);

        return $this->response->setJSON(body: [
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $datas,
        ]);
    }


    // 엑셀 다운로드
    public function excel()
    {
        try {

            $data = [
                'atcl_no' => $this->request->getGet('atcl_no'), // 매물번호
                'chk_atcl_no' => $this->request->getGet('chk_atcl_no'), // 매물번호입력
                'caller_no' => $this->request->getGet('caller_no'), // 발신팩스번호
                'stat_cd' => $this->request->getGet('stat_cd'), // 현재상태
                'realtor_nm' => $this->request->getGet('realtor_nm'), // 중개소
                'charger_gbn' => $this->request->getGet('charger_gbn'), // 배정여부
                'assign_yn' => $this->request->getGet('assign_yn'), // 배정여부2
                'receipt_sdate' => $this->request->getGet('receipt_sdate'), // 접수기간1
                'receipt_edate' => $this->request->getGet('receipt_edate'), // 접수기간2
                'complete_sdate' => $this->request->getGet('complete_sdate'), // 완료기간1
                'complete_edate' => $this->request->getGet('complete_edate'), // 완료기간2
                'srcSido' => $this->request->getGet('srcSido'), // 시도
                'srcGugun' => $this->request->getGet('srcGugun'), // 시군구
                'srcDong' => $this->request->getGet('srcDong'), // 읍면동
                'bonbu' => $this->request->getGet('bonbu'), // 본부
                'team' => $this->request->getGet('team'), // 팀
                'damdang' => $this->request->getGet('damdang'), // 담당
                'vrfcreq_way' => $this->request->getGet('vrfcreq_way'), // 검증방식1
                'vrfc_type_sub' => $this->request->getGet('vrfc_type_sub'), // 검증방식2
                'target_yn' => $this->request->getGet('target_yn'), // 홍보확인서여부
                'rcpt_cpid' => $this->request->getGet('rcpt_cpid'), // 매체사
                'chk_rec' => $this->request->getGet('chk_rec'), // 동의서 유무
                'fax_corp' => $this->request->getGet('fax_corp'), // 팩스업체
            ];

            $datas = $this->model->getExcelList($data);

            return $this->response->setJSON(body: [
                'data' => $datas,
            ]);

        } catch (\Exception $e) {
            $e->getPrevious()->getTraceAsString();
        }
    }


    // 상세화면
    public function detail($id)
    {
        $naver = new NaverApiClient();
        $id = (string) $id;

        if ($id === '') {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $codes = $this->codeModel->getCodeLists(['CONFIRM_RESULT_D11', 'CONSULTANT_COMMENT', 'TRADE_TYPE', 'VRFCREQ_WAY']); // 코드조회

        $data = $this->model->getDetail($id);


        $article = null;
        $confirm = null;
        if (!empty($data)) {
            switch ($data['work_type']) {
                case "1": // 현장확인 매물
                    $article = $this->model->getArticleInfo1($data['atcl_no']);
                    $article['stat_cd'] = $data['stat_cd'];
                    $confirm = $this->model->getV2Confirm($data['vr_sq'], $data['work_type']);
                    break;
                case "2": // 일반확인 매물
                    $article = $this->model->getArticleInfo2($data['atcl_no']);
                    $confirm = $this->model->getV2Confirm($data['vr_sq']);
                    break;
            }

            $this->data['article'] = $article;
            $this->data['confirm'] = $confirm;
        }

        // 단지번호
        $hscp_info = [];
        if (!empty($article['hscp_no'])) {
            $apt_rlet_type_cd = ['A01', 'A02', 'A03', 'A04', 'B01', 'B02', 'B03'];
            $villa_rlet_type_cd = ['A05', 'A06'];
            if (in_array($article['rlet_type_cd'], $apt_rlet_type_cd)) { // apt 단지
                $detail_hscp = $naver->aptDetail($article['hscp_no']);
            }

            if (in_array($article['rlet_type_cd'], $villa_rlet_type_cd)) { // villa 단지
                $detail_hscp = $naver->villaDetail($article['hscp_no']);
            }

            $this->data['hscp_info'] = $hscp_info;
        }


        $memo = $this->model->getMomo($data['vr_sq']);
        $history = $this->model->getHistory($data['vr_sq'], $data['work_type']);

        $this->data['codes'] = $codes;

        $this->data['data'] = $data;
        $this->data['memo'] = $memo;
        $this->data['history'] = $history;



        return view("pages/v2/m703/detail", $this->data);
    }

    // 현장확인 저장
    public function saveBunyang()
    {
        try {

            $fax_sq = $this->request->getPost('fax_sq');
            $vr_sq = $this->request->getPost('vr_sq');
            $atcl_no = $this->request->getPost('atcl_no');
            //$work_type			= $this->request->getPost('work_type');
            $work_type = '1';
            $result_d11 = $this->request->getPost('result_d11');
            $comment_d11 = $this->request->getPost('comment_d11');

            $fax_conf_yn_1 = $this->request->getPost('fax_conf_yn_1');
            $fax_conf_yn_2 = $this->request->getPost('fax_conf_yn_2');
            $fax_conf_yn_3 = $this->request->getPost('fax_conf_yn_3');

            $fax_conf_info_1 = $this->request->getPost('fax_conf_info_1');
            $fax_conf_info_2 = $this->request->getPost('fax_conf_info_2');
            $fax_conf_info_3 = $this->request->getPost('fax_conf_info_3');

            $resyn = $this->request->getPost('resYn');
            $dbusageagryn = $this->request->getPost('dbUsageAgrYn');
            $memo1 = $this->request->getPost('memo_vie');						//메모
            $memo2 = $this->request->getPost('memo_cal');						//메모

            if (empty($memo1)) {
                $memo = $memo2;
            } else {
                $memo = $memo1;
            }

            $this->model->saveReceiptFax($memo, $fax_sq, $vr_sq, $atcl_no, $work_type, $result_d11, $comment_d11, $fax_conf_yn_1, $fax_conf_yn_2, $fax_conf_yn_3, $fax_conf_info_1, $fax_conf_info_2, $fax_conf_info_3);


            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }

    // 홍보확인서 아님
    public function saveOthers()
    {
        try {

            $fax_sq = $this->request->getPost('fax_sq');

            $this->model->saveNotArticleFax($fax_sq);

            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }

    // 중복저장
    public function saveDuplicate()
    {
        try {

            $fax_sq = $this->request->getPost('fax_sq');
            $atcl_no = $this->request->getPost('atcl_no');
            $vr_sq = $this->request->getPost('vr_sq');

            $this->model->saveDuplicateFax($fax_sq, $atcl_no, $vr_sq);

            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }

    // 부분수신
    public function saveBubun()
    {
        try {

            $fax_sq = $this->request->getPost('fax_sq');


            $this->model->saveBubunFax($fax_sq);

            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }

    // 매물정보 변경
    public function saveFaxImgs()
    {
        try {

            $vr_sq = $this->request->getPost('vr_sq');			// 확인요청순번
            $atcl_no = $this->request->getPost('atcl_no');		// 매물번호
            $fax_sq = $this->request->getPost('fax_sq');		// fax 순번
            $trade_type = $this->request->getPost('trade_type'); // 거래구분
            $deal_amt = $this->request->getPost('deal_amt');	// 매매가
            $wrrnt_amt = $this->request->getPost('wrrnt_amt');	// 전세가
            $lease_amt = $this->request->getPost('lease_amt');	// 월세가
            $isale_amt = $this->request->getPost('isale_amt');	// 분양가
            $prem_amt = $this->request->getPost('prem_amt');	// 프리미엄


            $this->model->saveFaxImgInfo($fax_sq, $vr_sq, $atcl_no, $trade_type, $deal_amt, $wrrnt_amt, $lease_amt, $isale_amt, $prem_amt);


            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }


    // 중개사 요청사항(메모) 저장
    public function saveRequestMessage()
    {
        try {

            $rcpt_sq = $this->request->getPost('vr_sq');
            $atcl_no = $this->request->getPost('atcl_no');
            $fax_sq = $this->request->getPost('fax_sq');	// FAX 순번
            $msg = $this->request->getPost('msg');

            $rsrv_sq = $this->request->getPost('rsrv_sq');

            // UPDATE result
            $this->model->saveRequestMessage($rcpt_sq, $rsrv_sq, $msg);


            return $this->response->setJSON([
                'code' => '0',
                'msg' => 'success'
            ]);

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }

    // 다음 매물정보 조회
    public function getNextFaxImgs()
    {
        try {

            $curr_fax_sq = $this->request->getPost('curr_fax_sq');

            $data = $this->model->getNextFaxImgs($curr_fax_sq);

            if (empty($data)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => 'FAX 이미지가 존재하지 않습니다.'
                ]);
            } else {
                return $this->response->setJSON([
                    'code' => '0',
                    'msg' => 'success',
                    'data' => $data
                ]);
            }


        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }


    // 결과저장
    public function saveResult()
    {
        $naver = new NaverApiClient();

        try {

            $fax_sq = $this->request->getPost('fax_sq');
            $vr_sq = $this->request->getPost('vr_sq');
            $atcl_no = $this->request->getPost('atcl_no');
            $work_type = $this->request->getPost('work_type');
            $result_d11 = $this->request->getPost('result_d11');
            $comment_d11 = $this->request->getPost('comment_d11');

            $fax_conf_yn_1 = $this->request->getPost('fax_conf_yn_1');
            $fax_conf_yn_2 = $this->request->getPost('fax_conf_yn_2');
            $fax_conf_yn_3 = $this->request->getPost('fax_conf_yn_3');

            $fax_conf_info_1 = $this->request->getPost('fax_conf_info_1');
            $fax_conf_info_2 = $this->request->getPost('fax_conf_info_2');
            $fax_conf_info_3 = $this->request->getPost('fax_conf_info_3');

            $resyn = $this->request->getPost('resYn');
            $dbusageagryn = $this->request->getPost('dbUsageAgrYn');
            $memo = $this->request->getPost('memo_cal');						//메모

            $m415 = new M415Model();


            $article = $this->model->getArticleInfo2($atcl_no, $vr_sq);
            $v2_vrfc_req = $this->model->get_v2_vrfc_req($vr_sq);

            $stat = intval($article['stat_cd']);
            if ($stat > 40) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '이미 저장된 데이터입니다.',
                ]);
            } else if ($stat == 19) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '해당 매물은 등록 취소된 매물입니다.',
                ]);
            } else {

                //거주여부 & DB활용동의여부 수정 UPDATE
                if (!empty($resyn)) {
                    $this->model->updateResDB($resyn, $dbusageagryn, $vr_sq);
                }

                // DB에 결과를 저장한다.
                $return = $this->model->saveArticleFAX($memo, $fax_sq, $vr_sq, $atcl_no, $work_type, $result_d11, $comment_d11, $fax_conf_yn_1, $fax_conf_yn_2, $fax_conf_yn_3, $fax_conf_info_1, $fax_conf_info_2, $fax_conf_info_3);

                if (empty($return['code']) && $work_type == "2") {
                    // 검증센터에 데이터를 전송한다.
                    $m710Model = new M710Model();
                    $sendData = $this->model->getDataConfirmAPI($vr_sq);

                    $h_yn = $this->model->get_send_yn('H');
                    if ($h_yn['stop_yn'] == 'N') {	//전송금지 
                        //1.해당매물정보를v2_stop_api_save_info에다 넣음
                        $m710Model->insert_v2_stop_api_save_info($sendData['atclNo'], $vr_sq, 'H', $fax_sq);

                        //2.아무렇지않게 행동한다
                        $send_result['result'] = 'success';
                    } else {
                        $send_result = $naver->confirm($sendData['atclNo'], $sendData['success'], $sendData['checkList'], $sendData['charger'], $sendData['modifyInfo'], $sendData['date']);
                    }

                    if ($send_result['result'] == 'success') {
                        $this->model->InsCharger($vr_sq);

                        // DB에 상태값을 전송완료로 저장한다.
                        if (empty($sendData['success'])) {
                            $stat_cd = '39';	// 서류/전화 확인 실패
                            $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경

                            if ($fax_conf_info_3 != 'Y' || intval($sendData['try_cnt']) < 1) {
                                $stat_cd = '30';
                                $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);

                                return $this->response->setJSON([
                                    'code' => '9',
                                    'msg' => '의뢰인 정보 불일치로 저장되었습니다.',
                                ]);
                            }

                            if ($sendData['try_cnt'] >= '1') {
                                $stat_cd = '69';	// 검증실패
                                $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경

                                //★ 검증실패면 검증실패시간 업데이트하고 검증소요시간, 전체소요시간 산출
                                //1.서류전화 들어온시간
                                $insert_tm = $m415->getFaxSaveTime($vr_sq);
                                //2.서류/전화 불일치 시간
                                $tel_doc_conf_dt = $m415->getFaxFailTimeForHistory($vr_sq);
                                //3.검증실패시간
                                $finishTime = $m415->get_69_ForHistory($vr_sq);
                                //3.해당 정보를 테이블에 넣는다
                                $m415->insert_v2_time_required_Conf_Done($atcl_no, $article['cpid'], $article['vrfc_type'], $insert_tm['recv_time'], $tel_doc_conf_dt['insert_tm'], $finishTime['insert_tm']);

                                $this->model->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0302', '1', 'add');	// 최종실패로 저장

                            } else {
                                //★ 1차실패니까 검증실패시간 업데이트하고 검증소요시간 산출
                                //1.서류전화 들어온시간
                                $insert_tm = $m415->getFaxSaveTime($vr_sq);
                                //2.서류/전화 불일치 시간
                                $tel_doc_conf_dt = $m415->getFaxFailTimeForHistory($vr_sq);
                                //3.해당 정보를 테이블에 넣는다
                                $sf = 'F';
                                $m415->insert_v2_time_required_Conf($atcl_no, $article['cpid'], $article['vrfc_type'], $insert_tm['recv_time'], $tel_doc_conf_dt['insert_tm'], $sf);

                                $this->model->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0301', '1', 'add');	// 1차실패로 저장
                            }

                            $this->model->increseTryCnt($vr_sq);

                            if ($result_d11 == '20013') {
                                $this->model->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0203', '1', 'add');	// 기타로 저장
                            } else {
                                $this->model->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0202', '1', 'add');	// 불일치로 저장
                            }

                        } else {

                            log_message('debug', '703 save stat_cd = 35 start ::: ' . $vr_sq);
                            $stat_cd = '35';	// 서류/전화 확인 성공
                            $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경

                            if ($article['vrfc_type_sub'] == "D2") {
                                log_message('debug', '703 save stat_cd = 35 D2 ::: ' . $vr_sq);
                                $rgbk_confirm = $this->model->getRgbk_confirm($vr_sq);

                                if ($rgbk_confirm == '1') {
                                    log_message('debug', '703 save stat_cd = 35 rgbk_confirm ::: ' . $vr_sq);
                                    if ($this->model->check_chg_stat49($vr_sq)) {
                                        log_message('debug', '703 save stat_cd = 40 savechangeStep ::: ' . $vr_sq);
                                        $stat_cd = '40';
                                        $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 등기부등본 확인중 상태로 변경..
                                    }

                                    //★등기 로 넘어갈때
                                    //1.서류전화 들어온시간
                                    $insert_tm = $m415->getFaxSaveTime($vr_sq);
                                    log_message('debug', '703 save stat_cd = 35 insert_tm ::: ' . $insert_tm['recv_time']);
                                    //2.서류/전화 확인일자
                                    $tel_doc_conf_dt = $m415->get_cert_ing_TimeForHistory($vr_sq);
                                    log_message('debug', '703 save stat_cd = 35 tel_doc_conf_dt ::: ' . $tel_doc_conf_dt['insert_tm']);

                                    //3.해당 정보를 테이블에 넣는다
                                    if (empty($tel_doc_conf_dt)) {
                                        $tel_doc_conf_dt['insert_tm'] = date("Y-m-d H:i:s");
                                        log_message('debug', '703 save stat_cd = 35 tel_doc_conf_dt null ::: ' . $tel_doc_conf_dt['insert_tm']);
                                    }

                                    $sf = 'T';
                                    $m415->insert_v2_time_required_Conf($atcl_no, $article['cpid'], $article['vrfc_type'], $insert_tm['recv_time'], $tel_doc_conf_dt['insert_tm'], $sf);
                                    log_message('debug', '703 save stat_cd = 35 insert_v2_time_required_Conf ::: ' . json_encode(array($atcl_no, $article['cpid'], $article['vrfc_type'], $insert_tm['recv_time'], $tel_doc_conf_dt['insert_tm'], $sf)));

                                    $this->model->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0201', '1', 'add');	// 일치로 저장

                                } else {
                                    $stat_cd = '60';
                                    $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 검증완료 상태로 변경

                                    //★검증완료일때
                                    //0.불일치 이력이 있는지 확인
                                    $cnt = $m415->getFaxFailTimeForHistory($vr_sq);
                                    if (empty($cnt)) {	//검증완료일땐 불일치가없어야 통계포함된다
                                        //1.서류전화 들어온시간
                                        $insert_tm = $m415->getFaxSaveTime($vr_sq);
                                        //2.서류/전화 확인일자
                                        $tel_doc_conf_dt = $m415->getConfTimeForHistory($vr_sq);
                                        //3.검증시간
                                        $finishTime = $m415->get_60_ForHistory($vr_sq);
                                        //3.해당 정보를 테이블에 넣는다
                                        $m415->insert_v2_time_required_Conf_Done($atcl_no, $article['cpid'], $article['vrfc_type'], $insert_tm['recv_time'], $tel_doc_conf_dt['insert_tm'], $finishTime['insert_tm']);
                                    }
                                    $this->model->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0205', '1', 'add');	// 홍보확인서완료 등기부등본확인 안함 저장
                                }

                            }

                        }

                    } else {
                        $return = $send_result['error'];
                        $err_time = date("Y-m-d H:i:s");
                        $this->model->saveApiErr($fax_sq, $send_result['error']['code'], $send_result['error']['message'], $err_time, $v2_vrfc_req['atcl_no']);
                    }

                }

                return $this->response->setJSON([
                    'code' => '0',
                    'msg' => 'success',
                ]);
            }

        } catch (\Exception $e) {
            return $this->response->setJSON([
                'code' => '9',
                'msg' => $e->getMessage(),
            ]);
        }
    }


    // 홍보확인서 확인
    public function find()
    {
        $fax = $this->model->getOneFax();

        if (empty($fax)) {
            return redirect()->back()
                ->with('alert', '새로운 FAX가 존재하지 않습니다.');
        }


        return redirect()->to('/m703/m703a/detail/' . $fax['fax_sq']);
    }
}