<?php
//  ------------------------------------------------------------------------ //
// 本模組由 ugm 製作
// 製作日期：2015-01-29
// $Id:$
// ------------------------------------------------------------------------- //

/*-----------引入檔案區--------------*/
include_once "../../../mainfile.php";
include_once "../function.php";
$xoopsOption['template_main'] = 'ugm_tools_adm_nav.html';
include_once "header.php";

#取得kind資料庫
$tbl="ugm_tools_nav";
#取得模組名稱
$DIRNAME=$xoopsModule->getVar('dirname');
#引入類別物件---------------------------------
include_once XOOPS_ROOT_PATH.'/modules/ugm_tools/ugmKind.php';
/*-----------執行動作判斷區----------*/
$op=empty($_REQUEST['op'])?"":$_REQUEST['op'];
$sn=empty($_REQUEST['sn'])?"":intval($_REQUEST['sn']);

# kind--------------------------------------------------
$kind=empty($_REQUEST['kind'])?"nav":$_REQUEST['kind'];
#stop_level
$stop_level=get_stop_level($kind,$kind_arr);
$ugmKind=new ugmKind($tbl,$kind,$stop_level);
#---------------------------------

switch($op){
  case "op_update_sort":     //更新排序
    echo op_update_sort();
  exit;

  case "op_save_drag":       //移動類別儲存
    echo op_save_drag();
  exit;
  //更新狀態
  case "op_update_enable":
    op_update_enable();
    redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_SUCCESS);
  exit;

  //更新外連狀態
  case "op_update_target":
    op_update_target();
    redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_SUCCESS);
  exit;

  //新增資料
  case "op_insert":
    op_insert($sn);
    redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_SUCCESS);
  exit;

  //新增資料
  case "op_all_insert":
    op_all_insert();
    redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_SUCCESS);
  exit;
  //輸入表格
  case "op_form":
    op_form($sn);
  break;

  //刪除資料
  case "op_delete":
    op_delete($sn);
    redirect_header($_SERVER['PHP_SELF']."?kind={$kind}",3,_BP_DEL_SUCCESS);
  break;

  //預設動作
  default:
  $op="op_list";
  op_list();
  break;
  /*---判斷動作請貼在上方---*/
}

/*-----------秀出結果區--------------*/
//$xoopsTpl->assign("isAdmin" , true);
$file_name=basename ($_SERVER['PHP_SELF']);
$moduele_admin = new ModuleAdmin();
$xoopsTpl->assign("Navigation",$moduele_admin->addNavigation($file_name));
$xoopsTpl->assign("op" , $op);
$xoopsTpl->assign("DIRNAME" , $DIRNAME);
$xoopsTpl->assign("action" ,$file_name );
include_once 'footer.php';
/*-----------功能函數區--------------*/
#取得stop_level
function get_stop_level($kind,$kind_arr){
  foreach($kind_arr as $key=>$value){
    if($kind==$key){
      return $value['stop_level'];
    }
  }
}

###############################################################################
#  編輯表單
###############################################################################
function op_form($sn=""){
  global $xoopsDB,$xoopsTpl,$ugmKind;
  //----------------------------------*/
  $_GET['ofsn']=!isset($_GET['ofsn'])?0:intval($_GET['ofsn']);
  //抓取預設值
  if(!empty($sn)){
    $DBV=$ugmKind->get_one_table_4_sn($sn);//get_ugm_module_tbl($sn,$ugmKind->get_tbl());//
  }else{
    $DBV=array();
  }
  //預設值設定
  //設定「kind_sn」欄位預設值
  $DBV['sn']=(!isset($DBV['sn']))?"":$DBV['sn'];

  //設定「kind_ofsn」欄位預設值
  $DBV['ofsn']=(!isset($DBV['ofsn']))?$_GET['ofsn']:$DBV['ofsn'];
  $DBV['ofsn_option']=$ugmKind->get_admin_form_ofsn_option($DBV['ofsn']);

  //設定「title」欄位預設值
  $DBV['title']=(!isset($DBV['title']))?"":$DBV['title'];

  //設定「enable」欄位預設值
  $DBV['enable']=(!isset($DBV['enable']))?"1":$DBV['enable'];

  //kind
  $DBV['kind']=(!isset($DBV['kind']))?$ugmKind->get_kind():$DBV['kind'];

  //設定「target」欄位預設值
  $DBV['target']=(!isset($DBV['target']))?"0":$DBV['target'];

  //設定「url」欄位預設值
  $DBV['url']=(!isset($DBV['url']))?"":$DBV['url'];

  $DBV['op']="op_insert";
  //----- 驗證碼 -----------------*/
  if(!file_exists(XOOPS_ROOT_PATH."/modules/tadtools/formValidator.php")){
   redirect_header("index.php",3, _TAD_NEED_TADTOOLS);
  }
  include_once XOOPS_ROOT_PATH."/modules/tadtools/formValidator.php";
  $formValidator= new formValidator("#myForm",true);
  $javascript_code=$formValidator->render();
  //-------------------------------*/
  $xoopsTpl->assign('javascript_code',$javascript_code);
  $xoopsTpl->assign('DBV',$DBV);
}


###############################################################################
#  列出所有類別的資料
###############################################################################
function op_list(){
  global $xoopsTpl,$kind_arr,$ugmKind;
  # ----得到外鍵選單之選項 ----------------------------
  $kind_option="";
  foreach($kind_arr as $key=>$value){
    $selected="";
    if($ugmKind->get_kind()==$key){
      $selected=" selected";
    }
    $kind_option.="<option value='{$key}'{$selected}>{$value['title']}</option>";
  }
  $kind_form="
      <select name='kind' id='kind' onchange=\"location.href='?kind='+this.value\">
        {$kind_option}
      </select>
  ";
  #----------------------------------------------------
  $xoopsTpl->assign('kind_form',$kind_form);
  $xoopsTpl->assign('kind',$ugmKind->get_kind());
  # ----得到陣列 ----------------------------
  $ofsn=0;
  $level=1;
  $list=$ugmKind->get_admin_list_body($ofsn,$level);
  //print_r($list);die();

  #-----驗證碼---------------------------------------------------------
  if(!file_exists(XOOPS_ROOT_PATH."/modules/tadtools/formValidator.php")){
   redirect_header("index.php",3, _TAD_NEED_TADTOOLS);
  }
  include_once XOOPS_ROOT_PATH."/modules/tadtools/formValidator.php";
  $formValidator= new formValidator("#myForm",true);
  $formValidator_code=$formValidator->render();
  #-----驗證碼---------------------------------------------------------
  $xoopsTpl->assign('js_code',$formValidator_code);
  $xoopsTpl->assign('list',$list);
}

###########################################################
#  新增、編輯資料
###########################################################
function op_insert(){
  global $xoopsDB,$ugmKind;
  //---- 過濾資料 -----------------------------------------*/
  $myts =& MyTextSanitizer::getInstance();
  #類別名稱
  $_POST['title']=$myts->addSlashes($_POST['title']);
  if(empty($_POST['title']))return false;
  #網址
  $_POST['url']=$myts->addSlashes($_POST['url']);
  #類別
  $_POST['kind']=$myts->addSlashes($_POST['kind']);
  #狀態
  $_POST['enable']=intval($_POST['enable']);
  #連結狀態
  $_POST['target']=intval($_POST['target']);
  #sn
  $_POST['sn']    =intval($_POST['sn']);
  #ofsn
  $_POST['ofsn']  =intval($_POST['ofsn']);
  //-------------------------------------------------------*/
  if($_POST['sn']){
    #編輯
    #--------檢查---------------------------
    $DBV=$ugmKind->get_one_table_4_sn($_POST['sn']);
    if($_POST['ofsn']!=$DBV['ofsn']){
      #類別有變動
      if($_POST['sn']==$_POST['ofsn']){
        redirect_header($_SERVER['PHP_SELF'],3,_MA_TREETABLE_MOVE_ERROR1);
      }elseif(($ugmKind->chk_kind_level_down($_POST['sn'])+$ugmKind->chk_kind_level($_POST['ofsn'])) > $ugmKind->get_stop_level()){
        redirect_header($_SERVER['PHP_SELF'],3,_MD_UGMMOUDEL_KIND_LEVEL_ERROR);
      }
    }
    #--------檢查結束---------------------------
    #
    $sql = "update ".$xoopsDB->prefix($ugmKind->get_tbl())." set
      `ofsn`   = '{$_POST['ofsn']}' ,
      `title`  = '{$_POST['title']}' ,
      `enable` = '{$_POST['enable']}',
      `target` = '{$_POST['target']}',
      `url` = '{$_POST['url']}'
      where sn='{$_POST['sn']}'";
    $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  }else{
    #---------新增------------------------
    #---------取得排序--------------------
    $sql="select max(sort)as max_sort
          from ".$xoopsDB->prefix($ugmKind->get_tbl())."
          where ofsn='{$_POST['ofsn']}' and kind='{$_POST['kind']}'";
    $sort=get_ugm_module_sql($sql);
    $sort['max_sort']++;
    #---------寫入-------------------------
    $sql = "insert into ".$xoopsDB->prefix($ugmKind->get_tbl())."
    (`ofsn` ,`title` , `enable` , `sort`,`kind`,`target`,`url`)
    values('{$_POST['ofsn']}' , '{$_POST['title']}' ,'{$_POST['enable']}' , '{$sort['max_sort']}' , '{$_POST['kind']}', '{$_POST['target']}', '{$_POST['url']}')";
    $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
    //取得最後新增資料的流水編號
    $_POST['sn'] = $xoopsDB->getInsertId();
  }
  return $_POST['sn'];
}

###############################################################################
#  更新啟用
###############################################################################
function op_update_enable(){
  global $xoopsDB,$ugmKind;
  #權限
  /***************************** 過瀘資料 *************************/
  $enable=intval($_GET['enable']);
  $sn=intval($_GET['sn']);
  /****************************************************************/
  //更新
  $sql = "update ".$xoopsDB->prefix($ugmKind->get_tbl())." set  `enable` = '{$enable}' where `sn`='{$sn}'";
  $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  return ;
}
###############################################################################
#  更新外連
###############################################################################
function op_update_target(){
  global $xoopsDB,$ugmKind;
  #權限
  /***************************** 過瀘資料 *************************/
  $target=intval($_GET['target']);
  $sn=intval($_GET['sn']);
  /****************************************************************/
  //更新
  $sql = "update ".$xoopsDB->prefix($ugmKind->get_tbl())." set  `target` = '{$target}' where `sn`='{$sn}'";
  $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  return ;
}
###############################################################################
#  移動類別儲存
###############################################################################
function op_save_drag(){
  global $xoopsDB,$ugmKind;
  //$ofsn=intval(str_replace("tr_","",$_POST['ofsn']));
  //$sn=intval(str_replace("tr_","",$_POST['sn']));
  $ofsn=intval($_POST['ofsn']);//目的
  $sn=intval($_POST['sn']);//來源
  if(!$sn){
    #根目錄不可移動
    die(_MD_UGMMOUDEL_KIND_ROOT_ERROR."(".date("Y-m-d H:i:s").")"._BP_F5);
  }elseif($ofsn==$sn){
    #自己移至自己
    die(_MA_TREETABLE_MOVE_ERROR1."(".date("Y-m-d H:i:s").")"._BP_F5);
  }elseif($ugmKind->chk_kind_level($ofsn) + $ugmKind->chk_kind_level_down($sn) > $ugmKind->get_stop_level()){
    #自己往底層移動或自己底下層數+目的所在層數 > 類別層數
    die(_MD_UGMMOUDEL_KIND_LEVEL_ERROR."(".date("Y-m-d H:i:s").")"._BP_F5);
  }

  $sql="update ".$xoopsDB->prefix($ugmKind->get_tbl())."
        set `ofsn`='{$ofsn}' where `sn`='{$sn}'";
  $xoopsDB->queryF($sql) or die("Reset Fail! (".date("Y-m-d H:i:s").")");

  return "Reset OK! (".date("Y-m-d H:i:s").")"._BP_F5;
}

###########################################################
#  批次編輯資料
###########################################################
function op_all_insert(){
  global $xoopsDB,$ugmKind;
  //---- 過濾資料 -----------------------------------------*/
  $myts =& MyTextSanitizer::getInstance();
  foreach($_POST['title'] as $sn=>$title){
    $title=$myts->addSlashes($title);
    $sn=intval($sn);#編輯
    $url=$myts->addSlashes($_POST['url'][$sn]);
    $sql = "update ".$xoopsDB->prefix($ugmKind->get_tbl())." set
           `title` = '{$title}',
           `url` = '{$url}'
           where sn='{$sn}'";
    $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  }
}
###############################################################################
#  刪除資料
###############################################################################
function op_delete($sn=""){
  global $xoopsDB,$ugmKind;
  if(empty($sn))redirect_header($_SERVER['PHP_SELF'],3, _BP_DEL_ERROR);
  #檢查是否有子類別
  if ($ugmKind->check_sub_kind($sn)) redirect_header($_SERVER['PHP_SELF'],3, _MD_UGMMOUDEL_KIND_HAVE_SUB_NOT_DEL);
  $sql = "delete from ".$xoopsDB->prefix($ugmKind->get_tbl())."
          where sn='{$sn}'";//die($sql);
  $xoopsDB->queryF($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
}
###############################################################################
#  自動更新排序
###############################################################################
function op_update_sort(){
  global $xoopsDB,$ugmKind;
  $sort=1;
  foreach ($_POST['tr'] as $sn) {
    if(!$sn)continue;
    $sql="update ".$xoopsDB->prefix($ugmKind->get_tbl())." set `sort`='{$sort}' where `sn`='{$sn}'";
    $xoopsDB->queryF($sql) or die("Save Sort Fail! (".date("Y-m-d H:i:s").")");
    $sort++;
  }
  return "Save Sort OK! (".date("Y-m-d H:i:s").")"._BP_F5;
}
?>