<?php
namespace App\Models\manage;

use CodeIgniter\Model;

class PermitModel extends Model
{
    public function getUsrLevel()
    {
        $sql = "SELECT cd_sq AS 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 getMenuAuthList($usrLevel)
    {
        $sql = "SELECT 
                    a.mnu_id AS id, 
                    a.mnu_pid,
                    CASE WHEN a.mnu_pid = 'ROOT' THEN '#' WHEN a.mnu_pid = '0' THEN 'M' ELSE a.mnu_pid END AS `parent`, 
                    (SELECT a.mnu_nm FROM menu WHERE mnu_id = a.mnu_pid) mnu_pid_nm, 
                    a.mnu_nm AS text, 
                    a.mnu_tp, 
                    CASE WHEN a.mnu_tp = 'D' THEN '디렉토리' WHEN mnu_tp = 'P' THEN '화면' WHEN mnu_tp = 'R' THEN '루트' END AS mnu_tp_nm, 
                    a.mnu_url, 
                    CASE WHEN a.use_yn = 'Y' THEN '사용' ELSE '미사용' END AS use_yn_nm, 
                    a.view_odr,
                    b.mgrp_sq,
	                CASE WHEN b.mgrp_sq IS NOT NULL THEN 'selected' ELSE '' END `state`
                FROM
                    menu AS a
                LEFT JOIN
                    menu_perms AS b ON b.mnu_id = a.mnu_id	AND b.mgrp_sq = {$usrLevel}
                WHERE 1=1
                ORDER BY CASE WHEN id = 'ROOT' THEN 0 ELSE 1 END, a.mnu_id, a.view_odr
                ";

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

        return $query->getResultArray();
    }


    // 메뉴권한 전체삭제
    public function deleteMenuPermit($usrLevel)
    {
        $sql = "DELETE FROM menu_perms WHERE mgrp_sq = {$usrLevel} ";

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

    // 메뉴권한 등록
    public function saveMenuAuth($data)
    {
        $sql = "INSERT INTO menu_perms ";
        $sql .= "(mgrp_sq, mnu_id, prm_list, insert_tm, insert_usr, update_tm, update_usr) ";
        $sql .= "VALUES ";
        $sql .= "({$data['usrLevel']}, '{$data['mnuId']}', 'Y', NOW(), {$data['usrSq']}, NOW(), {$data['usrSq']}) ";

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

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

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