<?php
namespace App\Models\manage;

use CodeIgniter\Model;

class MenuModel extends Model
{

    public function getTotalCount()
    {
        $sql = "SELECT COUNT(*) AS cnt FROM menu WHERE 1=1 ";

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

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

    public function getMenuList($params)
    {

        $sql = "SELECT mnu_id, " .
            "      mnu_pid, " .
            "      (SELECT mnu_nm FROM menu WHERE mnu_id = a.mnu_pid) mnu_pid_nm, " .
            "      mnu_nm, " .
            "      mnu_tp, " .
            "      CASE WHEN mnu_tp = 'D' THEN '디렉토리' WHEN mnu_tp = 'P' THEN '화면' WHEN mnu_tp = 'R' THEN '루트' END AS mnu_tp_nm, " .
            "      mnu_url, " .
            "      use_yn, " .
            "      CASE WHEN use_yn = 'Y' THEN '사용' ELSE '미사용' END AS use_yn_nm, " .
            "      view_odr, " .
            "      insert_tm, " .
            "      (select usr_nm from users where usr_sq = a.insert_usr) insert_usr, " .
            "      (select usr_nm from users where usr_sq = a.update_usr) update_usr, " .
            "      update_tm " .
            " FROM menu a ";

        $sql .= "WHERE 1=1 ";

        // if (!empty($params['pid'])) {
        // $sql .= " AND mnu_pid = {$params['pid']} ";
        // }

        $sql .= " ORDER BY CASE WHEN mnu_pid = 'ROOT' THEN 0 ELSE 1 END, mnu_id, view_odr";


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


        return $query->getResultArray();

    }

    // 메뉴정보저장
    public function saveMenu($data)
    {
        $sql = "INSERT INTO menu ";
        $sql .= "(mnu_id, mnu_pid, mnu_nm, mnu_tp, mnu_url, view_odr, use_yn, insert_tm, insert_usr, update_tm, update_usr) ";
        $sql .= "VALUES ";
        $sql .= "('{$data['mnu_id']}', ";
        $sql .= " '{$data['mnu_pid']}', ";
        $sql .= " '{$data['mnu_nm']}', ";
        $sql .= " '{$data['mnu_tp']}', ";
        $sql .= " '{$data['mnu_url']}', ";
        $sql .= " {$data['view_odr']}, ";
        $sql .= " '{$data['use_yn']}', ";
        $sql .= " NOW(), ";
        $sql .= " {$data['usr_sq']}, ";
        $sql .= " NOW(), ";
        $sql .= " {$data['usr_sq']}) ";
        $sql .= "ON DUPLICATE KEY UPDATE ";
        $sql .= " mnu_nm    = '{$data['mnu_nm']}', ";
        $sql .= " mnu_tp    = '{$data['mnu_tp']}', ";
        $sql .= " mnu_url   = '{$data['mnu_url']}', ";
        $sql .= " view_odr  = {$data['view_odr']}, ";
        $sql .= " use_yn    = '{$data['use_yn']}', ";
        $sql .= " update_tm = NOW(), ";
        $sql .= " update_usr = {$data['usr_sq']}";


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



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

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

}