<?php
namespace App\Models\results;

use CodeIgniter\Model;

class M412Model extends Model
{
    public function get_send_yn($data)
    {
        $sql = "
                SELECT stop_yn
                FROM v2_stop_api_chg_stat
                WHERE `TYPE` = ?
                ORDER BY pk DESC
                LIMIT 1
                ";

        $query = $this->db->query($sql, [$data]);
        $row = $query->getRow();

        return $row ? $row->stop_yn : 'N';
    }
    public function getTotalCount($data)
    {
        $sql = "SELECT COUNT(*) AS cnt FROM (
                        SELECT * FROM v2_st_daily a
                    WHERE a.st_date BETWEEN DATE('{$data['sdate']}') AND DATE('{$data['edate']}')
                        GROUP BY a.st_date, a.cpid
                ) AS t ";

        $query = $this->db->query($sql);

        return $query->getRow()->cnt;
    }

    public function getResultList($data)
    {
        $sql = "SELECT
                    st_date,
                    cpid,
                    T0101, T0102, T0103,
                    T0201, T0202, T0203, T0204,
                    (T0201 + T0202 + T0203 + T0204) AS T0205,
                    T0301, T0302,
                    (T0101 + T0102 + T0103 - (T0201 + T0202 + T0203 + T0204)) AS T0303,
                    D0101, D0102, D0103,
                    D0201, D0202, D0203,
                    (D0201 + D0202 + D0203) AS D0204,
                    D0301, D0302,
                    (D0101 + D0102 + D0103 - (D0201 + D0202 + D0203)) AS D0303,
                    R0101, R0102, R0103,
                    (R0101 + R0102 + R0103) AS R0104,
                    R0105,
                    (T0101 + T0102 + T0103 + D0101 + D0102 + D0103) AS Z0101,
                    (T0201 + T0202 + T0203 + T0204 + D0201 + D0202 + D0203) AS Z0102,
                    (T0206 + D0205 + R0101 + R0103) AS Z0103,
                    (T0101 + T0102 + T0103 + D0101 + D0102 + D0103 - T0206 - D0205 - R0101 - R0103) AS Z0104,
                    A0101
                FROM (
                    SELECT
                        a.st_date,
                        a.cpid,
                        SUM(CASE a.gbn_cd WHEN 'T0101' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0101,
                        SUM(CASE a.gbn_cd WHEN 'T0102' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0102,
                        SUM(CASE a.gbn_cd WHEN 'T0103' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0103,
                        SUM(CASE a.gbn_cd WHEN 'T0201' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0201,
                        SUM(CASE a.gbn_cd WHEN 'T0202' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0202,
                        SUM(CASE a.gbn_cd WHEN 'T0203' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0203,
                        SUM(CASE a.gbn_cd WHEN 'T0204' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0204,
                        SUM(CASE a.gbn_cd WHEN 'T0206' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0206,
                        SUM(CASE a.gbn_cd WHEN 'T0301' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0301,
                        SUM(CASE a.gbn_cd WHEN 'T0302' THEN COALESCE(a.cnt,0) ELSE 0 END) AS T0302,
                        SUM(CASE a.gbn_cd WHEN 'D0101' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0101,
                        SUM(CASE a.gbn_cd WHEN 'D0102' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0102,
                        SUM(CASE a.gbn_cd WHEN 'D0103' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0103,
                        SUM(CASE a.gbn_cd WHEN 'D0201' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0201,
                        SUM(CASE a.gbn_cd WHEN 'D0202' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0202,
                        SUM(CASE a.gbn_cd WHEN 'D0203' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0203,
                        SUM(CASE a.gbn_cd WHEN 'D0205' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0205,
                        SUM(CASE a.gbn_cd WHEN 'D0301' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0301,
                        SUM(CASE a.gbn_cd WHEN 'D0302' THEN COALESCE(a.cnt,0) ELSE 0 END) AS D0302,
                        SUM(CASE a.gbn_cd WHEN 'R0101' THEN COALESCE(a.cnt,0) ELSE 0 END) AS R0101,
                        SUM(CASE a.gbn_cd WHEN 'R0102' THEN COALESCE(a.cnt,0) ELSE 0 END) AS R0102,
                        SUM(CASE a.gbn_cd WHEN 'R0103' THEN COALESCE(a.cnt,0) ELSE 0 END) AS R0103,
                        SUM(CASE a.gbn_cd WHEN 'R0105' THEN COALESCE(a.cnt,0) ELSE 0 END) AS R0105,
                        SUM(CASE a.gbn_cd WHEN 'A0101' THEN COALESCE(a.cnt,0) ELSE 0 END) AS A0101
                    FROM v2_st_daily a
                    WHERE a.st_date BETWEEN DATE('{$data['sdate']}') AND DATE('{$data['edate']}')
                    GROUP BY a.st_date, a.cpid
                ) AS V_T ";

        $query = $this->db->query($sql);


        return $query->getResultArray();
    }

    // 전송 타입 저장
    public function saveSendType($data)
    {
        $sql = "INSERT INTO v2_stop_api_chg_stat(`type`, insert_date, stop_yn, usr_sq) ";
        $sql .= "VALUES (?, NOW(), ?, ?) ";

        $this->db->query($sql, [
            $data['type'],
            $data['yn'],
            $data['usr_sq'],
        ]);


        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => '저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }


    public function getLists($data)
    {
        $sql = "SELECT
                    a.vr_sq,
                    j.usr_nm as reg_charger,
                    a.atcl_no,
                    a.cpid,
                    a.cp_atcl_id,
                    a.rlet_type_cd,
                    a.address1,
                    a.sise, 
                    a.rdate,
                    a.seller_tel_no,
                    a.seller_nm,
                    a.realtor_nm,
                    a.realtor_tel_no,
                    a.rlet_type_cd,
                    a.charger,
                    b.insert_tm,
                    b.stat_cd,
                    c.bild_nm,
                    b.vrfc_type,
                    c.rm_no,
                    c.`floor`,
                    c.address_code,
                    c.address2,
                m.address2a,
                m.address2b,
                    c.address3,
                    c.trade_type,
                    c.deal_amt,
                    c.wrrnt_amt,
                    c.lease_amt,
                    c.isale_amt,
                    c.prem_amt,
                    c.sply_spc,
                    c.excls_spc,
                    c.tot_spc,
                    c.grnd_spc,
                    c.bldg_spc,
                    c.hscp_no,
                    c.ptp_no,
                    d.insert_tm as update_res_tm,
                    greatest(ifnull(d45.insert_tm, ''), ifnull(d49.insert_tm, '')) as rgbk_check_tm,
                    e.insert_tm as result_tm,
                    f.region_nm,
                    g.cd_nm as pre_stat,
                    h.cd_nm as vrfc_type,
                    i.usr_nm,
                    d2.insert_tm as stat_39_tm,
                    a.vrfc_type_sub,
                    a.reference_file_url_yn,
                    k.`comment` AS reg_conf_yn_info_2,
                    l.`comment` AS reg_conf_yn_info_3,
                    m.corp_own
                FROM
                    v2_article_info a
                JOIN v2_vrfc_req b ON a.vr_sq = b.vr_sq	
                JOIN v2_modify_info c ON a.vr_sq = c.vr_sq
                LEFT JOIN v2_article_info_etc m ON a.vr_sq = m.vr_sq
                LEFT JOIN region_codes f ON a.address_code = f.region_cd
                LEFT JOIN v2_chg_stat d ON a.vr_sq = d.vr_sq AND d.stat_cd = '35'
                LEFT JOIN v2_chg_stat d45 ON d45.vr_sq = a.vr_sq AND d45.stat_cd = '45'
                LEFT JOIN v2_chg_stat d49 ON d49.vr_sq = a.vr_sq AND d49.stat_cd = '49'
                LEFT JOIN v2_chg_stat e ON a.vr_sq = e.vr_sq AND e.stat_cd = '60'
                LEFT JOIN codes g ON  b.stat_cd = g.cd AND g.category = 'STEP_VERIFICATION'
                LEFT JOIN codes h ON b.vrfc_type = h.cd AND h.category = 'VRFCREQ_WAY'
                LEFT JOIN users i ON a.charger = i.usr_id
                LEFT JOIN users j ON a.reg_charger = j.usr_id
                LEFT JOIN v2_check_list k ON a.vr_sq = k.vr_sq AND k.`type` = '21'
                LEFT JOIN v2_check_list l ON a.vr_sq = l.vr_sq AND l.type = '22'
                LEFT JOIN v2_chg_stat d2 ON d2.vr_sq = a.vr_sq AND d2.stat_cd = '39'

                WHERE
                    1=1 ";

        if (!empty($data['stat_cd'])) {
            $sql .= "AND b.stat_cd = {$data['stat_cd']} ";
        }

        if (!empty($data['sdate'])) {
            $sql .= "AND b.insert_tm >= '{$data['sdate']} 00:00:00' ";
        }

        if (!empty($data['edate'])) {
            $sql .= "AND b.insert_tm <= '{$data['edate']} 00:00:00' ";
        }


        $sql .= "ORDER BY b.vr_sq desc , b.insert_tm desc ";


        $query = $this->db->query($sql);

        return $query->getResultArray();
    }

    public function chgStat($vr_sq, $stat_cd, $usr_sq, $insert_tm)
    {
        $sql = "INSERT INTO v2_chg_stat (vr_sq, stat_cd, insert_user, insert_tm) ";
        $sql .= "VALUES (?, ?, ?, ?) ";
        $sql .= "ON DUPLICATE KEY UPDATE ";
        $sql .= "UPDATE vr_sq=VALUES(vr_sq), stat_cd=VALUES(stat_cd), insert_user=VALUES(insert_user), insert_tm=VALUES(insert_tm) ";

        $this->db->query($sql, [$vr_sq, $stat_cd, $usr_sq, $insert_tm]);

        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => 'v2_chg_stat 저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }

    public function chgStatVrfc($vr_sq, $stat_cd)
    {
        $sql = "UPDATE v2_vrfc_req SET ";
        $sql .= "stat_cd = ? ";
        $sql .= "WHERE vr_sq = ? ";

        $this->db->query($sql, [$stat_cd, $vr_sq]);

        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => 'v2_vrfc_req 저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }

    public function chgStatFax($vr_sq, $stat_cd)
    {
        $sql = "UPDATE fax_imgs SET ";
        $sql .= "stat_cd = ? ";
        $sql .= "WHERE vr_sq = ? ";

        $this->db->query($sql, [$stat_cd, $vr_sq]);

        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => 'fax_imgs 저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }

    //	서류/전화 불일치 시간
    public function getFaxFailTimeForHistory($vr_sq)
    {
        $sql = "select insert_tm from v2_chg_history" .
            " where vr_sq = ?" .
            " and stat_cd = '39'" .
            " and chg_type= 'C9'" .
            " order by seq desc" .
            " limit 1 ";

        $query = $this->db->query($sql, [$vr_sq]);

        return $query->getRowArray();
    }

    //	서류/전화 인입시간
    public function getSaveTimeForHistory($vr_sq)
    {
        $sql = "select insert_tm from v2_chg_history" .
            " where vr_sq = ?" .
            " and stat_cd = '30'" .
            " and chg_type= 'C9'" .
            " order by seq desc" .
            " limit 1 ";

        $query = $this->db->query($sql, [$vr_sq]);

        return $query->getRowArray();
    }

    //	서류/전화 확인완료 시간 = 등기부등본 확인중 시간
    public function getConfTimeForHistory($vr_sq)
    {
        $sql = "select insert_tm from v2_chg_history" .
            " where vr_sq = ?" .
            " and stat_cd = '35'" .
            " and chg_type= 'C9'" .
            " order by seq desc" .
            " limit 1 ";

        $query = $this->db->query($sql, [$vr_sq]);

        return $query->getRowArray();
    }

    //	검증완료 시간
    public function get_60_ForHistory($vr_sq)
    {
        $sql = "select insert_tm from v2_chg_history" .
            " where vr_sq = ?" .
            "  and stat_cd = '60'" .
            " and chg_type= 'C9'" .
            " order by seq desc" .
            " limit 1  ";

        $query = $this->db->query($sql, [$vr_sq]);

        return $query->getRowArray();
    }


    public function insert_v2_time_required_Conf_Done($atcl_no, $cpid, $vrfc_type, $insert_tm, $tel_doc_conf_dt, $finishTime)
    {
        if (substr($insert_tm, 0, 10) == substr($tel_doc_conf_dt, 0, 10)) {
            switch ($vrfc_type) {
                case 'D':
                    if (('12:00:00' < substr($insert_tm, -8)) && (substr($insert_tm, -8) < '13:00:00')) {//접수시간이 12~13시 사이면 13시로 해준다
                        if (substr($tel_doc_conf_dt, -8) > '13:00:00') {	//검증완료가 13시 '이후'에 끝나면 접수시간을 13시로 변경해준다
                            $insert_tm = date("Y-m-d", time()) . " 13:00:00";
                        }
                    } else if (
                        (substr($insert_tm, -8) > '17:30:00' || substr($insert_tm, -8) < '08:59:59') && //접수와 확인완료시간이 모두  17:30:00 ~ 09:00:00 사이가 아니면
                        (substr($tel_doc_conf_dt, -8) < '17:30:00' || substr($tel_doc_conf_dt, -8) < '08:59:59')
                    ) {
                        $insert_tm = date("Y-m-d", time()) . " 09:00:00";
                    }
                    ;
                    break;

                case 'T':
                    if (('13:00:00' < substr($insert_tm, -8)) && (substr($insert_tm, -8) < '14:00:00')) {//접수시간이 13~14시 사이면 14시로 해준다
                        if (substr($tel_doc_conf_dt, -8) > '14:00:00') {	//검증완료가 14시 '이후'에 끝나면 접수시간을 14시로 변경해준다
                            $insert_tm = date("Y-m-d", time()) . " 14:00:00";
                        }
                    } else if (
                        (substr($insert_tm, -8) > '17:30:00' || substr($insert_tm, -8) < '08:59:59') &&
                        (substr($tel_doc_conf_dt, -8) < '17:30:00' || substr($tel_doc_conf_dt, -8) < '08:59:59')
                    ) {	//접수와 확인완료시간이 모두  17:30:00 ~ 09:00:00 사이면
                        $insert_tm = date("Y-m-d", time()) . " 09:30:00";
                    }
                    ;
                    break;
            }
        } else {
            if ($vrfc_type == 'D') {	//홍보
                if (substr($insert_tm, -8) > '17:30:00' || substr($insert_tm, -8) < '08:59:59') {
                    $insert_tm = date("Y-m-d", time()) . " 09:00:00";
                }
            } else {	//전화
                if (substr($insert_tm, -8) > '17:30:00' || substr($insert_tm, -8) < '08:59:59') {
                    $insert_tm = date("Y-m-d", time()) . " 09:30:00";
                }
            }
        }
        $stan_date = substr($insert_tm, 0, 10);


        $sql = "INSERT INTO v2_time_required(stan_date, atcl_no, cpid, vrfc_type, insert_tm, tel_doc_conf_dt,conf_required_tm,tot_required_tm)" .
            " VALUES(?, ?, ?, ?, ?, ?, TIMEDIFF(?,?), TIMEDIFF(?,?)) " .
            " ON DUPLICATE KEY UPDATE insert_tm = VALUES(insert_tm), tel_doc_conf_dt=VALUES(tel_doc_conf_dt),conf_required_tm = VALUES(conf_required_tm),tot_required_tm = VALUES(tot_required_tm) ";

        $this->db->query($sql, [
            $stan_date,
            $atcl_no,
            $cpid,
            $vrfc_type,
            $insert_tm,
            $tel_doc_conf_dt,
            $tel_doc_conf_dt,
            $insert_tm,
            $tel_doc_conf_dt,
            $insert_tm,
        ]);

        if ($this->db->transStatus() === false) {
            return [
                'success' => false,
                'msg' => 'v2_time_required 저장실패',
            ];
        }

        // 성공
        return [
            'success' => true,
        ];
    }

    /**
     * 일자별 통계데이터에 값 집어 넣기...
     * 반환값 없음.
     * @param date $sd_date 날짜 값이 없을경우 현재날짜로 입력됨.
     * @param string $cpid CPID
     * @param string $gbn_cd 코드값 (category='STATISTICS_DAILY3')
     * @param int $cnt 더할 숫자..
     * @param string $cnt_type 숫자를 더할것인지.. 아니변 변경할것인지.
     */
    public function set_v2_st_daily($st_date, $cpid, $gbn_cd, $cnt, $cnt_type = 'add')
    {
        if (empty($cnt))
            $cnt = '0';

        $sql_dup = "";
        switch (strtolower($cnt_type)) {
            case 'add':
                $sql_dup = "on duplicate key update cnt = cnt + " . $cnt;
                break;

            case 'change':
                $sql_dup = "on duplicate key update cnt = values(cnt)";
                break;
        }
        if (empty($st_date)) {
            $sql = "insert into v2_st_daily (st_date, cpid, gbn_cd, cnt) values (now(), ?, ?, ?)" . $sql_dup;
            $data =
                [
                    $cpid,
                    $gbn_cd,
                    $cnt
                ]
            ;
        } else {
            $sql = "insert into v2_st_daily (st_date, cpid, gbn_cd, cnt) values (?, ?, ?, ?)" . $sql_dup;
            $data = [
                $st_date,
                $cpid,
                $gbn_cd,
                $cnt
            ];
        }

        $this->db->query($sql, $data);

        $return['error_number'] = $this->db->_error_number();
        $return['error_message'] = $this->db->_error_message();

        return $return;
    }
}