<?php
namespace App\Controllers\Article;

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

/**
 * 아파트 평면도
 * 2025.12.26
 * 작성자 : yangsh
 */
class Ground extends BaseController
{
    private $model, $codeModel;


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

    public function lists(): string
    {

        $codes = $this->codeModel->getCodeLists(['VIDEO_TARGET', 'APT_GROUND_STEP', 'PHO_YN', 'VDO_YN']); // 코드조회
        $sido = $this->model->getAreaList(); // 지역조회
        $bonbu = $this->model->getBonbuList(); // 본부
        $team = $this->model->getTeamList(); // 팀
        $user = $this->model->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/lists2", $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'), // 단지코드
            'part_no' => $this->request->getGet('part_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'), // 종료일            

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

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

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

        $deptStatistics = $this->model->getDeptStatistics($data); // 조직별통계
        $areaStatistics = $this->model->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 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 = [
                    'hscp_no' => $data[1],
                    'region_cd' => $data[2],
                    'part_no' => $data[0],
                    'apt_step' => 'S01',
                    'addr' => $data[3] . ' ' . $data[4] . ' ' . $data[5],
                    'addr2' => $data[6],
                    'rcpt_hscp_nm' => $data[7],
                    'apt_cate_nm' => $data[8],
                    'pyeong_cnt' => $data[9],
                    'rcpt_x' => $data[10],
                    'rcpt_y' => $data[11],
                    'ginsert_tm' => $rdate,
                ];

                // INSERT apt_ground
                $this->model->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'), // 단지코드
                'part_no' => $this->request->getGet('part_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'), // 종료일            

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

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

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

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

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


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


        $listDept = $this->model->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 chgAptDamdang()
    {
        try {

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

            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->model->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 detail($rcpt_no, $hscp_no): string
    {

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

        $bonbu = $this->model->getBonbuList();
        $team = $this->model->getTeamList();
        $user = $this->model->getUserList();

        // 상세정보
        $apt = $this->model->getDetail($rcpt_no, $hscp_no);

        // 동일단지
        $rdata = $this->model->getDetailLists($rcpt_no, $hscp_no);

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

        $this->data['bonbu'] = $bonbu;
        $this->data['team'] = $team;
        $this->data['user'] = $user;
        $this->data['apt'] = $apt;
        $this->data['rdata'] = $rdata;
        $this->data['history'] = $history;

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

    // 메모저장
    public function saveMemo()
    {
        try {

            $data = [
                'rcpt_no' => $this->request->getPost('rcpt_no'),
                'memo' => $this->request->getPost('memo'),
            ];

            // UPDATE apt_ground
            $this->model->saveMemo($data);

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

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

    // 담당자 변경
    public function saveKeeper()
    {
        try {


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


            // UPDATE apt_ground
            $this->model->saveKeeper($data);


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

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

    // 단지상태변경
    public function statusChange()
    {
        $lib = new MyUpload();

        try {

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


            if ($type === "phoX") {
                $apt = $this->model->getDetail($rcpt_no, "");

                if (!empty($apt['pho_no'])) {
                    $path = $apt['file_path'] . "" . $apt['filenm_up'];

                    $lib->deleteFile($path);
                }


            }

            // UPDATE apt_ground
            $this->model->statusChange($rcpt_no, $type);


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

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

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

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


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


            // UPDATE apt_ground
            $this->model->saveNote($data);


            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 {

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


            if (!isset($rcpt_no)) {
                return $this->response->setJSON([
                    'success' => false,
                    'msg' => '접수번호 누락'
                ]);
            }

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


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

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

            $gps_lat = null;
            $gps_lon = null;
            $camDate = null;
            // print_r($arrUploadfile);
            // exit;
            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;
                            }
                        }

                    }

                    $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'], // 저장파일명
                        'file_ext' => '.' . $uploadFile['ext'], // 파일확장자
                        'upload_path' => $uploadPath, // 저장경로
                        'thumb_name' => $base . '_thumb.jpg',
                        'cam_date' => $camDate, // 촬영일
                    ];

                    // INSERT INTO apt_ground_photo
                    $res = $this->model->saveImg($uploadParam);
                    log_message('debug', 'apt_ground_file :: rcpt_no : ' . $rcpt_no . ', fileName : ' . $uploadFile['file_name']);

                }
            }

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

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