<?php
// sleep(3);
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
//decode Mysql date format(Y-m-d) to user format (D/M/Y)
//#MysqlDateDecode
function MysqlDateDecode($mysqldate){
    //if empty date sent
   if(trim($mysqldate) == "" || trim($mysqldate) == "0000-00-00" || is_null($mysqldate))return "";
   //split the date
   $mysqldatearr = explode("-",$mysqldate);
   if(count($mysqldatearr) < 3)return "";
   $rempartarr = explode(" ",trim($mysqldatearr[2]));
   return $rempartarr[0]."/".$mysqldatearr[1]."/".$mysqldatearr[0];
}
function PadTime($val){
    $val = trim($val."");
    $valen = strlen($val);
    return $valen < 2?"0".$val:$val;

}
function UnProccessTime($timestr=""){
    if(is_null($timestr) || trim($timestr) == "")return "";
    $timearr = explode(":",$timestr);
    $hr = (int)$timearr[0];
    $min = isset($timearr[1])?(int)$timearr[1]:0;
    $sec = isset($timearr[2])?(int)$timearr[2]:0;
    $ampm = 0;
    if($hr > 12){
        $hr = $hr - 12;
        $ampm = 1;
    }
      return [PadTime($hr),PadTime($min),PadTime($sec),$ampm];
  }

  function BoolNumValue($val){
      return trim(strtoupper($val)) == 'TRUE'?1:0;
  }
$map = [
    "SchName"=>"",
    "SchCode"=>"",
    "Duration"=>"01:00:00",
    "Bases"=>0,
    "Direction"=>0,
    "SOrder"=>0,
    "TotQuestion"=>0,
    "TotQuestionAllocation"=>'["","","","",""]',
    "DisControl"=>0,
    "DisTimmer"=>1,
    "DisNumbring"=>1,
    "AllowAllQuestion"=>1,
    "DisRst"=>0,
    "AnimType"=>0,
    "AutoMark"=>1,
    "ScoreFormat"=>0,
    "CandidateStr"=>"{}",
    "ExmID"=>0,
    "UserID"=>0,
    "Scope"=>0,
    "StartDate"=>"",
    "EndDate"=>"",
    'StartTime'=>"",
    'EndTime'=>""
];
//  $map['StartDate'] = $examperiod[0];
// $map['EndDate'] = $examperiod[1];
if(isset($_POST['SchID']) || (int)$_POST['SchID'] > 0){
  //get the schedule
  $mapget = $dbo->SelectFirstRow("cbt_schedule_tb","","ID=".$_POST['SchID'],MYSQLI_ASSOC);
  if(is_array($mapget))$map=$mapget;
}
Form("groupname=CbtScheduleelem,action=javascript:Cbt.CbtSchedule.PSave(),id=cbtschfrm");
GroupBox("title=Schedule Details,id=cbtschexmgrpbx,logo=tasks,size=1");

  Box("id=cbtschexmbx,style=width:100%;overflow:auto;max-height:300px");
  echo '<input type="hidden" value="'.$_POST['SchID'].'" id="ScheduleID" />';
//   Box();Icon("edit fa-3x altColor2");_Box();
  //Box();echo"MONITOR STUDENT REGISTRATION PROCESS";_Box();  
 /*  Box("style=font-size:1.1em");echo"BASIC COMPUTING";_Box();  
  Box("");echo"COM 101";_Box(); */
  TextBoxGroup("width:calc(100% - 12px);margin:auto");
  TextBox("title=Schedule Code,id=newschcode,logo=list-alt,text=".CleanText($map['SchCode']));
  TextBox("title=Schedule Name,id=newschname,logo=list-alt,text=".CleanText($map['SchName']));
  TextBox("title=Schedule Scope,style=width:250px;text-transform:uppercase,id=cbtschscope,logo=users,selected=".$map['Scope'],array("Public","Private"));
  Note();
   echo '<b>Public :</b>Schedule can be accessed by other users <br/>';
   echo '<b>Private :</b>Schedule can be accessed by you only';
  _Note();
  _TextBoxGroup();

  Line();

Box("id=schexmdetbx");
 /*  Table("rowselect=false,style=width:calc(100% - 12px);font-size:0.8em;margin:10px auto;text-align:left;border-top-color:transparent,id=schexamdettb,multiselect=false,data-type=table,onselect=,rowalt=true,rowfilter=false");
  THeader(array("CODE","TITLE"),"");
  TRecord(array("--", "--"),"");
 THeader(array("QUESTION","STATS"),"");
 TRecord(array("Objective", "--"),"");
 TRecord(array("Subjective", "--"),"");
 TRecord(array("Theory", "--"),"");
 TRecord(array("Audio", "--"),"");
 TRecord(array("Video", "--"),"");
 TRecord(array("Total", "--"),"style=font-weight:bold");
 _Table(); */
 $exmdetincluded = true; //to be use in schexamdetails.php to determine if the script is included or called from ajax
 if($map['ExmID'] > 0){
     $_POST['EID'] = $map['ExmID'];
 }
 include "schexamdetails.php";
_Box(); 

       _Box();
 FlatButton("text=Assign Exam,logo=edit,onclick=Cbt.CbtSchedule.AssignExam(this),style=width:262px;margin:auto;border-radius:0px;margin-top:10px,title=Assign Exam,id=cbtschassignexambtn");
 //Ranges("id=hdhd,min=400,max=2000,text=Testing,value=0.8");
 _GroupBox();

 //Date Time settings
 GroupBox("title=Date/Time Settings,id=cbtschexmgrpbx,logo=calendar,size=1");
  Box("style=padding-left:8px;color:#777");echo"Exam Duration";_Box();
  TextBoxGroup();
  TextBoxGroupItem();
  if(!is_null($map['Duration'])){
     $duration = explode(":",$map['Duration']);   
  }else{
    $duration = [1,0,0];
  }

  TextBox("title=Hour,style=text-transform:uppercase,id=cbtschtimehr,logo=clock-o,type=number,text=".(int)$duration[0]);
  TextBoxGroupItemMore();
  TextBox("title=Minute,style=text-transform:uppercase,id=cbtschtimemin,logo=clock-o,type=number,text=".(int)$duration[1]);
  TextBoxGroupItemMore();
  TextBox("title=Seconds,style=text-transform:uppercase,id=cbtschtimesec,logo=clock-o,type=number,text=".(int)$duration[2]);
  _TextBoxGroupItem();
  TextBoxGroupItem();
  Note();echo "Hours";_Note();
  TextBoxGroupItemMore();
  Note();echo "Minute";_Note();
  TextBoxGroupItemMore();
  Note();echo "Seconds";_Note();
  _TextBoxGroupItem();
  
_TextBoxGroup();



TextBoxGroup("margin:10px auto; width:95%");
$bases = array("Exam","Question",'Mark');
$basesid = array_search($map['Bases'],$bases);
TextBox("title=Duration Bases,style=width:250px;text-transform:uppercase,id=cbtschdurbases,logo=th-list,selected={$basesid}",$bases);
Note();
 echo '<div><b style="font-weight:bold">Exam - </b>Total Duration = Set Duration</div>';
 echo '<div><b style="font-weight:bold">Question - </b>Total Duration = Total Question <b style="font-weight:bold">x</b> Set Duration</div>';
 echo '<div><b style="font-weight:bold">Mark - </b>Total Duration = Total Mark <b style="font-weight:bold">x</b> Set Duration</div>';
_Note();
_TextBoxGroup();

TextBoxGroup("margin:10px auto; width:95%");
$period =  "";
if(!is_null($map['StartDate']) && trim($map['StartDate']) != ""){
  $startdate = MysqlDateDecode($map['StartDate']);
$Enddate = MysqlDateDecode($map['EndDate']); 
$period = $startdate." - ".$Enddate; 
}

TextBox("title=Validity Period,type=calendar,style=width:250px;text-transform:uppercase,id=cbtschperiod,logo=calendar,calendar-range=true,text=".CleanText($period));
_TextBoxGroup();

TextBoxGroup();
  TextBoxGroupItem();
  $startTime = "";$startampm = 0;
  if(!is_null($map['StartTime']) && trim($map['StartTime']) != ""){
      $startTimearr = UnProccessTime($map['StartTime']);
      $startTime = $startTimearr[0].":".$startTimearr[1];
      $startampm = $startTimearr[3];
  }
  $endTime = "";$endampm = 0;
  if(!is_null($map['EndTime']) && trim($map['EndTime']) != ""){
      $endTimearr = UnProccessTime($map['EndTime']);
      $endTime = $endTimearr[0].":".$endTimearr[1];
      $endampm = $endTimearr[3];
  }
  
  TextBox("title=H:M - Start time,style=text-transform:uppercase,id=cbtschstarttime,logo=clock-o,text=".CleanText($startTime));
  TextBoxGroupItemMore();
  TextBox("title=AM/PM,style=text-transform:uppercase;width:100px,id=cbtschstarttimeap,logo=sun-o,selected=".$startampm,array("AM","PM"));
  _TextBoxGroupItem();
  
  TextBoxGroupItem();
  TextBox("title=H:M - End time,style=text-transform:uppercase,id=cbtschendtime,logo=history,text=".CleanText($endTime));
  TextBoxGroupItemMore();
  TextBox("title=AM/PM,style=text-transform:uppercase;width:100px,id=cbtschendtimeap,logo=moon-o,selected=".$endampm,array("AM","PM"));
  _TextBoxGroupItem();
  
_TextBoxGroup();

_GroupBox();

//Date Time settings
GroupBox("title=Question Settings,id=cbtschquestgrpbx,logo=question-circle-o,size=1");
TextBoxGroup();
$dirarray = array("Forward","Backward","Both");
$dirid = array_search($map['Direction'],$dirarray);
TextBox("title=Direction,style=text-transform:uppercase;width:250px,id=cbtschquetdirection,logo=arrows-h,selected=".$dirid,$dirarray);

$sorderarray = array("Sequential","Random","Manual");
$sorderid = array_search($map['SOrder'],$sorderarray);
TextBox("title=Ordering,style=text-transform:uppercase;width:250px,id=cbtschquetorder,logo=sort,selected=".$sorderid,$sorderarray);
Note();
echo '<div><b style="font-weight:bold">Sequential - </b>Next Operation Select the Next Question in Database Order</div>';
echo '<div><b style="font-weight:bold">Random - </b>Next Operation Select any on-selected Question Randomly</div>';
echo '<div><b style="font-weight:bold">Manual - </b>User Selects Question Manualy using the Question Map</div>';
_Note();


_TextBoxGroup();

 TextBoxGroup("margin:10px auto;width:95%");
/*TextBox("title=Total Number of Question,style=text-transform:uppercase,id=cbtschtotquest,logo=tasks,type=number"); */
/* TextBox("title=Shuffling,style=text-transform:uppercase;width:250px,id=cbtschquetsuffle,logo=sort,selected=0",array("Normal","Auto"));
Note();
echo '<div><b style="font-weight:bold">Normal - </b>Load Questions From Exam Sequentially</div>';
echo '<div><b style="font-weight:bold">Random - </b>Load Questions From Exam Randomly</div>';
_Note(); */
// TextBoxGroup();
Switcher("id=cbtschautomark,state=".BoolNumValue($map['AutoMark']).",text=Auto-Mark,style=width:100%;margin-top:10px;font-size:1.1em,info=Automatically mark exam based on answer set ,ontext=yes,offtext=no,align=right");
_TextBoxGroup();


//shuffle
_GroupBox();

//Parthern setting
GroupBox("title=Allocation,id=cbtschquestypgrpbx,logo=question-circle,size=1");

//,"1=OBJECTIVE&2=SUBJECTIVE&3=THEORY&4=AUDIO&5=VIDEO"
$allocdump = [
    ["OBJECTIVE",""],
    ["SUBJECTIVE",""],
    ["THEORY",""],
    ["AUDIO",""],
    ["VIDEO",""]
];
if(!is_null($map['TotQuestionAllocation']) && trim($map['TotQuestionAllocation']) != ""){
    $allocobj = json_decode($map['TotQuestionAllocation'],true);
    if(!is_null($allocobj)){
        $a=0;
        while($a < 5){
            $allocdump[$a][1] = $allocobj[$a];
            $a++;
        }
    }
}
$header=array("*CBTQType"=>"TYPE","*CBTQTypeNum"=>["TOTAL",".indallcell"]);
       SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:6px;margin-bottom:6px,id=sprcbttype,multiselect=false,cellfocus=,cellblur=Cbt.CbtSchedule.TotalAllocatedQ,cellkeypress=,dynamiccolumn=false,dynamicrow=false,minrow=5,rowdelete=false,disable=CBTQType,moverow=true",$header,$allocdump);
       
       TextBoxGroup("margin:10px auto;width:95%");
       TextBox("title=Total Allocated Question,style=text-transform:uppercase,id=cbtschtotquest,logo=tasks,type=number,readonly=true,text=".CleanText($map['TotQuestion']));
       _TextBoxGroup();

_GroupBox();

GroupBox("title=Display Settings,id=cbtschdispgrp,style=width:290px,size=1,logo=tv");

 //$lowlvl = $allset['LowerLevel'] == 'TRUE'?1:0;
 TextBoxGroup("width:95%;font-size:0.9em;margin:auto");
 Switcher("id=cbtdiscntr,state=".BoolNumValue($map['DisControl']).",text=Controls,style=width:100%;margin-top:10px,info=Display Controls on Candidate Screen (Pause, Play, Cancel) ,ontext=yes,offtext=no,align=right");
 //Line();
 //$unreg = $allset['UnRegCourses'] == 'TRUE'?1:0;
 Switcher("id=cbtdistimmer,state=".BoolNumValue($map['DisTimmer']).",text=Timmer,style=width:100%;margin-top:10px,info=Display Timmer on Candidate Screen,ontext=yes,offtext=no,align=right");
 //Line();
 //$rept = $allset['ReptCourses'] == 'TRUE'?1:0;
 Switcher("id=cbtdisnum,state=".BoolNumValue($map['DisNumbring']).",text=Page Numbering,style=width:100%;margin-top:10px,info=Display Page Numbering,ontext=yes,offtext=no,align=right");
 //Line();
 //$cprob = $allset['CheckProb'] == 'TRUE'?1:0;
 Switcher("id=cbtdisallquset,state=".BoolNumValue($map['AllowAllQuestion']).",text=Allow All Question View,style=width:100%;margin-top:10px,info=Allow Candidate to View all Questions,ontext=yes,offtext=no,align=right");
 //Line();
 //$cprev = $allset['CheckPrevReg'] == 'TRUE'?1:0;
 Switcher("id=cbtdisrst,state=".BoolNumValue($map['DisRst']).",text=Result,style=width:100%;margin-top:10px,info=Display Result After Exam,ontext=yes,offtext=no,align=right");

 $animTypearray = array("Horizontal","Vertical","Fadding","Zooming");
$animTypeid = array_search($map['AnimType'],$animTypearray);
 TextBox("title=Animation Type,style=text-transform:uppercase;width:250px,id=cbtschdisanimtype,logo=clone,selected={$animTypeid}",$animTypearray);


 $scoreFarray = array("Percentage","Value","Point");
$scoreFid = array_search($map['ScoreFormat'],$scoreFarray);
 TextBox("title=Score Display,style=text-transform:uppercase;width:250px,id=cbtschdisscore,logo=tasks,selected={$scoreFid}", $scoreFarray);

 _TextBoxGroup();
 _GroupBox();
 GroupBox("title=Add Candidate,id=cbtschassigncandgrp,size=2,logo=users");
 /* $studys = $dbo->RunQuery("SELECT ID, Name FROM study_tb WHERE SchoolType = (SELECT Type FROM school_tb LIMIT 1)");
    // $studyData = [];
    
     if(is_array($studys) && $studys[1] > 0){
         $qstrs = "";
         while($indstudys = $studys[0]->fetch_assoc()){
            //$qstrs .= "A"; continue;
             $qstrs .= " UNION SELECT '-1' as Level, 'ANY' as Name";
             
             $qstrs .= " UNION ";
            
             //get all programme in the faculty
             $qstrs .= "select Level, CONCAT('LEVEL',Level) as Name from schoollevel_tb where StudyID = {$indstudys['ID']}  and SchoolTypeID = (select Type from school_tb limit 1)";
             //$studyData[$indstudys['ID']] = $indstudys['Name'];
            // continue;
         }
         $qstrs = ltrim($qstrs," UNION ");
        }
 $headerd = array(
   "*cbtcandop"=>array("JOIN/GROUP",$dbo->DataString(array("NONE","AND","OR","START GROUP","END GROUP"))),

  "*cbtcandLevel"=>array("LEVEL",$dbo->DataString(TextBoxSQL($qstrs)),true),
  "*cbtcandCond"=>array("CONDITION",$dbo->DataString(
   array("None","State of Origin","Gender","Marital Status","Set/Batch","Mode Of Entering","Department","Faculty/School","Study","Faculty Group","Registration Number","Name","Slot","Paid")
  )),
  "*cbtcandCondOp"=>array("OPERATOR","1=IS&2=IS NOT&3=IS OR LESS THAN&4=IS OR GREATER THAN&5=LESS THAN&6=GREATER THAN&7=IN"),
  "*cbtcandVal"=>array("VALUE","@cportal/Pages/Scripts/Payment/paytypecond.php PayTypeCondValue Cond=?cbtcandCond?"));
 
  $headerd["*cbtcandStatus"]=array("ENABLED","YES|NO");
 
 
 SpreadSheet("class=ep-animate-opacity,rowselect=false,style=width:calc(100% - 10px);margin:auto;margin-top:0px;margin-bottom:6px,id=cbtcandrulespre,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=true,onchange=Cbt.CbtSchedule.CheckItem,minrow=5,rowfilter=true,filtertitle=FILTER CANDIDATE RULE LIST,filterstyle=width:calc(100% - 10px);margin:auto;margin-top:10px",$headerd);
 TextBoxGroup("width:calc(100% - 16px);margin:auto;text-align:center");
 Note();
 echo "Verify Ruleset by Loading Selected Candidate  <br/>****** Save Updates before Loading Selected Candidate ******";
 _Note();
 _TextBoxGroup();
 FlatButton("text=Load Selected Candidate, style=margin:auto; margin-top:5px; width:500px,onclick=Cbt.CbtSchedule.LoadCand(),logo=tasks,id=cbtschloadcandbtn"); */

 Box("id=candidatesbx");
CardList("action=Cbt.CbtSchedule.AddCandidate(),id=schcandidate");
 if(!is_null($map['CandidateStr']) && trim($map['CandidateStr']) != ""){
    $data = json_decode($map['CandidateStr'],true);
    if(count($data) > 0){
        foreach($data as $dkey => $ddata){
            Card($ddata);
        }
    }
 }
_CardList();
_Box();

 _GroupBox();
_Form();
?>