<?php
  require_once("../../../../general/TaquaLB/Elements/Elements.php");
  $configdir = "../../../../../../".$_POST['SubDir'];
  require_once("../../../../general/config.php");
 $sch = $dbo->SelectFirstRow("school_tb","SchStartSem,SchStartSes,SemLabel","1=1 LIMIT 1");
  //require("../../../../general/getinfo.php");
//require("../../../../epconfig/GenScript/PHP/getinfo.php");
//AllowUser("ssettings");



//check required fields
/* schsetname= &
schsetabbr= &
schsettype=1&
schsetdescr= &
schsetshortaddr= &
schsetlongaddr= &
schsetemail= &
schsetphone= &
loadimg=&camimg=&clearimg=&
schsetloadlvl=1&
schsetextrapre= 
schsetlogo_image_file=%3F
*/
//exit(json_encode($_FILES['schsetlogo_image_file']));
$dbarr = [];
foreach(['schsetname'=>"Name",'schsetabbr'=>"Abbr",'schsetshortaddr'=>"ShortAddr"] as $field=>$DB){
    if(!isset($_POST[$field]) || trim($_POST[$field]) == ""){
        exit("#INVALID ENTERING");
    }else{
        $dbarr[$DB] = $dbo->SqlSafe($_POST[$field]);
    }
}

//set defaults
$dbarr['Type'] = !isset($_POST['schsettype']) || (int)$_POST['schsettype'] < 1?1:$_POST['schsettype'];
$dbarr['LongAddr'] = !isset($_POST['schsetlongaddr'])?"":$_POST['schsetlongaddr'];
$dbarr['description'] = !isset($_POST['schsetdescr'])?"":$_POST['schsetdescr'];
$dbarr['email'] = !isset($_POST['schsetemail'])?"":$_POST['schsetemail'];
$dbarr['Phone'] = !isset($_POST['schsetphone'])?"":$_POST['schsetphone'];
$dbarr['LevelLoad'] = !isset($_POST['schsetloadlvl'])?"MANUAL":(int)$_POST['schsetloadlvl'] == 1?"AUTO":"MANUAL";
$dbarr['ExtraYearPrefix'] = !isset($_POST['schsetextrapre']) || trim($_POST['schsetextrapre']) ==""?"Spillover":$_POST['schsetextrapre'];
$dbarr['MaxExtraYear'] = !isset($_POST['maxextratb']) || trim($_POST['maxextratb']) ==""?3:$_POST['maxextratb'];
$dbarr['AutoRegNo'] = !isset($_POST['schsetautoreg'])?"FALSE":(int)$_POST['schsetautoreg'] == 1?"TRUE":"FALSE";
$dbarr['RegNoFormat'] = !isset($_POST['schautoregnoformat']) || trim($_POST['schautoregnoformat']) ==""?"?AUTONUM?":$_POST['schautoregnoformat'];
$dbarr['RegNumStart'] = !isset($_POST['schautoregnostart']) || trim($_POST['schautoregnostart']) ==""?1:$_POST['schautoregnostart'];
$dbarr['AutoRegNoScope'] = !isset($_POST['schautoregnoscope']) || trim($_POST['schautoregnoscope']) == ""?"BATCHPROG":$_POST['schautoregnoscope'];
$dbarr['AutoRegNoSet'] = !isset($_POST['schautoregnostud']) || trim($_POST['schautoregnostud']) == ""?"FRESH":$_POST['schautoregnostud'];//
$dbarr['AutoRegNoTrigger'] = !isset($_POST['schautoregnotrigger']) || trim($_POST['schautoregnotrigger']) == ""?"COURSE":$_POST['schautoregnotrigger'];
$dbarr['SemLabel'] = !isset($_POST['schsemlabel']) || trim($_POST['schsemlabel']) == ""?"Semester":$_POST['schsemlabel'];

//New school Study IDs
$newStudyIDs = [];
$newstuds = $dbo->Select("study_tb","ID","SchoolType =". $dbarr['Type']);
            if(is_array($newstuds) && $newstuds[1] > 0){ //if current have studies
             
              while($nstudyID = $newstuds[0]->fetch_assoc()){
                $newStudyIDs[] =  $nstudyID["ID"];
              }

            }

if(count($newStudyIDs) < 1){
    exit("#Setup Error: Studies not assign to the Selected School Type.<br />Assign Studies to the School Type in Application Settings Modules");
}

$ex = $dbo->SelectFirstRow("school_tb","");
//Auto Migrate
$automigrate = (int)$_POST['schsetmigrate'];
$migratefrom = 0;
if($automigrate == 1){
    //check if migrate nessasary. i.e school type changed
    //$schdet = $dbo->SelectFirstRow("school_tb");
    if(is_array($ex)){
        if((int)$ex['Type'] != (int)$dbarr['Type']){
            $migratefrom = (int)$ex['Type'];
        }
    }
}


//exit("# ".$migratefrom);


$dbo->Bigin();
//check if already exist

if(is_array($ex)){ //if exist - Perform Update
 $ID = $ex["ID"];
 $imgup = true;
 //check if image sent
 if(isset($_FILES['schsetlogo_image_file'])){
       
    $name = $_FILES['schsetlogo_image_file']['name'];
    $namearr = explode(".",$name);
    $ext = $namearr[count($namearr) - 1];
    $dbarr['logo'] = "UserImages/School/logo.".$ext;

 }
 $updt = $dbo->Update("school_tb",$dbarr,"ID=".$ID);

 if(is_array($updt)){
    if(isset($dbarr['logo'])){
        if(Upload('schsetlogo_image_file',$configdir."Files/".$dbarr['logo'])){
            //$dbarr['logo'] = $db;
            //remove the prevous if changed
            if(trim($dbarr['logo']) != trim($ex['logo'])){
                unlink($configdir."Files/".$ex['logo']);
            }
        
    }else{//if upload failed
        $dbo->Rollback();
        exit("#School Logo Upload Failed");
    }
        ///
    }
    
    if(isset($_POST['sess']) && trim($_POST['sess']) !=""){
        
       $grdsh = SheetDatabind($_POST['sess'],"session_tb",[1=>"SesID","SesName","Abbr","Enable"],[2]);
       $semsheetarr = $dbo->DataArray($_POST['sems']);
       if(!isset($semsheetarr['MaxDataRow']))exit("Invalid {$ex['SemLabel']} Parameter");
       $Numstr = "";
       $cnt = 1;
       for($smm=1;$smm<=(int)$semsheetarr['MaxDataRow'];$smm++){
        if($semsheetarr[$smm.'_deleted'] == "true"){
            $Numstr .= "&".$smm."_5=0";
            continue;
        }
        $Numstr .= "&".$smm."_5=".$cnt;
        $cnt++;
       }
      // exit($_POST['sems'].$Numstr);
       $semsh = SheetDatabind($_POST['sems'].$Numstr,"semester_tb",[1=>"ID","Sem","Descr","Enable","Num"],[2]);
      // exit("aaa");
    if ($grdsh !== true || $semsh !== true){
        $dbo->Rollback();
        exit("#School Setting Update Failed");
    }else{
        //update study ids if auto migrate is set
        if($migratefrom > 0){
            //get all study of the current school
            $currentstuds = $dbo->Select("study_tb","ID","SchoolType =". $migratefrom);
            if(is_array($currentstuds) && $currentstuds[1] > 0){ //if current have studies
              $currStudyIDs = [];
              while($curstudyID = $currentstuds[0]->fetch_assoc()){
                $currStudyIDs[] =  $curstudyID["ID"];
              }
              if(count($currStudyIDs) > 0){
                  //loop tru the new study ids
                  foreach($newStudyIDs as $ind=>$nstID){
                      //get the cur study id
                      $cursid = $currStudyIDs[$ind];
                      $cousrex = $dbo->SelectFirstRow("course_tb","count(CourseID)","StudyID = $nstID");
                      if($cousrex[0] < 1)$dbo->RunQuery("UPDATE course_tb SET StudyID=$nstID WHERE StudyID = $cursid");

                      $facrex = $dbo->SelectFirstRow("fac_tb","count(FacID)","StudyID = $nstID");
                      if($facrex[0] < 1)$dbo->RunQuery("UPDATE fac_tb SET StudyID=$nstID WHERE StudyID = $cursid");

                      $maxchrex = $dbo->SelectFirstRow("maxch_tb","count(ID)","StudyID = $nstID");
                      if($maxchrex[0] < 1)$dbo->RunQuery("UPDATE maxch_tb SET StudyID=$nstID WHERE StudyID = $cursid");

                      $rstrex = $dbo->SelectFirstRow("resultapprove_tb","count(ID)","StudyID = $nstID");
                      if($rstrex[0] < 1)$dbo->RunQuery("UPDATE resultapprove_tb SET StudyID=$nstID WHERE StudyID = $cursid");
                      
                      $schrex = $dbo->SelectFirstRow("schoollevel_tb","count(ID)","StudyID = $nstID");
                      if($schrex[0] < 1)$dbo->RunQuery("UPDATE schoollevel_tb SET StudyID=$nstID WHERE StudyID = $cursid");

                      $strex = $dbo->SelectFirstRow("studentinfo_tb","count(id)","StudyID = $nstID");
                      if($strex[0] < 1)$dbo->RunQuery("UPDATE studentinfo_tb SET StudyID=$nstID WHERE StudyID = $cursid"); 

                     /**/
                      //update course_tb
                     //exit("UPDATE course_tb SET StudyID=$nstID WHERE StudyID = $cursid AND (select count(CourseID) FROM course_tb WHERE StudyID = $nstID) < 1");
                  }
              }

            }
        }
$dbo->Commit();
        //exit("*School Settings Saved Successfully");
        $semheaders = array(
            "-SchSemID"=>"SemID",
            "*ScgSemName"=>strtoupper($dbarr['SemLabel']),
            "*ScgSemDescr"=>"DESCRIPTION",
            "*SchSemEnable"=>array("ENABLE","YES|NO"));
           // Box("id=coverbox,style=width:inherit;height:inherit;background-color:red;position:absolute;z-index:1");_Box();
           /* SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:6px;margin-bottom:6px,id=schsemspsh,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=true,minrow=-1",$semheaders, "SELECT ID, Sem, Descr, Enable, IF(Current = 1,'*check','#wrench') as logo, IF(Current = 1,'Active Session','Set to Active') as info , IF(Current = 1,'',CONCAT('School.SchoolSettings.SetSem(',ID,',\'',Sem,'\')')) as Action FROM semester_tb ORDER BY ID"); */
           SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:6px;margin-bottom:6px,id=schsemspsh,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=true,minrow=-1",$semheaders, "SELECT ID, Sem, Descr, Enable, IF(Current = 1,'*check',IF(ID={$sch['SchStartSem']},'*university','#wrench')) as logo, IF(Current = 1,'Active ".$sch['SemLabel']."',IF(ID={$sch['SchStartSem']},'School Start ".$sch['SemLabel']."','Set to Current')) as info , CONCAT('School.SchoolSettings.SetSem(',ID,',\'',Sem,'\')') as Action FROM semester_tb ORDER BY Num");
     echo '<input type="hidden" id="SemLabelInp" value="'.$sch['SemLabel'].'" />';
           echo "~~@@!!#@";
           $sesheaders = array(
            "-SchSesID"=>"SesID",
            "*ScgSessionN"=>"SESSION",
            "*ScgSessionAbb"=>"ABBREVIATION",
            "*SchSesEnable"=>array("ENABLE","YES|NO"));
          // Box("id=coverbox,style=width:inherit;height:inherit;background-color:red;position:absolute;z-index:1");_Box();
          /*  SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:6px;margin-bottom:6px,id=schsessionspsh,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=true,minrow=-1",$sesheaders, "SELECT SesID, SesName, Abbr, Enable, IF(Current = 1,'*check','#wrench') as logo, IF(Current = 1,'Active Session','Set to Active') as info , IF(Current = 1,'',CONCAT('School.SchoolSettings.SetSession(',SesID,',\'',SesName,'\')')) as Action FROM session_tb ORDER BY SesID"); */
          SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:6px;margin-bottom:6px,id=schsessionspsh,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=true,minrow=-1",$sesheaders, "SELECT SesID, SesName, Abbr, Enable, IF(Current = 1,'*check',IF(SesID={$sch['SchStartSes']},'*university','#wrench')) as logo, IF(Current = 1,'Active Session',IF(SesID={$sch['SchStartSes']},'Start Session','Set to Active')) as info , CONCAT('School.SchoolSettings.SetSession(',SesID,',\'',SesName,'\')') as Action FROM session_tb ORDER BY SesID");

           echo '~~@@!!#@' .$dbarr['SemLabel'];

           exit();
    }
    }else{
        /* $dbo->Commit();
        exit("*School Settings Saved Successfully"); */
        $dbo->Rollback();
        exit("#No School Academic Session Configured");
    }
    

   
 }else{
    $dbo->Rollback();
    exit("#School Setting Update Failed");
 }
 
   //update the logo if set
  

  

}else{ // if not exist atall
    if(!isset($_FILES['schsetlogo_image_file']))exit("#Operation Aborted: School Logo Not Set");
    $name = $_FILES['schsetlogo_image_file']['name'];
    $namearr = explode(".",$name);
    $ext = $namearr[count($namearr) - 1];
    $dbarr['logo'] = "UserImages/School/logo.".$ext;
    if(Upload('schsetlogo_image_file',"../../../../epconfig/".$updt['logo'])){
        //$dbarr['logo'] = $db;
        //remove the prevous if changed
    
}else{//if upload failed
    $dbo->Rollback();
    exit("#School Logo Upload Failed");
}

$inst = $dbo->Insert("school_tb",$dbarr);
if($inst != "#"){
    $dbo->Rollback();
    exit("#School Setting Update Failed");
}

$dbo->Commit();
exit("*School Settings Saved Successfully");

}
 


?>