<?php
namespace App\Models\manage;

use CodeIgniter\Model;

class UserModel extends Model
{

    // 유저레벨
    public function getUserLevel()
    {
        $sql = "SELECT cd, cd_nm" .
            "  FROM codes" .
            " WHERE category = 'USER_LEVEL'" .
            " AND use_yn = 'Y'" .
            " ORDER BY view_odr asc";

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

        return $query->getResultArray();
    }

    // 본부리스트
    public function getBonbuList()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
            "  FROM departments" .
            " WHERE depth = 1" .
            "   AND use_yn = 'Y'" .
            " ORDER BY lft";

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

        return $query->getResultArray();
    }

    // 팀리스트
    public function getTeamList()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm" .
            "  FROM departments" .
            " WHERE depth = 2" .
            "   AND use_yn = 'Y'" .
            " ORDER BY dept_nm";

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

        return $query->getResultArray();
    }

    // 조직리스트
    public function getDeptCode()
    {
        $sql = "SELECT dept_sq, pdept_sq, dept_nm, dept_desc, dept_head, use_yn, depth, insert_tm, insert_usr, update_tm, update_usr, lft, rgt" .
            "  FROM departments" .
            "  WHERE use_yn = 'Y' " .
            " ORDER BY lft";

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

        return $query->getResultArray();
    }

    public function getTotalCount($data)
    {
        $params = [];

        $sql = "SELECT COUNT(*) AS cnt FROM users AS a WHERE 1=1 ";

        if (!empty($data['srchLevel'])) {
            $sql .= " AND a.usr_level = ?";
            array_push($params, $data['srchLevel']);
        }

        if (!empty($data['srchTeam'])) {
            $sql .= " AND a.dept_sq = ? ";
            array_push($params, $data['srchTeam']);
        }

        if (!empty($data['useYn'])) {
            $sql .= " AND a.use_yn = ? ";
            array_push($params, $data['useYn']);
        }

        if (!empty($data['srchTxt'])) {
            switch ($data['srchType']):
                case "1":
                    $sql .= " AND a.usr_nm LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "2":
                    $sql .= " AND a.usr_id LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "3":
                    $sql .= " AND a.usr_position LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "4":
                    $sql .= " AND REPLACE(a.usr_tel1, '-', '') LIKE CONCAT('%', REPLACE(?, '-', ''), '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "5":
                    $sql .= " AND CONCAT(a.usr_addr1, ' ', a.usr_addr2) LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                default:
                    $sql .= "
                            AND (
                                a.usr_nm LIKE CONCAT('%', ?, '%')   
                                OR a.usr_id LIKE CONCAT('%', ?, '%')
                                OR a.usr_position LIKE CONCAT('%', ?, '%')
                                OR REPLACE(a.usr_tel1, '-', '') LIKE CONCAT('%', REPLACE(?, '-', ''), '%')
                                OR CONCAT(a.usr_addr1, ' ', a.usr_addr2) LIKE CONCAT('%', ?, '%')
                            )
                            ";
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    break;
            endswitch;

        }

        $query = $this->db->query($sql, $params ?: []);

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


    public function getUserList($start, $end, $data)
    {
        $params = [];

        $sql = "SELECT
	                usr_sq
                    ,	(select dept_sq from departments where dept_sq = (select pdept_sq from departments where a.dept_sq = dept_sq)) pdept_sq				
                    , (select dept_nm from departments where dept_sq = (select pdept_sq from departments where a.dept_sq = dept_sq)) pdept_nm
                    , (select dept_nm from departments where a.dept_sq = dept_sq) as dept_nm
                    , dept_sq
                    , usr_id
                    , usr_nm
                    , (select cd_nm from codes where a.usr_level = cd and category = 'USER_LEVEL') level_nm
                    , usr_level
                    , usr_position
                    , usr_tel1
                    , usr_tel2
                    , usr_addr1
                    , usr_addr2
                    , insert_tm
                    , (select usr_nm from users where usr_sq = a.insert_usr) insert_usr
                    , update_tm
                    , (select usr_nm from users where usr_sq = a.update_usr) update_usr
                    , use_yn
                    , case when a.use_yn = 'Y' then '예' when a.use_yn = 'N' then '아니요' end as use_yn_nm 
                    , sms_auth_yn
                    , case when a.sms_auth_yn = 'Y' then '예' when a.sms_auth_yn = 'N' then '아니요' end as sms_auth_yn_nm
                    , last_usr_pw_tm
                FROM
                    users AS a 
                WHERE
                    1=1 ";

        if (!empty($data['srchLevel'])) {
            $sql .= " AND a.usr_level = ?";
            array_push($params, $data['srchLevel']);
        }

        if (!empty($data['srchTeam'])) {
            $sql .= " AND a.dept_sq = ?";
            array_push($params, $data['srchTeam']);
        }

        if (!empty($data['useYn'])) {
            $sql .= " AND a.use_yn = ?";
            array_push($params, $data['useYn']);
        }

        if (!empty($data['srchTxt'])) {
            switch ($data['srchType']):
                case "1":
                    $sql .= " AND a.usr_nm LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "2":
                    $sql .= " AND a.usr_id LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "3":
                    $sql .= " AND a.usr_position LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "4":
                    $sql .= " AND REPLACE(a.usr_tel1, '-', '') LIKE CONCAT('%', REPLACE(?, '-', ''), '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "5":
                    $sql .= " AND CONCAT(a.usr_addr1, ' ', a.usr_addr2) LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                default:
                    $sql .= "
                            AND (
                                a.usr_nm LIKE CONCAT('%', ?, '%')   
                                OR a.usr_id LIKE CONCAT('%', ?, '%')
                                OR a.usr_position LIKE CONCAT('%', ?, '%')
                                OR REPLACE(a.usr_tel1, '-', '') LIKE CONCAT('%', REPLACE(?, '-', ''), '%')
                                OR CONCAT(a.usr_addr1, ' ', a.usr_addr2) LIKE CONCAT('%', ?, '%')
                            )
                            ";
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    break;
            endswitch;

        }

        $sql .= "ORDER BY a.insert_tm DESC ";
        $sql .= "LIMIT ?, ?";

        $params[] = (int) $start; // offset
        $params[] = (int) $end;   // limit


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

        return $query->getResultArray();
    }


    // 유저등록
    public function insertUser($data)
    {


        $sql = "INSERT INTO users
                (usr_id, usr_pw, dept_sq, usr_nm, usr_level, usr_position, usr_tel1, usr_tel2, usr_addr1, usr_addr2, insert_tm, insert_usr, use_yn, sms_auth_yn, last_usr_pw_tm)" .
            " VALUES (?, SHA2(?,256), ?, ?, ?, ?, ?, ?, ?, ?, now(), ?, ?, ?, now())";


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

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

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


    // 유저수정
    public function updateUser($data, $addUserPswd, $usrSq)
    {
        $sql = "UPDATE users SET 
            usr_nm = ?,
            dept_sq = ?,
            usr_level = ?,
            usr_position = ?,
            usr_tel1 = ?,
            usr_tel2 = ?,
            usr_addr1 = ?,
            usr_addr2 = ?,
            update_tm = NOW(),
            update_usr = ?,
            use_yn = ?,
            sms_auth_yn = ?";

        $params = [
            $data[0],  // usr_nm
            $data[1],  // dept_sq
            $data[2],  // usr_level
            $data[3],  // usr_position
            $data[4],  // usr_tel1
            $data[5],  // usr_tel2
            $data[6],  // usr_addr1
            $data[7],  // usr_addr2
            $data[8],  // update_usr
            $data[9],  // use_yn
            $data[10], // sms_auth_yn
        ];

        if (!empty($addUserPswd)) {
            $sql .= ", usr_pw = SHA2(?, 256),
                  last_usr_pw_tm = NOW()";
            $params[] = $addUserPswd;
        }

        $sql .= " WHERE usr_sq = ?";
        $params[] = $usrSq;

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

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

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

    public function removeUser($data)
    {

        $sql = " UPDATE users			" .
            " SET usr_nm = '***'	" .
            " ,usr_pw = '1234'		" .
            " ,usr_tel1 = '***'		" .
            " ,usr_tel2 = ''		" .
            " ,usr_addr1 = ''		" .
            " ,usr_position = ''	" .
            " ,dept_sq = '14' 		" .	//소속조직 : 퇴사자 관리
            " ,sms_auth_yn = 'N'	" .
            " ,use_yn = 'N'			" .
            " ,usr_addr2 = '삭제'		" .
            " ,update_tm = NOW()	" .
            " ,update_usr = ? 		" .
            " WHERE usr_sq = ?		";


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


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

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

    // 유저 SMS 인증정보 일괄 수정
    public function updateUserSmsYn($useYn)
    {
        $sql = "UPDATE users
				SET sms_auth_yn = {$useYn}}
				WHERE use_yn = 'Y' ";

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

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

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

    // 엑셀 다운로드 조회
    public function getExcelUserList($data)
    {
        $params = [];

        $sql = "SELECT
                    (select dept_nm from departments where dept_sq = (select pdept_sq from departments where a.dept_sq = dept_sq)) AS '소속본부'
                    , (select dept_nm from departments where a.dept_sq = dept_sq) AS '소속팀'
                    , usr_id AS '사원번호'
                    , usr_nm AS '사용자명'
                    , (SELECT cd_nm FROM codes where a.usr_level = cd and category = 'USER_LEVEL') AS '등급'
                    , usr_position AS '직급'
                    , usr_tel1 AS '연락처'
                    , CONCAT(usr_addr1, usr_addr2) AS '주소'
                    , case when a.sms_auth_yn = 'Y' then '예' when a.sms_auth_yn = 'N' then '아니요' end AS 'SMS인증여부'
                    , insert_tm AS '등록자'
                    , (select usr_nm from users where usr_sq = a.insert_usr) AS '등록일시'
                    , update_tm AS '수정자'
                    , (select usr_nm from users where usr_sq = a.update_usr) AS '수정일시'                
                    , last_usr_pw_tm AS '비빌번호변경일시'
                FROM
                    users AS a 
                WHERE
                    1=1 ";

        if (!empty($data['srchLevel'])) {
            $sql .= " AND a.usr_level = ? ";
            array_push($params, $data['srchLevel']);
        }

        if (!empty($data['srchTeam'])) {
            $sql .= " AND a.dept_sq = ? ";
            array_push($params, $data['srchTeam']);
        }

        if (!empty($data['useYn'])) {
            $sql .= " AND a.use_yn = ? ";
            array_push($params, $data['useYn']);
        }

        if (!empty($data['srchTxt'])) {
            switch ($data['srchType']):
                case "1":
                    $sql .= " AND a.usr_nm LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "2":
                    $sql .= " AND a.usr_id LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "3":
                    $sql .= " AND a.usr_position LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "4":
                    $sql .= " AND REPLACE(a.usr_tel1, '-', '') LIKE CONCAT('%', REPLACE(?, '-', ''), '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                case "5":
                    $sql .= " AND CONCAT(a.usr_addr1, ' ', a.usr_addr2) LIKE CONCAT('%', ?, '%') ";
                    array_push($params, $data['srchTxt']);
                    break;
                default:
                    $sql .= "
                            AND (
                                a.usr_nm LIKE CONCAT('%', ?, '%')   
                                OR a.usr_id LIKE CONCAT('%', ?, '%')
                                OR a.usr_position LIKE CONCAT('%', ?, '%')
                                OR REPLACE(a.usr_tel1, '-', '') LIKE CONCAT('%', REPLACE(?, '-', ''), '%')
                                OR CONCAT(a.usr_addr1, ' ', a.usr_addr2) LIKE CONCAT('%', ?, '%')
                            )
                            ";
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    array_push($params, $data['srchTxt']);
                    break;
            endswitch;

        }

        $sql .= "ORDER BY a.insert_tm DESC ";


        $query = $this->db->query($sql, $params ?: []);

        return $query->getResultArray();
    }


    // 최근 비밀번호 변경일 확인
    public function chkChgPwDiff($usr_id)
    {
        $sql = "SELECT DATEDIFF( NOW() , ifnull( last_usr_pw_tm , '2024-01-01 00:00:00') ) as diff FROM users WHERE usr_id = ?";

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

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

    // 기존 비밀번호 일치 확인
    public function chkUserExist($usr_id, $usr_pass)
    {
        $sql = "SELECT COUNT(*) AS cnt FROM users WHERE usr_id = ? AND usr_pw = SHA2(?, 256)";

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

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

    // 비밀번호 변경
    public function changeUsrPass($usr_id, $usr_pass, $new_pass)
    {
        $sql = "UPDATE users SET usr_pw = SHA2(?, 256), last_usr_pw_tm = NOW() WHERE usr_id = ? AND usr_pw = SHA2(?, 256) ";

        if ($this->db->query($sql, [$new_pass, $usr_id, $usr_pass]) === false) {
            return [
                'success' => false,
                'msg' => '비밀번호 변경 실패',
            ];
        }

        $this->addUserChgHistory(session('usr_sq'), session('usr_sq'), "개인 비밀번호 변경", $new_pass);

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

    }

    // 변경이력저장
    public function addUserChgHistory($usr_sq, $update_user, $memo, $pwd = null)
    {
        $sql = "INSERT INTO user_chg_history(usr_sq,update_user,memo,update_dttm )" .
            "    VALUES(?,?,?,now() )";
        $data = [
            $usr_sq,
            $update_user,
            $memo
        ];
        $this->db->query($sql, $data);
    }
}

