<?php
namespace App\Controllers\V2;

use App\Controllers\BaseController;
use App\Libraries\Common;
use App\Libraries\NaverApiClient;
use App\Models\common\CodeModel;
use App\Models\results\M415Model;
use App\Models\v2\M708Model;
use App\Models\v2\M710Model;
use Exception;

class M708 extends BaseController
{
    private $model, $codeModel;

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

    public function lists(): string
    {
        $codes = $this->codeModel->getCodeLists(['CP_ID', 'STEP_VERIFICATION', 'RECEIPT_STATUS3', 'ARTICLE_TYPE']); // 코드조회
        $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/m708/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'), // 담당
            'target_yn' => $this->request->getGet('target_yn'), // 홍보확인서여부
            'rcpt_cpid' => $this->request->getGet('rcpt_cpid'), // 매체사
            'rlet_type_cd' => $this->request->getGet('rlet_type_cd'), // 매물종류            
            'rcpt_v2' => $this->request->getGet('rcpt_v2'), // 검증방식          
        ];

        $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'), // 담당
                'target_yn' => $this->request->getGet('target_yn'), // 홍보확인서여부
                'rcpt_cpid' => $this->request->getGet('rcpt_cpid'), // 매체사
                'rlet_type_cd' => $this->request->getGet('rlet_type_cd'), // 매물종류            
                'rcpt_v2' => $this->request->getGet('rcpt_v2'), // 검증방식          
            ];

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

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

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


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

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

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

        $data = $this->model->getDetail($id);
        $memo = $this->model->getMemo($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;
        }

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

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


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


    // 이미지회전
    public function rotateImage()
    {
        $common = new Common();

        try {

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

            if (empty($degrees) || !is_numeric($degrees)) {
                $degrees = 90;
            }

            $regist = $this->model->getRecordInfo($vr_sq, '2');
            $fullPath = $regist['file_path'] . $regist['file_name'];
            $fullPath = $_SERVER['DOCUMENT_ROOT'] . $common->realpath_to_webpath($fullPath);

            $degrees = (float) $degrees;

            $im = new \Imagick($fullPath);

            // 배경색(회전 시 빈 공간 채우는 색). 투명 원하면 'transparent'
            $im->setImageBackgroundColor(new \ImagickPixel('white'));

            // 회전
            $im->rotateImage($im->getImageBackgroundColor(), $degrees);

            // 포맷/압축 유지(옵션)
            $im->setImageCompressionQuality(90);

            // 덮어쓰기
            $im->writeImage($fullPath);

            $im->clear();
            $im->destroy();

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

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

    // 매물검색
    public function getArticleInfo()
    {
        try {

            $atcl_no = $this->request->getGet('atcl_no');

            $row = $this->model->getArticleInfo($atcl_no);


            if (empty($row)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '매물이 존재하지 않습니다.',
                ]);
            }

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

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

    // 홍보확인서 아님 저장
    public function saveNotArticle()
    {
        try {

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

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


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

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

    // 중복으로 저장
    public function saveDuplImgs()
    {
        try {

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

            $this->model->saveDuplImgs($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 saveMobileBunyang()
    {
        try {

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

            $this->model->saveMobileBunyang($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 saveBunyang()
    {
        try {

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

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

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

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


    // 중개인 요청사항 저장
    public function saveRequestMessage()
    {
        $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'
        ]);
    }

    // 확인결과 저장
    public function saveResult()
    {
        $naver = new NaverApiClient();
        $model710 = new M710Model();
        $model415 = new M415Model();
        $v2DailyModel = new V2StDailyModel();

        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');
            $file_type = $this->request->getPost('file_type');

            $resyn = $this->request->getPost('resYn');
            $dbusageagryn = $this->request->getPost('dbUsageAgrYn');
            $send_yn = 'Y';

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

            if (intval($article['stat_cd']) >= 40) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '이미 저장된 데이터입니다.',
                ]);
            } else {

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

                // DB에 결과 저장
                $return = $this->model->saveHongBoFAX($fax_sq, $vr_sq, $atcl_no, $work_type, $send_yn, $result_d11 ?? null, $comment_d11 ?? null, $fax_conf_yn_1 ?? null, $fax_conf_yn_2 ?? null, $fax_conf_yn_3 ?? null, $fax_conf_info_1 ?? null, $fax_conf_info_2 ?? null, $fax_conf_info_3 ?? null, $file_type);

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

                    if (($fax_conf_yn_3 ?? 'N') == 'Y' || (int) $article['try_cnt'] < 1) {
                        $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 ($sendData['try_cnt'] >= '1') {
                                    $stat_cd = '69';	// 검증실패
                                    $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경..
                                    $v2DailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0302', '1', 'add');	// 최종실패로 저장
                                } else {
                                    $v2DailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0301', '1', 'add');	// 1차실패로 저장
                                }
                                //							$res_try = $this->m708_model->chgTryCnt($vr_sq, intval($sendData['try_cnt']) +1);

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

                                if (($result_d11 ?? '') == '20013') {
                                    $v2DailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0203', '1', 'add');	// 기타로 저장
                                } else {
                                    $v2DailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0202', '1', 'add');	// 불일치로 저장
                                }
                            } else {
                                $stat_cd = '35';	// 서류/전화 확인 성공
                                $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경..

                                $rgbk_cofirm = $this->model->getRgbk_confirm($vr_sq);
                                if ($rgbk_cofirm == '1') {
                                    $stat_cd = '40';
                                    $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 등기부등본 확인중 상태로 변경..	

                                    $v2DailyModel->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);	// 검증완료 상태로 변경..	

                                    $v2DailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0205', '1', 'add');	// 홍보확인서완료 등기부등본확인 안함 저장
                                }
                            }
                        } else {
                            throw new \Exception($send_result['error']);
                        }
                    } else {
                        $stat_cd = '39';	// 서류/전화 확인 실패
                        $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);

                        $stat_cd = '30';	// 서류/전화 확인 중
                        $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);

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

                        throw new \Exception('의뢰인 정보 불일치로 저장되었습니다.');
                    }

                }


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

            }


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

    // 분양계약서 조회
    public function saveBunyangCnt()
    {
        try {

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

            $rsrv_sq = $this->model->get_rsrv_sq($vr_sq);
            $cnt = $this->model->getI8Cnt($rsrv_sq['rsrv_sq']);

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

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

    // 분양계약서 저장
    public function saveResult3()
    {
        $naver = new NaverApiClient();
        $v2StDailyModel = new V2StDailyModel();

        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');

            $resyn = $this->request->getPost('resYn');
            $dbusageagryn = $this->request->getPost('dbUsageAgrYn');
            $send_yn = 'Y';					// 업데이트 된다면 미처리->처리상태로 변경

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

            if ((int) $article['stat_cd'] >= 40) {
                throw new \Exception('이미 저장된 데이터입니다.');
            } else {
                if (!empty($resyn)) {
                    $this->model->updateResDB($resyn, $dbusageagryn, $vr_sq);
                }

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

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

                    if (($fax_conf_yn_3 ?? 'N') == 'Y' || $article['try_cnt'] < '1') {
                        $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 ($sendData['try_cnt'] >= '1') {
                                    $stat_cd = '69';	// 검증실패
                                    $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경..
                                    $v2StDailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0302', '1', 'add');	// 최종실패로 저장
                                } else {
                                    $v2StDailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0301', '1', 'add');	// 1차실패로 저장
                                }
                                //							$res_try = $this->m708_model->chgTryCnt($vr_sq, intval($sendData['try_cnt']) +1);

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

                                if (($result_d11 ?? '') == '20013') {
                                    $v2StDailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0203', '1', 'add');	// 기타로 저장
                                } else {
                                    $v2StDailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0202', '1', 'add');	// 불일치로 저장
                                }
                            } else {
                                $stat_cd = '35';	// 서류/전화 확인 성공
                                $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 전송완료 상태로 변경..

                                $rgbk_cofirm = $this->model->getRgbk_confirm($vr_sq);
                                if ($rgbk_cofirm == '1') {
                                    $stat_cd = '40';
                                    $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);	// 등기부등본 확인중 상태로 변경..	

                                    $v2StDailyModel->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);	// 검증완료 상태로 변경..	

                                    $v2StDailyModel->set_v2_st_daily(NULL, $v2_vrfc_req['cpid'], 'D0205', '1', 'add');	// 홍보확인서완료 등기부등본확인 안함 저장
                                }
                            }
                        } else {
                            throw new \Exception($send_result['error']);
                        }
                    } else {
                        $stat_cd = '39';	// 서류/전화 확인 실패
                        $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);

                        $stat_cd = '30';	// 서류/전화 확인 중
                        $this->model->saveChangeStep($fax_sq, $vr_sq, $stat_cd);

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


                        throw new \Exception('의뢰인 정보 불일치로 저장되었습니다.');
                    }
                }

                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(),
            ]);
        }
    }

}