<?php
namespace App\Controllers\results;

use App\Controllers\BaseController;
use App\Models\common\SmsModel;
use App\Models\results\M412Model;


class M412 extends BaseController
{

    private $model;
    private $smsModel;

    public function __construct()
    {
        $this->model = new M412Model();
        $this->smsModel = new SmsModel();
    }


    public function stats(): string
    {
        $sendH = $this->model->get_send_yn('H');
        $sendD = $this->model->get_send_yn('D');
        $sendT = $this->model->get_send_yn('T');
        $sendN = $this->model->get_send_yn('N');
        $sendJ = $this->model->get_send_yn('J');
        $sendO = $this->model->get_send_yn('O');

        $this->data['sendH'] = $sendH;
        $this->data['sendD'] = $sendD;
        $this->data['sendT'] = $sendT;
        $this->data['sendN'] = $sendN;
        $this->data['sendJ'] = $sendJ;
        $this->data['sendO'] = $sendO;


        return view("pages/results/m412/stats", $this->data);
    }

    public function getResultList()
    {
        $data = [
            'sdate' => $this->request->getGet('sdate'),
            'edate' => $this->request->getGet('edate'),
        ];

        $totalCount = $this->model->getTotalCount($data);

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

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

    // 타입별 전송 on/off 저장
    public function saveSendType()
    {
        try {

            $usr_nm = session('usr_nm');
            $client_ip = getRealClientIp();

            $data = [
                'type' => $this->request->getPost('type'),
                'yn' => $this->request->getPost('yn'),
                'usr_sq' => session('usr_sq'),
            ];

            // INSERT v2_stop_api_chg_stat
            $this->model->saveSendType($data);

            $send_sms_member = [
                ["name" => '김인', "tel" => '010-4010-8318'],
                ["name" => "이민호", "tel" => '010-6743-3112'],
                ["name" => "이권희", "tel" => '010-4706-3638'],
            ];


            $send_h_yn = $this->model->get_send_yn('H');//가장 마지막의 홍보확인서 전송여부
            $send_t_yn = $this->model->get_send_yn('T'); //가장 마지막의 전화확인 전송여부
            $send_d_yn = $this->model->get_send_yn('D');//가장 마지막의 등기부등본 전송여부
            $send_n_yn = $this->model->get_send_yn('N'); //가장 마지막의 전화확인 전송여부
            $send_j_yn = $this->model->get_send_yn('J');//가장 마지막의 전화확인 전송여부
            $send_o_yn = $this->model->get_send_yn('O'); //가장 마지막의 모바일확인 V2 전송여부


            foreach ($send_sms_member as $member):

                $dest_phone = $member['tel'];
                $dest_name = $member['name'];
                $send_phone = '1600-5749';
                $send_name = 'SYSTEM';
                $subject = '매물 전송 확인 -' . date("Y-m-d H:i:s");

                $msg_body = '[' . date("Y-m-d H:i:s") . ']' . $usr_nm . "(" . $client_ip . ")" . '매물 전송 확인' . PHP_EOL
                    . '홍보확인서:' . $send_h_yn . PHP_EOL
                    . '전화확인:' . $send_t_yn . PHP_EOL
                    . '등기부등본:' . $send_d_yn . PHP_EOL
                    . '신홍보확인서:' . $send_n_yn . PHP_EOL
                    . '공동중개매물:' . $send_j_yn . PHP_EOL
                    . '모바일확인 V2:' . $send_o_yn;


                $msg_length = strlen(iconv('UTF-8', 'EUCKR', $msg_body));
                $msg_type = 0;
                if ($msg_length > 80 && $msg_type == 0) {
                    $msg_type = 5;
                }

                $memo = $msg_body;

                // 문자 발송
                // $this->smsModel->sendSms($dest_phone, $dest_name, $send_phone, $send_name, $subject, $msg_body, $msg_type, $memo);

            endforeach;




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

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

    // 전화확인완료 처리
    public function saveSendComplete()
    {
        try {
            $data = [
                'sdate' => $this->request->getPost('sdate'),
                'edate' => $this->request->getPost('edate'),
                'stat_cd' => 35,
            ];

            $lists = $this->model->getLists($data);

            if (empty($lists)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'msg' => '데이터 누락'
                ]);
            } else {
                foreach ($lists as $row):
                    $usr_sq = session('usr_sq');
                    $stat_cd = 60;
                    $vr_sq = $row['vr_sq'];
                    $fax_sq = $row['fax_sq'];
                    $toDay = date('Y-m-d H:i:s');
                    $atcl_no = $row['atcl_no'];
                    $vrfc_type = $row['vrfc_type'];
                    $cpid = $row['cpid'];

                    // INSERT INTO v2_chg_stat
                    $result_query8 = $this->model->chgStat($vr_sq, '60', $usr_sq, $toDay);

                    // UPDATE v2_vrfc_req
                    $chgVrfc60 = $this->model->chgStatVrfc($vr_sq, '60');	//v2_vrfc_req INSERT

                    // UPDATE fax_imgs
                    $statFaxUp60 = $this->model->chgStatFax($vr_sq, '60');	//fax_imgs

                    //★검증완료일때
                    //0.불일치 이력이 있는지 확인
                    $cnt = $this->model->getFaxFailTimeForHistory($vr_sq);
                    if (empty($cnt)) {
                        //1.서류전화 들어온시간
                        $insert_tm = $this->model->getSaveTimeForHistory($vr_sq);
                        //2.서류/전화 확인일자
                        $tel_doc_conf_dt = $this->model->getConfTimeForHistory($vr_sq);
                        //3.검증시간
                        $finishTime = $this->model->get_60_ForHistory($vr_sq);
                        //4.해당 정보를 테이블에 넣는다
                        $this->model->insert_v2_time_required_Conf_Done($atcl_no, $cpid, $vrfc_type, $insert_tm['recv_time'], $tel_doc_conf_dt['insert_tm'], $finishTime['insert_tm']);
                    }

                    // 홍보확인서완료 등기부등본확인 안함 저장
                    $this->model->set_v2_st_daily(NULL, $cpid, 'D0205', '1', 'add');

                endforeach;

                echo json_encode(['error' => ['code' => '0', 'message' => $cnt . '건 - 처리되었습니다.']]);

            }


            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 = [
                'sdate' => $this->request->getGet('sdate'),
                'edate' => $this->request->getGet('edate'),
            ];

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

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

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