<?php
extract($_POST);
$Key = !isset($Key)?"":$Key;
$Value = !isset($Value)?0:$Value;
$Name = !isset($Name)?"All":$Name;
if($Key != ""){
    require_once("../../../../general/TaquaLB/Elements/Elements.php");
    $configdir = "../../../../../../".$_POST['SubDir'];
    require_once("../../../../general/config.php");
   // $schdet = $dbo->SelectFirstRow("school_tb","SemLabel");
    
    //require("../../../../general/getinfo.php");
//echo $Value;
}
/* if(!isset($Key) || !isset($Value)){
    exit('#');
} */



if(isset($Data)){
    
    $allItems = json_decode($Data,true);
    //print_r()
    
}else{
//all item array
$allItems = [
    "ApplyGID"=>["Name"=>"Application","Loaded"=>"All","ID"=>0,"Prev"=>"","Next"=>"ApplyID","DisableField"=>"","SilentMode"=>false],
    "ApplyID"=>["Name"=>"Modules","Loaded"=>"None","ID"=>0,"Prev"=>"ApplyGID","Next"=>"PageID","DisableField"=>"","SilentMode"=>true]
];
}
/*  "PageID"=>["Name"=>"Pages","Loaded"=>"None","ID"=>0,"Prev"=>"ApplyID","Next"=>"","DisableField"=>"","SilentMode"=>true] */
$StrucObj = [];
//get the school structure Control
$sctrucc = $dbo->SelectFirstRow("school_tb",'SchStrucContr,SemLabel');
$semLabel = $sctrucc["SemLabel"];
    
    if(is_array($sctrucc) && !is_null($sctrucc['SchStrucContr'])){
      $StrucObj = json_decode($sctrucc['SchStrucContr'],true);
      //if($StrucObj[]) //Tring to replace the default name with the database set name if it exist
    }

/* ,
    "PageID"=>[
"-SchFacGrpID"=>"FACULTY GROUP ID",
"*SchFacGrpName"=>"FACULTY GROUP NAME",
"*SchFacGrpDescr"=>"DESCRIPTION",
    ] */
  /*   $disable = [
        "ApplyGID"=>"ApplyGLogo;ApplyGColor;ApplyGScope"
    ] */

        
if(isset($allItems[$Key])){
    //set the sent item details
$allItems[$Key]['ID'] = $Value;
$allItems[$Key]['Loaded'] = $Name;
}else{
    $Key = "";
}





Box("class=ep-animate-opacity");
TextBoxGroup();
              TextBoxGroupItem();
                  $cnt = 0; $curseen = false; $Nxt = $Key == ""?true:false;
$CurKey = "";
$markup = '';
$strctatus = 0;
                  echo '<div class="displaymapitem">';
                  $prevkey = ''; $backAction = 'void(0)';
                  foreach ($allItems as $rkey => &$det) {
                      $iscurrent = 'false';
                      if($rkey == "Details")continue;
$act = "void(0)";//Portal.Menus.Load(1,'FacID','FacName')
//check if database name exist
if(isset($StrucObj[$rkey]) && isset($StrucObj[$rkey]["Name"]) && trim($StrucObj[$rkey]["Name"]) != ""){
    $det['Name'] = $StrucObj[$rkey]["Name"];
}
//$det['Current'] = false;
                      $cnt++;
                      if($rkey == $Key){ //if the clicked item, mening the next is to be displaed
                        $Nxt = true;
                        //set indicator for the next item as the current
                        $act = $prevkey != ""?"Portal.Menus.Load({$allItems[$prevkey]['ID']},'$prevkey','{$allItems[$prevkey]['Loaded']}')":"Portal.Menus.Load(0,'a','')";
                          
//if($prevkey != ""){
   // $backAction = "Portal.Menus.Load({$allItems[$prevkey]['ID']},'$prevkey','{$allItems[$prevkey]['Loaded']}')";
    $backAction = $act;

//}
                      }else{
                        if($Nxt){ //if this is the nxt (will be the current)
                            $class = "dis-current";$curseen = true;
                            $det['Loaded'] = 'All'; 
                            $allItems['Details']['Current'] = $rkey; 
                            $act = "Portal.Menus.Refresh()";
                            $iscurrent = 'true';
$Nxt = false;$CurKey = $rkey;

//update the silent mode if set

/* if($CurKey != "SchID" && $CurKey != "FacGrpID"){
    
    
      if(isset($StrucObj[$CurKey]['SilentMode']) && $StrucObj[$CurKey]['SilentMode'] == true)$strctatus=1;
   // }
    $SetSilentMode = (int)$SetSilentMode;
    if($SetSilentMode >= 0 &&  $SetSilentMode != $strctatus){ //from silent mode setting and changes made
        //update silent mode
        if(!isset($StrucObj[$CurKey])){
            $StrucObj[$CurKey] = [];
        }
        $StrucObj[$CurKey]["SilentMode"] = (int)$SetSilentMode == 1?true:false;
        $upd = $dbo->Update("school_tb",["SchStrucContr"=>json_encode($StrucObj)]);
        if(is_array($upd))$strctatus = $SetSilentMode;
    }
} */

                        }else{
                            if($curseen){
                                $class = "dis-child";
                                $allItems[$rkey]['Loaded'] = "None";
                                $det['Loaded'] = 'None';
                            }else{
                                $class = "dis-parent";
                                $act = $prevkey != ""?"Portal.Menus.Load({$allItems[$prevkey]['ID']},'$prevkey','{$allItems[$prevkey]['Loaded']}')":"Portal.Menus.Load(0,'a','')";
                                //if($prevkey != ""){
                                    $backAction = $act;
                               // }
                            }
                            //$class = ($curseen)?"dis-child":"dis-parent";
//$act = ($curseen)?$act:"Portal.Menus.Load(1,'FacID','FacName')";//$allItems[$Key]['ID']
                        }
                            
                      } 
                      //$silmodeind = (isset($StrucObj[$rkey]['SilentMode']) && $StrucObj[$rkey]['SilentMode'] == true)?'&nbsp;<i class="fa fa-eye-slash altColor" style="margin:0px;vertical-align:middle"></i>':'';
                      $silmodeind = "";
                      if($iscurrent == 'false'){
                         
                        $markup .= '<a class="'.$class.'" href="javascript:'.$act.'"><span>'.$det['Name'].'</span><span><b style="vertical-align:middle">'.$det['Loaded'].'</b>'.$silmodeind.'</span></a>';

                      }else{
                        $markup .= '<div class="'.$class.' iscurrent" ><span contentEditable="false" id="currenStrucName">'.$det['Name'].'</span><span><b style="vertical-align:middle">'.$det['Loaded'].'</b>'.$silmodeind.'</span></div>';
                      }
                      
                    if($cnt < count($allItems) - 1){
                        $markup .=  '<i class="fa fa-angle-double-right altColor2"></i>';
                    }
                    $prevkey = $rkey;
                  }
                  $bkclass = $backAction == 'void(0)'?'dis-child':''; //if no action fade it
                  //Include the loading markup
                  $markup .= '<a class="dis-current ep-animate-opacity" href="javascript:'.$act.'" id="menusload" style="float:right;text-align:right;display:none"><span>Loading ...</span><span id="menusloadtitle"></span></a><div style="clear:both"></div>';
                echo '<a href="javascript:'.$backAction.'" class="ep-hover-scale '.$bkclass.'" ><i class="fa fa-chevron-left altColor2 fa-fw"></i></a>';
                  echo $markup;
                  echo '</div>';
                  
              _TextBoxGroupItem();
                //$strctatus = 0;
               /*  if($CurKey != "SchID" && $CurKey != "FacGrpID"){
                    
                  
                  

              Switcher("id=schstrcsilentmode,state=$strctatus,text=Silent Mode,style=width:100%;font-size:1.1em,info=Structure will be hidden and the first record will be set Automatically,ontext=yes,offtext=no,align=left,onchange=Portal.Menus.SetSilentMode");
              } */
              
          _TextBoxGroup();
//$disdet = ["SchID"=>0,"StudyID"=>0,"FacGrpID"=>0,"FacID"=>0,"DeptID"=>0,"ProgID"=>0,"Current"=>"SchID"];
Box('id=pmenudatabx,style=display:none');
echo json_encode($allItems);
_Box();
if($CurKey != "ApplyID"){
Note('style=width:calc(95% - 10px);margin:auto;margin-top:6px;margin-bottom:6px');
echo 'Use the <i class="fa fa-chevron-right altColor2"></i> Arrow button to load the Sub Structure of each display Structure Item';
/* if($CurKey == "FacGrpID"){
    echo '<br /> '.$allItems["FacGrpID"]["Name"].' is not related to '.$allItems["StudyID"]["Name"].', it is technically for grouping '.$allItems["FacID"]["Name"];
} */
_Note();
}
          //$sesheadersu = 
          // Box("id=coverbox,style=width:inherit;height:inherit;background-color:red;position:absolute;z-index:1");_Box();
          //set counter mysql global variable
          $lim = $strctatus == 1?"LIMIT 1":"";
          $varb = $dbo->RunQuery("SET @t1 := 0");
          /* [
        "-ApplyID"=>"APPLY ID",
        "*ApplyName"=>"NAME",
        "*ApplyDescr"=>"DESCRIPTION",
        "-ApplyGrpID"=>"GROUPID",
        "*ApplyLogo"=>"LOGO",
        "*ApplyColor"=>"COLOR",
        "*ApplyDir"=>"DIRECTORY",
        "*ApplyGData"=>"GLOBAL DATA",
        "*ApplyPages"=>"PAGES",
        "*ApplyEnable"=>array("ENABLE","YES|NO"),
        "*ApplyStatus"=>array("STATUS","OPENED=OPENED&CLOSED=CLOSED")]
Name
Descr
GroupID 
Logo
Enable
Status
Color
Placeholder
Dir
GlobalData
Pages

    ]; */
          $query = [
            "ApplyGID"=>"SELECT ID, `Name`,Descr, Logo, Color, Scope, `Enable`, '*chevron-right' as logo, 'Load Sub' as info , CONCAT('Portal.Menus.Load(',ID,',\'ApplyGID\',\'',Name,'\')') as Action FROM new_apply_group_tb ORDER BY MenuOrder",

        "ApplyID"=>"SELECT ID, Name, Descr, GroupID, Logo,Color,Dir,GlobalData,Pages, Enable, Status, PayID, PayBases FROM new_apply_tb WHERE GroupID = {$allItems['ApplyGID']['ID']} ORDER BY MenuOrder"
        ];

        /* "-SchClassID"=>"Class ID",
                "*SchClassName"=>"CLASS NAME",
                "*SchClassCapacity"=>"CAPACITY",
                "*SchClassHeadUID"=>["HEAD STAFF","#select UserID,UserName from user_tb"],
                "*SchClassHeadTitle"=>"JOB TITLE",
                "*SchClassDescr"=>"DESCRIPTION",
                "-SchClassProg"=>["PROGRAMME","#select ProgID,ProgName from programme_tb where DeptID=".$allItems['DeptID']['ID']." UNION select '#' as ProgID, 'OTHERS' as ProgName UNION select ProgID,ProgName from programme_tb where DeptID != ".$allItems['DeptID']['ID']] */

       /*  $defaults = [
            "SchID"=>[],

        "StudyID"=>[["ID, Name, StudyHeadUserID, StudyHeadTitle, StudyDescr, IF(AcceptLetter = 'TRUE',1,IF(AcceptLetter = '1',1,0)) as acceptL, AcceptLetterID, SchoolType, StudySchID"]],

            "FacGrpID"=>"SELECT -1 as FacGrpID, 'ALL' as FacGrpName, 'All Faculties' as FacGrpDescr,'*chevron-right' as logo, 'Load Sub' as info , CONCAT('Portal.Menus.Load(',-1,',\'FacGrpID\',\'','ALL','\')') as Action UNION SELECT *,'*chevron-right' as logo, 'Load Sub' as info , CONCAT('Portal.Menus.Load(',FacGrpID,',\'FacGrpID\',\'',FacGrpName,'\')') as Action FROM facgroup_tb",

        "FacID"=>"SELECT FacID, FacName, FacHeadUserID, FacHeadTitle, Abbr, Descr,GroupID,StudyID, '*chevron-right' as logo, 'Load Sub' as info, IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable , CONCAT('Portal.Menus.Load(',FacID,',\'FacID\',\'',FacName,'\',',$strctatus,',',@t1,')') as Action FROM fac_tb WHERE (GroupID = {$allItems['FacGrpID']['ID']} OR -1 = {$allItems['FacGrpID']['ID']}) AND StudyID = {$allItems['StudyID']['ID']}",

            "DeptID"=>"SELECT DeptID, DeptName, DeptHeadUserID, DeptHeadTitle, Abbr,FacID,Descr,'*chevron-right' as logo, 'Load Sub' as info, IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable , CONCAT('Portal.Menus.Load(',DeptID,',\'DeptID\',\'',DeptName,'\',',$strctatus,',',@t1,')') as Action FROM dept_tb WHERE FacID = {$allItems['FacID']['ID']}",

            "ProgID"=>"SELECT ProgID, ProgName,Degree,YearOfStudy, ProgHeadUserID, ProgHeadTitle, Abbr, DeptID, Descr, IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable FROM programme_tb WHERE DeptID = {$allItems['DeptID']['ID']}"
        ];
 */
        $numrow='-1';
        $rowsel = 'true';
        if($strctatus == 1){
            $numrow='1';
            $rowsel = 'false';
        }

        $applypaytypesq = "UNION(select ID as PayID, ItemName as PayName from item_tb where studType != 'w')";
//exit($Key);
    if($CurKey == "ApplyID"){
        //get the group details
        $appgrpdet = $dbo->SelectFirstRow("new_apply_group_tb","Scope","ID=".$allItems['ApplyGID']['ID']);
        if(is_array($appgrpdet) && $appgrpdet['Scope'] == "LOGIN"){
            $applypaytypesq = "";
        }else{
            
        }
    }


$fields = [
    "ApplyGID"=>[
        "-ApplyGID"=>"GROUPID",
        "*ApplyGName"=>"MENU NAME",
        "*ApplyGDescr"=>"DESCRIPTION",
        "*ApplyGLogo"=>"LOGO",
        "*ApplyGColor"=>"COLOR THEME",
        "*ApplyGScope"=>array("SCOPE","ALL=ALL&LOGIN=LOGIN&MAIN=MAIN"),
        "*ApplyGStatus"=>array("ENABLE","YES|NO")],
    "ApplyID"=>[
        "-ApplyID"=>"APPLY ID",
        "*ApplyName"=>"NAME",
        "*ApplyDescr"=>"DESCRIPTION",
        "-ApplyGrpID"=>"GROUPID",
        "*ApplyLogo"=>"LOGO",
        "*ApplyColor"=>"COLOR",
        "*ApplyDir"=>"FOLDER",
        "*ApplyGData"=>"GLOBAL DATA",
        "*ApplyPages"=>"PAGES",
        "*ApplyEnable"=>array("ENABLE","YES|NO"),
        "*ApplyStatus"=>array("STATUS","OPENED=OPENED&CLOSED=CLOSED"),
        "*ApplyPayID"=>array("PAYMENT","#(select 0 as PayID, 'NONE' as PayName)".$applypaytypesq),
        "*ApplyPayBases"=>array("PAY BASES","1=".strtoupper($semLabel)."&2=LEVEL&3=PROGRAMME")
        ]
    ];
        //disable row select
        // $rowsel = 'false';
        // $numrow = '-1';
        $cdisable="";
        if(isset($allItems[$CurKey]['DisableField']) && trim($allItems[$CurKey]['DisableField']) != "")$cdisable=",disable=".$allItems[$CurKey]['DisableField'];
        Box("style=width:100%;overflow:auto");
           SpreadSheet("rowselect=false,style=width:95%;margin:auto;margin-bottom:6px,id=pmenustrss,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=$rowsel,minrow=$numrow,rowfilter=true,case=none,moverow=true,filtertitle=FILTER".$allItems[$CurKey]['Name'].",filterstyle=width:95%;margin:auto;margin-top:6px;text-transform:uppercase$cdisable",$fields[$CurKey], $query[$CurKey]);
           _Box();
           //echo json_encode($allItems);
           //echo $query[$CurKey];
           _Box();

?>  