<?php
if( !$cate_area ) return;

include_once "{$_SERVER['DOCUMENT_ROOT']}/common.inc.php";
include_once _ADM_INC_PATH_ ."/auth_check.php";

include _ADM_INC_PATH_ ."/header.html";

if( !isset($mnuObj) ) $mnuObj = new Menu(TB_menu_list);
$mnuObj->cate_area = $cate_area;
?>

        <div id="cmd_bar" class="mb-2">
          <div class="h4"><i class="bi bi-files-alt"></i> 메뉴 관리</div>
          <div class="text-right">
          </div>
        </div>

        <div id="base_info_body" class="container-fluid mt-3">
          <div class="row">
            <div class="col-5">
              <h5 class="d-flex justify-content-between">
                <span><i class="bi bi-subtract"></i> 메뉴 리스트</span>
                <small class="text-info">※ 순서 및 위치는 마우스로 드래그 하여 변경합니다.</small>
              </h5>
              <div class="mt-3 cont_hfix">
                <div class="jstree-default sticky-top"><div id="trmenu_top" class="jstree-open"><a class="jstree-icon jstree-ocl" role="presentation"></a><i class="jstree-icon jstree-themeicon" role="presentation"></i>최상위</div></div>
                <div id="trmenu_list"></div>
              </div>
            </div>
            <div class="col-7">
              <h5><i class="bi bi-subtract"></i> 메뉴 정보</h5>
              <form method="post" name="menuform" class="mt-3 fadmin" action="###" onsubmit="return false">
                <?=hidden_input("parent_id","")?>
                <div class="fld-block">
                  <label class="form-label">현재 메뉴</label>
                  <div class="w-100 ">
                    최상위 <span class="menu_breadcrumb"></span>
                    <a href="javascript:;" class="btn_url btn btn-sm btn-info float-right">바로가기</a>
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_mode" class="form-label">작업 선택</label>
                  <div class="w-100">
                    <select class="form-select inline" id="cate_mode" name="cate_mode">
                      <option value="N">현재 메뉴를 부모로 하는 새로운 메뉴 추가</option>
                      <option value="M" disabled>현재 메뉴 수정</option>
                    </select>
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_id" class="form-label">메뉴 ID</label>
                  <div class="w-100">
                    <input type="text" class="form-control inline" id="cate_id" name="cate_id" placeholder="Menu ID">
                    <small class="text-info">※ ID는 전체 메뉴에서 고유한 값이어야 합니다.</small>
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_name" class="form-label">메뉴명</label>
                  <div class="w-100">
                    <input type="text" class="form-control inline" id="cate_name" name="cate_name" placeholder="메뉴명을 입력해 주세요.">
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_data" class="form-label">메뉴 URL 경로</label>
                  <div class="w-100">
                    <input type="text" class="form-control w-100" id="cate_data" name="cate_data" placeholder="Url 경로를 입력합니다.">
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_exp" class="form-label">메뉴 안내문</label>
                  <div class="w-100">
                    <textarea class="form-control" id="cate_exp" name="cate_exp"  placeholder="안내문이 필요할 경우 등록합니다."></textarea>
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_class" class="form-label">아이콘 Class</label>
                  <div class="w-100">
                    <input type="text" class="form-control" id="cate_class" name="cate_class" placeholder="메뉴의 아이콘과 관련한 Class를 지정합니다.">
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_use" class="form-label">사용여부</label>
                  <div class="w-100 form-control">
                    <label><input type="checkbox" class="form-check-inline" id="cate_use" name="cate_use" value="Y" data-defval=""> 사용함</label>
                  </div>
                </div>
                <div class="fld-block">
                  <label for="Code_Idx" class="form-label">접근 권한</label>
                  <div class="w-100">
                    <div class="input-group">
                      <span class="input-group-text w-25 allsel" data-tgt="cate_auth_read\[">조 회 : </span>
                      <div class="form-control d-flex justify-content-around">
                        <?=getCheckboxes("cate_auth_read[]", $mnuObj->authDest)?>
                      </div>
                    </div>
                    <div class="input-group">
                      <span class="input-group-text w-25 allsel" data-tgt="cate_auth_write\[">작 성 : </span>
                      <div class="form-control d-flex justify-content-around">
                        <?=getCheckboxes("cate_auth_write[]", $mnuObj->authDest)?>
                      </div>
                    </div>
                    <div class="input-group">
                      <span class="input-group-text w-25 allsel" data-tgt="cate_auth_delete\[">수정/삭제 : </span>
                      <div class="form-control d-flex justify-content-around">
                        <?=getCheckboxes("cate_auth_delete[]", $mnuObj->authDest)?>
                      </div>
                    </div>
                    <?php if( $GLOBALS['_Auth_']['menuObj']->hasMenuAuth("R","mnu_auth") ){?>
                    <small class="text-info">※ 상세 권한 관리는 <a href="/kadm/auth">[권한관리]</a> 메뉴를 이용하세요.</small>
                    <?php }?>
                  </div>
                </div>
                <div class="fld-block">
                  <label for="cate_exp" class="form-label">권한 적용페이지</label>
                  <div class="w-100">
                    <textarea class="form-control" id="cate_filepath" name="cate_filepath" rows="4" placeholder="권한이 적용될 source 페이지를 등록합니다.<?=PHP_EOL?>예) /kadm/menu/menu_manage.php"></textarea>
                    <small class="text-info">※ 페이지 內 코드가 우선시 되며, 페이지내 코드가 없을 경우 위 페이지들의 접근(조회) 권한을 적용합니다.</small>
                  </div>
                </div>
                <div class="mt-4 text-center">
                  <button type="button" class="btn btn-sm btn-warning px-5" id="btnMnuReset">Reset</button>
                  <button type="button" class="btn btn-sm btn-primary px-5" id="btnMnuSummit">Submit</button>
                  <button type="button" class="btn btn-sm btn-danger px-5" id="btnMnuDelete">Delete</button>
                </div>
              </form>
            </div>
          </div>
        </div>
<?php

include _ADM_INC_PATH_ ."/footer.html";
?>

<script>
var treedata = [];
jQuery('#trmenu_list').jstree({
  core : {
    data : treedata,
    check_callback : true,
    multiple : false,
  },
  dnd : {
    large_drag_target : true,
    large_drop_target : true,
    inside_pos: "last"
  },
  plugins : ['dnd','wholerow']
}).on("select_node.jstree",function(e,data){ //메뉴 선택시
  let _this = this;
  let jstree = jQuery(_this).jstree();
  let frm = jQuery(document.menuform);
  let node_id = data.selected[0];

  frm.find("input[name=parent_id]").val(node_id);
  frm.find("select[name=cate_mode]").val("M").trigger("change");
  frm.find('.menu_breadcrumb').html(menu_path(jstree));
}).on("ready.jstree",function(){
  tree_load();
}).on("refresh.jstree",function(){
  let _this = this;
  let jstree = jQuery(_this).jstree();
  if( jstree.outFunc ){
    jstree.outFunc(jstree);
  }
  jstree.open_node(jstree.get_selected()[0]);
}).on("move_node.jstree",function(e, data){
  let formdata = new FormData();
  formdata.append("cate_area", "<?=$cate_area?>");
  formdata.append("cate_id",   data.node.id);
  formdata.append("target_id", data.parent);
  formdata.append("pos_num",data.position);
  formdata.append("mode","sortMenu");
  ajax_form({
    url: "./menu.ajax.php",
    type: "POST",
    data: formdata,
    success: function(data){
      if( data.code ){
        side_menu_load();
        kuls_success("<?=cUtil\Mlang::getText("적용 되었습니다.")?>");
      }else{
        kuls_alert(data.mesg);
      }
    },
    error: function(request, status, error) {
      kuls_alert(error.message);
    }
  });
});

jQuery("#trmenu_top").on("click",function(){ //최상단 선택시
  tree_sel_first();
})
jQuery("#trmenu_top .jstree-icon").on("click",function(e){ //최상단 아이콘 클릭시
  e.stopPropagation();
  tree_all_toggle();
});
jQuery("#cate_mode").on("change",function(e){ //폼 작업 선택 변경시
  tree_frm_set("#trmenu_list", jQuery(this).val()=="N");
});
jQuery("#btnMnuReset").on("click",function(){
  tree_sel_first();
});
jQuery("#btnMnuSummit").on("click",function(){ //Submit 클릭시
  let formdata = new FormData(document.menuform);
  formdata.append("cate_area", "<?=$cate_area?>");
  formdata.append("mode", "putMenu");
  ajax_form({
    url: "./menu.ajax.php",
    type: "POST",
    data: formdata,
    success: function(data){
      if( data.code ){
        tree_load(function(){
          let jstree = jQuery('#trmenu_list').jstree();
          let frm = jQuery(document.menuform);
          if( formdata.get("cate_mode") == "M" ){
            jstree.outFunc = false;
            jstree.select_node(formdata.get("cate_id")); //수정된 ID로 선택
          }else{
            if( formdata.get("parent_id") ){
              jstree.select_node(formdata.get("parent_id")); //부모 ID로 선택
            }
            frm.get(0).reset();
          }
        });
        side_menu_load(); //관리자화면 사이드메뉴

        kuls_success("<?=cUtil\Mlang::getText("등록 되었습니다.")?>");
      }else{
        kuls_alert(data.mesg);
      }
    },
    error: function(request, status, error) {
      kuls_alert(error.message);
    }
  });
});
jQuery("#btnMnuDelete").on("click",function() { //삭제시
  kuls_confirm("<?=cUtil\Mlang::getText("메뉴 삭제")?>", "<?=cUtil\Mlang::getText("※ 해당 메뉴 / 하위 메뉴 모두 삭제 됩니다.<br/>삭제를 진행 하시겠습니까?")?>",function(){
    let formdata = new FormData(document.menuform);
    formdata.append("cate_area", "<?=$cate_area?>");
    formdata.append("mode", "delMenu");
    ajax_form({
      url: "./menu.ajax.php",
      type: "POST",
      data: formdata,
      success: function(data){
        if( data.code ){
          tree_load();
          side_menu_load(); //관리자화면 사이드메뉴
          tree_sel_first();
          kuls_success("<?=cUtil\Mlang::getText("삭제 되었습니다.")?>");
        }else{
          kuls_alert(data.mesg);
        }
      },
      error: function(request, status, error) {
        kuls_alert(error.message);
      }
    });
  });
});

const tree_load = function(func){
  ajax_json({
    url: "./menu.ajax.php",
    type: "POST",
    data: {
      cate_area: "<?=$cate_area?>",
      mode: "getMenuList"
    },
    success: function(data){
      if( data.code ){
        let jstree = jQuery('#trmenu_list').jstree();
        jstree.settings.core.data = data.data;
        if( func ){
          jstree.outFunc = func;
        }
        jstree.refresh();
      }
    },
    error: function(request, status, error) {
    }
  });
}

const tree_sel_first = function(){
  let jstree = jQuery('#trmenu_list').jstree();
  let frm = jQuery(document.menuform);

  jstree.deselect_all();
  frm.find("[name=parent_id]").val("");
  frm.find('.menu_breadcrumb').html("");

  tree_frm_set(jstree, true);
};

const tree_all_toggle = function(tgt){
  if( jQuery("#trmenu_list .jstree-open [aria-level=1]").length > 0 ){
    jQuery('#trmenu_list').jstree().close_all();
  }else{
    jQuery('#trmenu_list').jstree().open_all();
  }
};
const tree_frm_set = function(jstree, reset){
  if( typeof jstree == "string" ){
    jstree = jQuery(jstree).jstree();
  }
  let frm = jQuery(document.menuform);

  if(frm.find("[name=parent_id]").val()){
    frm.find("select[name=cate_mode] option[value=M]").prop("disabled",false);
  }else{
    frm.find("select[name=cate_mode] option[value=M]").prop("disabled",true);
  }

  if( reset ){
    frm.find("input[type!=hidden][type!=radio][type!=checkbox]")
    .add("textarea")
    .val("");

    frm.find("input[type=checkbox]")
    .add("input[type=radio]")
    .add("select")
    .data("defval","");

    frm.find("select[name=cate_mode]").val("N");
  }else{
    let snode = jstree.get_selected()[0]
    if( !snode && frm.find("[name=parent_id]").val() ){
      snode = frm.find("[name=parent_id]").val();
      jstree.get_node(snode).state.selected = true;
    }
    let selected_node = jstree.get_node(snode);
    Object.keys(selected_node.data).forEach( k => {
      frm.find("[type=text][name="+k+"]")
      .add("[type=hidden][name="+k+"]")
      .add("[type=password][name="+k+"]")
      .add("[type=date][name="+k+"]")
      .add("[type=datetime][name="+k+"]")
      .add("[type=number][name="+k+"]")
      .add("textarea[name="+k+"]")
      .val(selected_node.data[k]);

      frm.find("[type=radio][name="+k+"]")
      .add("[type=checkbox][name="+k+"]")
      .add("[type=checkbox][name^="+k+"\\[]")
      .add("select[name="+k+"]").data("defval",selected_node.data[k]);

      if( k == "cate_data" ){
        if( selected_node.data[k] ){
          document.querySelector(".btn_url").href=selected_node.data[k];
          document.querySelector(".btn_url").target='_blank';
        }else{
          document.querySelector(".btn_url").href="javascript:;";
          document.querySelector(".btn_url").target='';
        }
      }
    } );
  }
  formSetVal(frm);
};

const menu_path = function(jstree, node_id){
  let menu_path_str = "";
  let selcted_node = jstree.get_node(node_id||jstree.get_selected()[0]);
  if( selcted_node.parent && selcted_node.parent != "#" ){
    menu_path_str = menu_path(jstree, selcted_node.parent);
  }
  //return ((menu_path_str)?menu_path_str+" > "+selcted_node.text:selcted_node.text);
  return menu_path_str+" > "+selcted_node.text;
};
</script>
