<?php
namespace App\Controllers\V2;

use App\Controllers\BaseController;
use App\Libraries\MyUpload;
use App\Models\common\CodeModel;
use App\Models\v2\M713Model;

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

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


    public function lists(): string
    {
        $codes = $this->codeModel->getCodeLists(['STEP_VERIFICATION', 'VRFCREQ_WAY', 'CP_ID', '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/m713/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'), // 매물번호
            '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
            'rcpt_cpid' => $this->request->getGet('rcpt_cpid'), // 매체사
            'rlet_type_cd' => $this->request->getGet('rlet_type_cd'), // 매물종류
            'chk_spc_yn' => $this->request->getGet('chk_spc_yn'), // 면적확인
            'reference_file_url_yn' => $this->request->getGet('reference_file_url_yn'), // 참고용
            'corp_own' => $this->request->getGet('corp_own'), // 법인소유
        ];

        $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'), // 매물번호
                '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
                'rcpt_cpid' => $this->request->getGet('rcpt_cpid'), // 매체사
                'rlet_type_cd' => $this->request->getGet('rlet_type_cd'), // 매물종류
                'chk_spc_yn' => $this->request->getGet('chk_spc_yn'), // 면적확인
                'reference_file_url_yn' => $this->request->getGet('reference_file_url_yn'), // 참고용
                'corp_own' => $this->request->getGet('corp_own'), // 법인소유
            ];

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

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

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


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

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

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

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

        $record = $this->model->getRecordInfo($id, '1');	//홍보확인서
        $regist = $this->model->getRecordInfo($id, '2');	//등기부등본
        $display = $this->model->getDisplay('M713_detail');

        $sido = $this->model->getAreaList(); // 지역조회

        $this->data['codes'] = $codes;
        $this->data['data'] = $data;
        $this->data['memo'] = $memo;
        $this->data['record'] = $record;
        $this->data['regist'] = $regist;
        $this->data['display'] = $display;
        $this->data['sido'] = $sido;

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

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

            // UPDATE v2_article_info_etc
            $this->model->saveCorpOwn($vr_sq, $atcl_no);


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

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


    // 파일업로드
    public function uploadFile()
    {
        $lib = new MyUpload();

        try {
            $usr_id = session('usr_id');
            $vr_sq = $this->request->getPost('vr_sq');

            $file = $this->request->getFile('file');

            if ($file && $file->isValid() && !$file->hasMoved()) {

                $uploadPath = "/upload/v2_file/" . $vr_sq . "/";

                $arrUploadfile = [];
                if ($file->isValid() && !$file->hasMoved()) {
                    $uploadData = $lib->do_upload2($file, $uploadPath);

                    if ($uploadData !== false) {
                        $arrUploadfile[] = $uploadData;
                    }
                }

                if (!empty($arrUploadfile)) {
                    foreach ($arrUploadfile as $key => $uploadFile) {
                        $data = [
                            'vr_sq' => $vr_sq,
                            // 'file_sq' => $this->request->getPost('file_sq'),
                            'orig_name' => $uploadFile['origin_name'],
                            'new_name' => $uploadFile['file_name'],
                            'file_path' => $uploadPath, // 필요에 따라 상대경로로만 저장
                            'ext' => '.' . $uploadFile['ext'],
                            'size' => $file->getSize(),
                            'img_yn' => null,
                            'img_height' => null,
                            'img_width' => null,
                            'usr_id' => $usr_id,
                        ];
                    }

                    if (!empty($data)) {

                        // 파일업로드 정보 저장
                        $this->model->saveFileInfo($data);

                    }

                }

            }


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


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

    }

    // 다음매물확인
    public function nextRegi()
    {
        try {

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

            $data = $this->model->getNextInfo($vr_sq);

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


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