<?php
namespace App\Controllers\article;

use App\Controllers\article\Exception;
use App\Controllers\BaseController;
use App\Libraries\MyUpload;
use App\Models\article\AptModel;
use App\Models\common\CodeModel;

class Apt extends BaseController
{
    private $aptModel, $codeModel;
    public function __construct()
    {
        $this->aptModel = new AptModel();
        $this->codeModel = new CodeModel();
    }

    // 아파트단지
    public function lists(): string
    {
        $codes = $this->codeModel->getCodeLists(['VIDEO_TARGET', 'APT_STEP', 'PHO_YN', 'VDO_YN']); // 코드조회
        $sido = $this->aptModel->getAreaList(); // 지역조회
        $bonbu = $this->aptModel->getBonbuList(); // 본부
        $team = $this->aptModel->getTeamList(); // 팀
        $user = $this->aptModel->getUserList(); // 유저

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

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

    // 아파트단지목록 조회
    public function getAptLists()
    {

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

        $data = [
            'hscp_no' => $this->request->getGet('hscp_no'), // 단지코드
            'pho_no' => $this->request->getGet('pho_no'), // 사진코드
            'srcSido' => $this->request->getGet('srcSido'), // 시|도
            'srcGugun' => $this->request->getGet('srcGugun'), // 시|군|구
            'srcDong' => $this->request->getGet('srcDong'), // 읍|면|동

            'rcpt_hscp_nm' => $this->request->getGet('rcpt_hscp_nm'), // 단지명
            'sdate' => $this->request->getGet('sdate'), // 시작일
            'edate' => $this->request->getGet('edate'), // 종료일
            'households_cnt1' => $this->request->getGet('households_cnt1'), // 총세대수1
            'households_cnt2' => $this->request->getGet('households_cnt2'), // 총세대수2
            'dong_cnt1' => $this->request->getGet('dong_cnt1'), // 총동수1
            'dong_cnt2' => $this->request->getGet('dong_cnt2'), // 총동수2

            'bonbu' => $this->request->getGet('bonbu'), // 본부
            'team' => $this->request->getGet('team'), // 팀
            'damdang' => $this->request->getGet('damdang'), // 담당

            'stat' => $this->request->getGet('stat'), // 진행상태
        ];

        $totalCount = $this->aptModel->getTotalCount($data);
        $datas = $this->aptModel->getAptLists($start, $end, $data);

        $deptStatistics = $this->aptModel->getDeptStatistics($data); // 조직별통계
        $areaStatistics = $this->aptModel->getStatistics($data); // 지역별통계

        return $this->response->setJSON(body: [
            'draw' => (int) ($this->request->getGetPost('draw') ?? 0), // 서버사이드면 권장
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $datas,
            'widgets' => [
                'deptList' => $deptStatistics,
                'areaStats' => $areaStatistics,
            ],
        ]);

    }

    // 전체촬영불가 단지 확인
    public function chkTakeAptPhotoCnt()
    {
        $data = $this->aptModel->chkTakeAptPhotoCnt();

        return $this->response->setJSON(
            body:
            $data
        );
    }

    // 관할포인트 인쇄 - 화면
    public function print(): string
    {
        $deptSq = $this->request->getGet('depChk');
        $dept_cnt = count($deptSq);


        $listDept = $this->aptModel->getDeptMapList($deptSq);

        if (!empty($listDept)) {
            $lati = 0;
            $long = 0;
            foreach ($listDept as $dept) {
                $lati += $dept['rcpt_y'];
                $long += $dept['rcpt_x'];
            }

            $lati = $lati / $dept_cnt;
            $long = $long / $dept_cnt;
        }

        return view("pages/article/printMap", [
            // 'lati' => $lati,
            // 'long' => $long,
            'listDept' => $listDept,
        ]);
    }

    // 아파트단지 정보저장
    public function saveAptMemo()
    {
        try {

            $rcpt_no = $this->request->getPost('rcpt_no');
            $video_target = $this->request->getPost('video_target');

            if (empty($rcpt_no)) {
                throw new Exception("단지정보 누락");
            }

            $params = [
                'target' => $video_target,
                'memo' => $this->request->getPost('memo') ?: '',
                'rcpt_no' => $rcpt_no,
            ];

            // UPDATE apt_result
            $this->aptModel->saveAptMemo($params);


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


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

    // 담당자정보변경
    public function chgAptDamdang()
    {
        try {

            $team = $this->request->getPost('team');
            $damdang = $this->request->getPost(index: 'usr_id');

            if (empty($team)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '팀정보 누락',
                ]);
            }

            if (empty($damdang)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '담당자정보 누락',
                ]);
            }


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

            $rows = json_decode($rows, true);

            if (count($rows) > 0) {
                foreach ($rows as $row) {
                    $params = [
                        $team,
                        $damdang,
                        $row['rcpt_no'],
                    ];


                    // UPDATE apt_result
                    $this->aptModel->updateAptDamdang($params);

                }
            } else {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '저장데이터 누락',
                ]);
            }

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


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


    // 영상담당 정보 저장
    public function chgAptVideoTarget()
    {
        try {

            $target = $this->request->getPost('video');

            if (empty($target)) {
                throw new Exception("영상대상 정보 누락");
            }


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

            $rows = json_decode($rows, true);

            if (count($rows) > 0) {
                foreach ($rows as $row) {
                    $params = [
                        'target' => $target,
                        'apt_step' => $row['apt_step'],
                        'rcpt_no' => $row['rcpt_no'],
                        'usr_id' => session('usr_id'),
                    ];


                    // UPDATE apt_result
                    $this->aptModel->updateAptVideoTarget($params);

                }
            } else {
                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 uploadExcel()
    {
        try {

            $payload = $this->request->getJSON(true);
            $datas = $payload['datas'] ?? null;

            if (count($datas) === 0) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => "데이터 없음",
                ]);
            }


            foreach ($datas as $data) {
                $rdate = date("Y-m-d H:i:s");

                $params = [
                    'row_no' => $data[0],
                    'hscp_no' => $data[1],
                    'uni_hscp_no' => $data[2],
                    'region_cd' => $data[3],
                    'addr' => $data[4],
                    'addr2' => $data[5],
                    'apt_cate_nm' => $data[6],
                    'rcpt_hscp_nm' => $data[7],
                    'move_ym' => $data[8],
                    'households_cnt' => $data[9],
                    'dong_cnt' => $data[10],
                    'pyeong_cnt' => $data[11],
                    'dongho' => $data[12],
                    'use_yn' => $data[13],
                    'rcpt_x' => $data[14],
                    'rcpt_y' => $data[15],
                    'pho_exept_yn' => $data[16],
                    'rdate' => $rdate,
                ];

                // INSERT apt_receipt, apt_result
                $this->aptModel->saveExcelUploadData($params);

            }

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

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

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

            $data = [
                'hscp_no' => $this->request->getGet('hscp_no'), // 단지코드
                'pho_no' => $this->request->getGet('pho_no'), // 사진코드
                'srcSido' => $this->request->getGet('srcSido'), // 시|도
                'srcGugun' => $this->request->getGet('srcGugun'), // 시|군|구
                'srcDong' => $this->request->getGet('srcDong'), // 읍|면|동

                'rcpt_hscp_nm' => $this->request->getGet('rcpt_hscp_nm'), // 단지명
                'sdate' => $this->request->getGet('sdate'), // 시작일
                'edate' => $this->request->getGet('edate'), // 종료일
                'households_cnt1' => $this->request->getGet('households_cnt1'), // 총세대수1
                'households_cnt2' => $this->request->getGet('households_cnt2'), // 총세대수2
                'dong_cnt1' => $this->request->getGet('dong_cnt1'), // 총동수1
                'dong_cnt2' => $this->request->getGet('dong_cnt2'), // 총동수2

                'bonbu' => $this->request->getGet('bonbu'), // 본부
                'team' => $this->request->getGet('team'), // 팀
                'damdang' => $this->request->getGet('damdang'), // 담당

                'stat' => $this->request->getGet('stat'), // 진행상태
            ];

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

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

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


    // 아파트단지 상세화면
    public function detail($id = null): string
    {
        $rcpt_no = (int) $id;

        if ($rcpt_no == null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $bonbu = $this->aptModel->getBonbuList();
        $team = $this->aptModel->getTeamList();
        $user = $this->aptModel->getUserList();
        $codes = $this->codeModel->getCodeLists(['VIDEO_TARGET', 'PHO_CATE1', 'PHO_CATE2']); // 코드조회

        $apt = $this->aptModel->getDetail($rcpt_no);

        //이미지 리스트
        $image = $this->aptModel->getImgList($rcpt_no);

        //이미지 총 개수
        $cntAllPho = $this->aptModel->cntAllPho($rcpt_no);
        if (empty($cntAllPho)) {
            $cntAllPho = 0;
        }
        //동영상 리스트
        $vdo = $this->aptModel->getVideoList($rcpt_no);
        //사진및 설명정보의 카테고리 리스트
        $cateInfo = $this->aptModel->getCateInfoList($rcpt_no);

        //정보변경이력
        $history = $this->aptModel->getHistory($rcpt_no);

        $code1 = [];
        $code2 = [];
        $video = [];
        if (!empty($codes)) {
            foreach ($codes as $code) {
                if ($code['category'] === "PHO_CATE1") {
                    array_push($code1, $code);
                } else if ($code['category'] === "PHO_CATE2") {
                    array_push($code2, $code);
                } else if ($code['category'] === "VIDEO_TARGET") {
                    array_push($video, $code);
                }
            }
        }

        $this->data['apt'] = $apt;
        $this->data['bonbu'] = $bonbu;
        $this->data['team'] = $team;
        $this->data['user'] = $user;
        $this->data['code1'] = $code1;
        $this->data['code2'] = $code2;
        $this->data['video'] = $video;
        $this->data['image'] = $image;
        $this->data['vdo'] = $vdo;
        $this->data['history'] = $history;
        $this->data['cateInfo'] = $cateInfo;
        $this->data['cntAllPho'] = $cntAllPho;

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

    public function cateJson()
    {
        $params = [
            $this->request->getGet('pho_cate1'),
        ];

        $datas = $this->aptModel->getCateJson($params);


        return $this->response->setJSON($datas);
    }


    // 담당자 정보 저장
    public function saveKeeper()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'bonbu' => $this->request->getPost('bonbu'),
                'team' => $this->request->getPost('team'),
                'user' => $this->request->getPost('user'),
            ];

            // UPDATE apt_result
            $this->aptModel->saveKeeper($params);


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

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

    // 지도좌표 수정
    public function saveCoordinate()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'rcpt_x' => $this->request->getPost('rcpt_x'),
                'rcpt_y' => $this->request->getPost('rcpt_y'),
            ];

            // UPDATE apt_receipt, apt_result
            $this->aptModel->saveCoordinate($params);


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

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

    // 단지 특이사항 저장
    public function saveNote()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'note' => $this->request->getPost('note'),
            ];

            // UPDATE apt_result
            $this->aptModel->saveNote($params);


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

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


    // 동영상 촬영정보 저장
    public function saveVideoTarget()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'target' => $this->request->getPost('video_target'),
            ];

            // UPDATE apt_result
            $this->aptModel->saveVideoTarget($params);


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

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

    // 촬영불가사유 저장
    public function saveVideoReason()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'not_vdo_reson' => $this->request->getPost('not_vdo_reson'),
                'vdo_up_ynx' => $this->request->getPost('vdo_up_ynx'),
            ];

            // UPDATE apt_result
            $this->aptModel->saveVideoReason($params);


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

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

    // 사진업로드 불가사유 저장
    public function savePhoReason()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'pho_cate2' => $this->request->getPost('pho_cate2'),
                'pho_up_nu' => $this->request->getPost('pho_up_nu'),
                'usr_id' => session('usr_id'),
            ];

            // UPDATE apt_category
            $this->aptModel->savePhoReason($params);


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

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

    // 사진 카테고리 수정
    public function saveCate()
    {
        try {
            $phoNo = $this->request->getPost('pho_no');
            if (!is_array($phoNo)) {
                $phoNo = [$phoNo];
            }

            $params = [
                'pho_no' => $phoNo,
                'pho_cate1' => $this->request->getPost('pho_cate1'),
                'pho_cate2' => $this->request->getPost('pho_cate2'),
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'now_cate' => $this->request->getPost('nowCate2'),
            ];

            $this->aptModel->saveCate($params);

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

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

    }

    // 사진 노출정보 저장
    public function savePhotoView()
    {
        try {
            $phoNo = $this->request->getPost('pho_no');
            if (!is_array($phoNo)) {
                $phoNo = [$phoNo];
            }

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

            $params = [
                'pho_no' => $phoNo,
                'pho_view_yn' => $this->request->getPost('pho_view_yn_' . $pho_cate2),
                'rcpt_no' => $this->request->getPost('rcpt_no'),
            ];

            $this->aptModel->savePhotoView($params);

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

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

    // 사진정보삭제
    public function removePhoto()
    {
        try {
            $phoNo = $this->request->getPost('pho_no');
            if (!is_array($phoNo)) {
                $phoNo = [$phoNo];
            }

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

            $params = [
                'pho_no' => $phoNo,
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'cate2_cd' => $this->request->getPost('cate2_cd'),
            ];

            $this->aptModel->removePhoto($params);

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

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

    // 사진설명 저장
    public function savePhoExplain()
    {
        try {

            $params = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'pho_cate2' => $this->request->getPost('pho_cate2'),
                'pho_explain' => session('pho_explain'),
                'usr_id' => session('usr_id'),
            ];

            $this->aptModel->savePhoExplain($params);


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

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

    // 단지정보 작성완료
    public function saveWriteComplete()
    {
        try {

            $rcpt_no = $this->request->getPost('rcpt_no');
            if (empty($rcpt_no)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '정보누락'
                ]);
            }

            $this->aptModel->saveWriteComplete($rcpt_no);

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

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

    // 검수완료 저장
    public function confirmAptInfo()
    {
        try {

            $rcpt_no = $this->request->getPost('rcpt_no');
            $hscp_no = $this->request->getPost('hscp_no');

            $params = [
                'rcpt_no' => $rcpt_no,
                'hscp_no' => $hscp_no,
            ];

            $apiData = $this->aptModel->new_api_photo_send_data($rcpt_no);

            $ip_addr = array(
                '172.16.100.2',
                '172.16.100.3',
                '172.16.100.4',
                '172.16.100.5'
            );

            if (
                isset($_SERVER['HTTPS']) &&
                ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
                isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
                $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
            ) {
                $protocol = 'https://';
            } else {
                $protocol = 'http://';
            }

            if (in_array($_SERVER['SERVER_ADDR'], $ip_addr) == false) {
                $domain = $protocol . $_SERVER['HTTP_HOST'];
                // $domain = $protocol . 'test-admin.confirms.co.kr';
            } else {
                $domain = $protocol . 'admin.confirms.co.kr';
            }


            foreach ($apiData as $key => $d) {
                $isExposed = ($d['use_yn'] == 'Y' ? true : false);
                $array[] = array('mainCategory' => $d['cate1_cd'], 'subCategory' => $d['cate2_cd'], 'comment' => $d['pho_explain']);
                $array1[] = array(
                    'photoNumber' => $d['pho_no'],
                    'mainCategory' => $d['cate1_cd'],
                    'subCategory' => $d['cate2_cd'],
                    'lat' => $d['pho_lati'],
                    'lng' => $d['pho_long'],
                    'url' => $d['url'],
                    'isExposed' => $isExposed,
                    'order' => 1
                );
            }

            $serializedArray = array_map('serialize', $array);
            $uniqueArray = array_unique($serializedArray);
            $post_data_array['categories'] = array_map('unserialize', array_values($uniqueArray));

            $post_data_array['photos'] = $array1;

            $send_post_data = json_encode($post_data_array, JSON_UNESCAPED_UNICODE);


            /**API시작**/
            $result = $this->syncRequestListNew($hscp_no, $send_post_data);
            /**API끝**/


            if ($result['code'] == 'success') {
                $syncId = '';
                $this->aptModel->saveCheck($rcpt_no, $syncId);

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

            } else {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '저장실패'
                ]);
            }

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

    // 재전송
    public function resendAptInfo()
    {
        try {

            $rcpt_no = $this->request->getPost('rcpt_no');
            $hscp_no = $this->request->getPost('hscp_no');

            $params = [
                'rcpt_no' => $rcpt_no,
                'hscp_no' => $hscp_no,
            ];

            $apiData = $this->aptModel->new_api_photo_send_data($rcpt_no);

            $ip_addr = array(
                '172.16.100.2',
                '172.16.100.3',
                '172.16.100.4',
                '172.16.100.5'
            );

            if (
                isset($_SERVER['HTTPS']) &&
                ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
                isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
                $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
            ) {
                $protocol = 'https://';
            } else {
                $protocol = 'http://';
            }

            if (in_array($_SERVER['SERVER_ADDR'], $ip_addr) == false) {
                $domain = $protocol . $_SERVER['HTTP_HOST'];
                // $domain = $protocol . 'test-admin.confirms.co.kr';
            } else {
                $domain = $protocol . 'admin.confirms.co.kr';
            }

            foreach ($apiData as $key => $d) {
                $isExposed = ($d['use_yn'] == 'Y' ? true : false);
                $array[] = array('mainCategory' => $d['cate1_cd'], 'subCategory' => $d['cate2_cd'], 'comment' => $d['pho_explain']);
                $array1[] = array(
                    'photoNumber' => $d['pho_no'],
                    'mainCategory' => $d['cate1_cd'],
                    'subCategory' => $d['cate2_cd'],
                    'lat' => $d['pho_lati'],
                    'lng' => $d['pho_long'],
                    'url' => $d['url'],
                    'isExposed' => $isExposed,
                    'order' => 1
                );
            }
            $serializedArray = array_map('serialize', $array);
            $uniqueArray = array_unique($serializedArray);
            $post_data_array['categories'] = array_map('unserialize', array_values($uniqueArray));

            $post_data_array['photos'] = $array1;
            $send_post_data = json_encode($post_data_array, JSON_UNESCAPED_UNICODE);

            log_message('debug', 'APT_SEND rcpt_no:::::::' . $rcpt_no . ':::::::' . $send_post_data);
            // $send_post_data = to_han( json_encode( $post_data_array) );
            /**API시작**/
            $result = $this->syncRequestListNew($hscp_no, $send_post_data);
            /**API끝**/

            if ($result['code'] == 'success') {
                $syncId = '';
                $this->aptModel->saveResend($rcpt_no, $syncId);

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

            } else {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '저장실패'
                ]);
            }


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

    // 파일업로드 - 동영상, 사진
    public function uploadFile()
    {
        $lib = new MyUpload();

        try {
            $rcpt_no = $this->request->getPost('rcpt_no');
            $uploadType = $this->request->getPost('upload_type');
            $files = $this->request->getFiles();
            $uploadPath = "/upload/apt_file/" . $rcpt_no . "/";

            if (!isset($files['files'])) {
                return $this->response->setJSON([
                    'success' => false,
                    'msg' => '파일 없음'
                ]);
            }

            if ($uploadType === "photo") {

                $arrUploadfile = [];
                foreach ($files['files'] as $file) {

                    $uploadData = $lib->do_upload2($file, $uploadPath);

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

                }

                $gps_lat = null;
                $gps_lon = null;
                $camDate = null;
                if (!empty($arrUploadfile)) {
                    foreach ($arrUploadfile as $key => $uploadFile) {
                        $object_storage_url = $uploadFile['object_storage_url'];
                        $arrExifData = @exif_read_data($object_storage_url);
                        if (!empty($arrExifData)) {
                            $notFound = "Unavailable";
                            if (@array_key_exists('DateTime', $arrExifData)) {
                                $camDate = $arrExifData['DateTime'];
                            } else {
                                $camDate = $notFound;
                            }

                            $imageMetaData = $camDate;
                            $camDate = substr(str_replace(':', '-', $camDate), 0, 10);



                            $arrGPS = $arrExifData['GPS'] ?? null;

                            if (empty($arrGPS)) { // GPS 섹션이 없으면, 개별 키로도 체크
                                if (!empty($arrExifData['GPSLongitude']) && !empty($arrExifData['GPSLatitude'])) {
                                    $arrGPS = [
                                        'GPSLongitude' => $arrExifData['GPSLongitude'],
                                        'GPSLatitude' => $arrExifData['GPSLatitude'],
                                    ];
                                }
                            }

                            if (
                                !empty($arrGPS)
                                && !empty($arrGPS['GPSLongitude'])
                                && !empty($arrGPS['GPSLatitude'])
                                && is_array($arrGPS['GPSLongitude'])
                                && is_array($arrGPS['GPSLatitude'])
                            ) { //GPS 정보가 있다면
                                if (@array_key_exists('GPSLongitude', $arrGPS) && (@array_key_exists('GPSLatitude', $arrGPS))) {
                                    list($temp_d1, $temp_d2) = sscanf($arrGPS["GPSLatitude"][0], "%d/%d"); //문자->숫자로 계산
                                    $gps_lat_d = $temp_d1 / $temp_d2;
                                    list($temp_d1, $temp_d2) = sscanf($arrGPS["GPSLatitude"][1], "%d/%d");
                                    $gps_lat_m = $temp_d1 / $temp_d2;
                                    list($temp_d1, $temp_d2) = sscanf($arrGPS["GPSLatitude"][2], "%d/%d");
                                    $gps_lat_s = $temp_d1 / $temp_d2;

                                    list($temp_d1, $temp_d2) = sscanf($arrGPS["GPSLongitude"][0], "%d/%d"); //문자->숫자로 계산
                                    $gps_lon_d = $temp_d1 / $temp_d2;
                                    list($temp_d1, $temp_d2) = sscanf($arrGPS["GPSLongitude"][1], "%d/%d");
                                    $gps_lon_m = $temp_d1 / $temp_d2;
                                    list($temp_d1, $temp_d2) = sscanf($arrGPS["GPSLongitude"][2], "%d/%d");
                                    $gps_lon_s = $temp_d1 / $temp_d2;

                                    $gps_lat = $gps_lat_d + $gps_lat_m / 60 + $gps_lat_s / 3600; //도분초를 도로 변환
                                    $gps_lon = $gps_lon_d + $gps_lon_m / 60 + $gps_lon_s / 3600;
                                }
                            } else {
                                $xy = $this->aptModel->getDetail($rcpt_no);

                                $gps_lat = $xy['rcpt_y'];
                                $gps_lon = $xy['rcpt_x'];
                            }


                        }

                        $base = $uploadFile['base_name'];     // xxxx
                        $dir = rtrim(dirname($uploadFile['object_key']), '/'); // upload/apt_file/2
                        $thumbKey = $dir . '/' . $base . '_thumb.jpg';

                        $imageDataBlob = file_get_contents($object_storage_url);
                        $im = new \Imagick();
                        $im->readImageBlob($imageDataBlob);
                        $im->thumbnailImage(105, 80, false);
                        $thumb_im = $im->getImageBlob();
                        // 썸네일 s3 전송
                        $lib->upload_object_storage_imagick2($thumbKey, $thumb_im);


                        /** 
                         * 파일업로드 내용 저장
                         * rcpt_no, pho_lati, pho_long, filenm, filenm_up, file_path, thumb_path, thumb_nm, cloud_upload_yn
                         * 
                         */
                        $uploadParam = [
                            'rcpt_no' => $rcpt_no, // 접수번호
                            'gps_lat' => $gps_lat, // latitude
                            'gps_lon' => $gps_lon, // longitude
                            'origin_name' => $uploadFile['origin_name'], // 원본파일명
                            'file_name' => $uploadFile['file_name'], // 저장파일명
                            'upload_path' => $uploadPath, // 저장경로
                            'thumb_name' => $base . '_thumb.jpg',
                            'cam_date' => $camDate, // 촬영일
                        ];

                        $res = $this->aptModel->saveImg($uploadParam);
                        log_message('debug', 'apt_file :: rcpt_no : ' . $rcpt_no . ', fileName : ' . $uploadFile['file_name']);

                    }
                }

            } else if ($uploadType === "video") {


                $arrUploadfile = [];
                foreach ($files['files'] as $file) {

                    $uploadData = $lib->do_upload2($file, $uploadPath);

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

                }

                // print_r($arrUploadfile);
                // exit;

                if (!empty($arrUploadfile)) {
                    foreach ($arrUploadfile as $key => $uploadFile) {
                        $uploadParam = [
                            'rcpt_no' => $rcpt_no, // 접수번호
                            'origin_name' => $uploadFile['origin_name'], // 원본파일명
                            'file_name' => $uploadFile['file_name'], // 저장파일명
                            'upload_path' => $uploadPath, // 저장경로
                            // 'thumb_name' => $base . '_thumb.jpg',
                            // 'cam_date' => $camDate, // 촬영일
                        ];


                        // 동영상 정보 저장
                        $this->aptModel->saveVideo($uploadParam);

                    }
                }


            }


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


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

    // 업로드파일삭제
    public function reqRemovePho()
    {
        try {

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


            if ($type === "all") {
                $rcpt_no = $this->request->getPost('rcpt_no');

                // 사진 일괄 삭제
                $this->aptModel->removeAllPho($rcpt_no);


            } else if ($type === "select") {
                $phoNo = $this->request->getPost('phoNo'); // ✅ 배열로 들어옴

                if (!is_array($phoNo))
                    $phoNo = [$phoNo];

                if (empty($phoNo)) {
                    return $this->response->setJSON([
                        'code' => '9',
                        'msg' => '데이터 누락'
                    ]);
                }

                // 선택 사진 삭제
                $this->aptModel->removePho($phoNo);


            } else {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '잘못된 접근'
                ]);
            }


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


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


    // 업로드 파일 카테고리 지정
    public function savePhoCate()
    {
        try {

            $rcpt_no = $this->request->getPost('rcpt_no');
            $code1 = $this->request->getPost('code1');
            $code2 = $this->request->getPost('code2');
            $phoNo = $this->request->getPost('phoNo');

            if (!is_array($phoNo))
                $phoNo = [$phoNo];

            if (empty($phoNo)) {
                return $this->response->setJSON([
                    'code' => '9',
                    'msg' => '데이터 누락'
                ]);
            }

            foreach ($phoNo as $pho) {

                $data = [
                    'rcpt_no' => $rcpt_no,
                    'pho_no' => $pho,
                    'code1' => $code1,
                    'code2' => $code2,
                ];

                // 카테고리 지정
                $this->aptModel->updatePhoCate($data);

            }

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


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


    /**
     * 동기화요청 API
     */
    public function syncRequestListNew($hscp_no, $postData)
    {

        $addr = $this->apt_model->getSyncAddr();
        $key = $addr['api_key'];
        $server = $addr['api_server'];
        $secret = $addr['api_secret'];
        $urlString = $server . "/kiso/confirms/complex/" . $hscp_no . "/photo";

        $postData = str_replace("\\/", '/', $postData);


        $headers = array();
        $headers[] = 'x-naver-client-id: ' . $key;
        if (!empty($secret)) {
            $headers[] = 'x-naver-client-secret: ' . $secret;
        }
        $headers[] = 'Accept: application/json';
        $headers[] = 'Content-Type: application/json';

        // var_dump( $urlString );
        // var_dump( $headers );
        log_message('debug', ' syncRequestListNew => url =>' . $urlString . '===============postData =>' . $postData);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $urlString,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => $headers,
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        $result = json_decode($response, TRUE);

        log_message('debug', ' syncRequestListNew => url =>' . $urlString . '===============returnData =>' . $response . '====http_code===' . $info);
        // if ( $info == "200" ) {
        if (isset($result) && $result['code'] == 'success') {
            return $result;
        } else {
            return array('code' => 'fail', 'message' => '전송실패', "timeStamp" => date("Y-m-dTH:i:s"));
        }

        // $jsonArray = json_decode($response, TRUE);

        // if ($response === false || $info['http_code'] != 200){
        // 		$return = "false";
        // }else{
        // 	$jsonArray = json_decode($response, TRUE);
        // 	if ($jsonArray['code'] == "success"){
        // 		// $return = $jsonArray['syncList'];
        // 		$return = "true";

        // 	}else{
        // 		$return = "false";
        // 	}
        // }
        // return $return;
    }
}