<?php
namespace App\Controllers\V2;

use App\Controllers\BaseController;
use App\Libraries\Common;
use App\Models\common\CodeModel;
use App\Models\v2\M709Model;

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

    public function __construct()
    {
        $this->model = new M709Model();
        $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/m709/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']);
                    break;
                case "2": // 일반확인 매물
                    $article = $this->model->getArticleInfo2($data['atcl_no']);
                    break;
            }

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

        // dd($data);
        // exit;

        $history = $this->model->getHistory($id);

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

        return view("pages/v2/m709/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 saveAddress()
    {
        try {

            $vr_sq = $this->request->getPost('vr_sq');			// 확인요청순번
            $atcl_no = $this->request->getPost('atcl_no');		// 매물번호
            $fax_sq = $this->request->getPost('fax_sq');		    // fax 순번
            $address2 = $this->request->getPost('address2');	    // 상세주소1            
            $address3 = $this->request->getPost('address3');	    // 상세주소2
            $trade_type = $this->request->getPost('trade_type');	// 거래구분
            $floor = $this->request->getPost('floor');			// 층
            $floor2 = $this->request->getPost('floor2');			// 총층


            $data = [
                'vr_sq' => $vr_sq,
                'atcl_no' => $atcl_no,
                'fax_sq' => $fax_sq,
                'address2' => $address2,
                'address3' => $address3,
                'trade_type' => $trade_type,
                'floor' => $floor,
                'floor2' => $floor2,
            ];

            $this->model->saveAddress($data);

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

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


    // 확인결과저장
    public function saveImageArticle()
    {
        try {

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

            $data = [
                'fax_sq' => $fax_sq,
                'work_type' => $work_type,
                'atcl_no' => $atcl_no,
                'vr_sq' => $vr_sq,
                'file_type' => $file_type,
            ];

            $this->model->saveImageArticle($data);

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