<?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");
    //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 = [
    "SchID"=>["Name"=>"School","Loaded"=>"All","ID"=>0,"Prev"=>"","Next"=>"StudyID","DisableField"=>"","SilentMode"=>false],
    "StudyID"=>["Name"=>"Study","Loaded"=>"None","ID"=>0,"Prev"=>"SchID","Next"=>"FacGrpID","DisableField"=>"","SilentMode"=>true],
    "FacGrpID"=>["Name"=>"Faculty Group","Loaded"=>"None","ID"=>0,"Prev"=>"StudyID","Next"=>"FacID","DisableField"=>"","SilentMode"=>true],
    "FacID"=>["Name"=>"Faculty","Loaded"=>"None","ID"=>0,"Prev"=>"FacGrpID","Next"=>"DeptID","DisableField"=>"","SilentMode"=>true],
    "DeptID"=>["Name"=>"Department","Loaded"=>"None","ID"=>0,"Prev"=>"FacID","Next"=>"ProgID","DisableField"=>"","SilentMode"=>true],
    "ProgID"=>["Name"=>"Programme","Loaded"=>"None","ID"=>0,"Prev"=>"DeptID","Next"=>"ClassID","DisableField"=>"","SilentMode"=>true],
    "ClassID"=>["Name"=>"Class","Loaded"=>"None","ID"=>0,"Prev"=>"ProgID","Next"=>"","DisableField"=>"","SilentMode"=>true],
    "Details"=>["Current"=>"SchID"]
];
}

$StrucObj = [];
//get the school structure Control
$sctrucc = $dbo->SelectFirstRow("school_tb",'SchStrucContr');

    
    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
    }


$fields = [
    "SchID"=>[
        "-StrSchGrpID"=>"SCHOOL ID",
        "*StrSchGrpName"=>"SCHOOL NAME",
        "*StrSchGrpAddr"=>"ADDRESS",
        "*StrSchGrpCountry"=>"COUNTRY",
        "*StrSchGrpHeadUID"=>["HEAD STAFF","#select UserID,UserName from user_tb"],
        "*StrSchGrpHeadTitle"=>"JOB TITLE",
        "*StrSchGrpDescr"=>"DESCRIPTION"],
    "StudyID"=>[
        "-SchStuId"=>"STUDY ID",
        "*SchStuName"=>"STUDY NAME",
        "*SchStuHeadUID"=>["HEAD STAFF","#select UserID,UserName from user_tb"],
        "*SchStuHeadTitle"=>"JOB TITLE",
        "*SchStuDescr"=>"DESCRIPTION",
        "*SchStuAcceptLetter"=>array("PRINT ACCEPTANCE","YES|NO"),
        "*SchStuAcceptLetterID"=>["ACCEPTANCE DESIGN","#select ID,Title from report_tb where Marker='StudentRegSheet'"],
        "-SchStuSchoolType"=>"SchoolType",
        "-SchStuSchID"=>["SCHOOL","#select SchGrpID, SchGrpName from school_grp_tb"]],
    "FacGrpID"=>[
"-SchFacGrpID"=>"FACULTY GROUP ID",
"*SchFacGrpName"=>"FACULTY GROUP NAME",
"*SchFacGrpDescr"=>"DESCRIPTION",
    ],
    "FacID"=>[
        "-SchFacID"=>"FACULTY ID",
        "*SchFacName"=>"FACULTY NAME",
        "*SchFacHeadUID"=>["HEAD STAFF","#select UserID,UserName from user_tb"],
        "*SchFacHeadTitle"=>"JOB TITLE",
        "*SchFacAbbr"=>"ABBREVIATION",
        "*SchFacDescr"=>"DESCRIPTION",
"-SchFacGroup"=>array("FACULTY GROUP","#select FacGrpID, FacGrpName from facgroup_tb"),
"-SchFacStudy"=>array("STUDY","#select ID, Name from study_tb where SchoolType = (select Type from school_tb limit 1) AND StudySchID =".$allItems['SchID']['ID']."")
            ],
    "DeptID"=>[
        "-SchDeptID"=>"DEPARTMENT ID",
        "*SchDeptName"=>"DEPARTMENT NAME",
        "*SchDeptHeadUID"=>["HEAD STAFF","#select UserID,UserName from user_tb"],
        "*SchDeptHeadTitle"=>"JOB TITLE",
        "*SchDeptAbbr"=>"ABBREVIATION",
        "-SchDeptFac"=>["FACULTY","#select FacID,FacName from fac_tb where StudyID = ".$allItems['StudyID']['ID']." UNION select '#' as DeptID, 'OTHERS' as DeptName UNION select FacID,FacName from fac_tb where StudyID != ".$allItems['StudyID']['ID']],
        "*SchDeptDescr"=>"DESCRIPTION"
            ],
    "ProgID"=>[
        "-SchProgID"=>"PROGRAMME ID",
        "*SchProgName"=>"PROGRAMME NAME",
        "*SchProgDegree"=>"DEGREE",
        "*SchProgYear"=>"YEAR OF STUDY",
        "*SchProgHeadUID"=>["HEAD STAFF","#select UserID,UserName from user_tb"],
        "*SchProgHeadTitle"=>"JOB TITLE",
        "*SchProgAbbr"=>"ABBREVIATION",
        "*SchProgRegFormat"=>"REG.NO. FORMAT",
        "*SchProgRegStart"=>"REG.NO. START",
        "-SchProgDept"=>["DEPARTMENT","#select DeptID,DeptName from dept_tb where FacID=".$allItems['FacID']['ID']." UNION select '#' as DeptID, 'OTHERS' as DeptName UNION select DeptID,DeptName from dept_tb where FacID != ".$allItems['FacID']['ID']],
        "*SchProgDescr"=>"DESCRIPTION"
            ],
            "ClassID"=>[
                "-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']]
                    ]
    ];

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





Box("class=ep-animate-opacity, style=width:100%");
echo '<div style="width:100%;overflow:auto">';
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)";//School.Structure.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 != ""?"School.Structure.Load({$allItems[$prevkey]['ID']},'$prevkey','{$allItems[$prevkey]['Loaded']}')":"School.Structure.Load(0,'a','')";
                          
//if($prevkey != ""){
   // $backAction = "School.Structure.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 = "School.Structure.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 != ""?"School.Structure.Load({$allItems[$prevkey]['ID']},'$prevkey','{$allItems[$prevkey]['Loaded']}')":"School.Structure.Load(0,'a','')";
                                //if($prevkey != ""){
                                    $backAction = $act;
                               // }
                            }
                            //$class = ($curseen)?"dis-child":"dis-parent";
//$act = ($curseen)?$act:"School.Structure.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>':'';
                      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="true" 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="strucload" style="float:right;text-align:right;display:none"><span>Loading ...</span><span id="strucloadtitle"></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>';
                  /* echo '<div class="displaymapitem">
                  <a class="dis-current" href="javascript:void(0)"><span>School</span><span>All</span></a>
                  <i class="fa fa-angle-double-right altColor2"></i>
                  <a  class="dis-child" href="javascript:void(0)"><span>Study</span><span>None</span></a>
                  <i class="fa fa-angle-double-right altColor2"></i>
                  <a class="dis-child" href="javascript:void(0)"><span>Faculty Group</span><span>None</span></a>
                  <i class="fa fa-angle-double-right altColor2"></i>
                  <a class="dis-child" href="javascript:void(0)"><span>Faculty</span><span>None</span></a>
                  <i class="fa fa-angle-double-right altColor2"></i>
                  <a class="dis-child" href="javascript:void(0)"><span>Department</span><spa    n>None</span></a>
                  <i class="fa fa-angle-double-right altColor2"></i>
                  <a class="dis-child" href="javascript:void(0)"><span>Programme</span><span>None</span></a></div>'; */
              _TextBoxGroupItem();
                //$strctatus = 0;
                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;
                    } */
                  

              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=School.Structure.SetSilentMode");
              }
              
          _TextBoxGroup();
          echo '</div>';
//$disdet = ["SchID"=>0,"StudyID"=>0,"FacGrpID"=>0,"FacID"=>0,"DeptID"=>0,"ProgID"=>0,"Current"=>"SchID"];
Box('id=schstrucdatabx,style=display:none');
echo json_encode($allItems);
_Box();
if($CurKey != "ClassID"){
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
          /* "FacGrpID"=>"SELECT -1 as FacGrpID, 'ALL' as FacGrpName, 'All Faculties' as FacGrpDescr,'*chevron-right' as logo, 'Load Sub' as info , CONCAT('School.Structure.Load(',-1,',\'FacGrpID\',\'','ALL','\')') as Action UNION SELECT *,'*chevron-right' as logo, 'Load Sub' as info , CONCAT('School.Structure.Load(',FacGrpID,',\'FacGrpID\',\'',FacGrpName,'\')') as Action FROM facgroup_tb $lim" */
          $lim = $strctatus == 1?"LIMIT 1":"";
          $varb = $dbo->RunQuery("SET @t1 := 0");
          $query = [
            "SchID"=>"SELECT SchGrpID, SchGrpName,SchGrpAddr, SchGrpCountry, SchGrpHeadUserID, SchGrpHeadTitle, SchGrpDecr, '*chevron-right' as logo, 'Load Sub' as info , CONCAT('School.Structure.Load(',SchGrpID,',\'SchID\',\'',SchGrpName,'\')') as Action FROM school_grp_tb",

        "StudyID"=>"(SELECT ID, Name, StudyHeadUserID, StudyHeadTitle, StudyDescr, IF(AcceptLetter = 'TRUE',1,IF(AcceptLetter = '1',1,0)) as acceptL, AcceptLetterID, SchoolType, StudySchID, '*chevron-right' as logo, 'Load Sub' as info, IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable , CONCAT('School.Structure.Load(',ID,',\'StudyID\',\'',Name,'\',',$strctatus,',',@t1,')') as Action FROM study_tb WHERE SchoolType = (Select Type From school_tb) AND StudySchID = {$allItems['SchID']['ID']})UNION(SELECT '','','','','','','','',{$allItems['SchID']['ID']},'','','','') $lim",

            "FacGrpID"=>"SELECT *,'*chevron-right' as logo, 'Load Sub' as info , CONCAT('School.Structure.Load(',FacGrpID,',\'FacGrpID\',\'',FacGrpName,'\')') as Action FROM facgroup_tb $lim",

        "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('School.Structure.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']})UNION(SELECT '','','','','','',{$allItems['FacGrpID']['ID']},{$allItems['StudyID']['ID']},'','',IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable,'') $lim",

            "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('School.Structure.Load(',DeptID,',\'DeptID\',\'',DeptName,'\',',$strctatus,',',@t1,')') as Action FROM dept_tb WHERE FacID = {$allItems['FacID']['ID']})UNION(SELECT '','','','','',{$allItems['FacID']['ID']},'','','','','') $lim",

            "ProgID"=>"(SELECT ProgID, ProgName,Degree,YearOfStudy, ProgHeadUserID, ProgHeadTitle, Abbr,RegNoFormat,RegNumStart, DeptID, Descr,'*chevron-right' as logo, 'Load Sub' as info, IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable, CONCAT('School.Structure.Load(',ProgID,',\'ProgID\',\'',ProgName,'\',',$strctatus,',',@t1,')') as Action FROM programme_tb WHERE DeptID = {$allItems['DeptID']['ID']})UNION(SELECT '','','','','','','','','',{$allItems['DeptID']['ID']},'','','','','') $lim",

            "ClassID"=>"(SELECT ID, Name,Capacity,HeadID, HeadTitle, Descr, ProgID, IF((@t1 := @t1 + 1) > 1,IF($strctatus = 1,'true','false'),'false') as disable FROM studentclass_tb WHERE ProgID = {$allItems['ProgID']['ID']})UNION(SELECT '','','','','','',{$allItems['ProgID']['ID']},'') $lim"
        ];

        /* "-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('School.Structure.Load(',-1,',\'FacGrpID\',\'','ALL','\')') as Action UNION SELECT *,'*chevron-right' as logo, 'Load Sub' as info , CONCAT('School.Structure.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('School.Structure.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('School.Structure.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';
        }
          Box("style=width:100%;overflow:auto");
           SpreadSheet("rowselect=false,style=width:95%;margin:auto;margin-bottom:6px,id=schstrss,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=$rowsel,minrow=$numrow,rowfilter=true,case=none,filtertitle=FILTER ".$allItems[$CurKey]['Name'].",filterstyle=width:95%;margin:auto;margin-top:6px;text-transform:uppercase",$fields[$CurKey], $query[$CurKey]);
           _Box();
           //echo json_encode($allItems);
           //echo $query[$CurKey];
           _Box();

?>  