<?php

function Testing($param){

    return ["Testing"=>["Data"=>json_encode($param)]];
}


//report data for result broadsheet
function BroadSheetBasic($param){
    global $dbo;
    //return ['Failed'=>["Message"=>json_encode($param),'ResultInfo'=>[0],'Title'=>"jjjj"]]; 
    $Dt = $param['Data'];
    $title = "";
    if(isset($Dt['StudyID'])){
        extract($Dt);
        if((int)$StudyID < 1){
            //get based on prog
            $sudobj = $dbo->SelectFirstRow("study_tb s, programme_tb p, dept_tb d, fac_tb f","s.ID","p.ProgID = $ProgID AND p.DeptID = d.DeptID AND d.FacID = f.FacID AND f.StudyID = s.ID");
            if(is_array($sudobj))$StudyID = $sudobj['ID'];
        }
        $title = $utitle;
        //get the other parameters
        $rstinfo = $dbo->RunQuery("SELECT f.FacName, d.DeptName, p.ProgName, p.YearOfStudy,s.SesName,UCASE(IF(sm.Descr='',sm.Sem,sm.Descr)) as SemName,UCASE(IF(lvl.Descr='',lvl.Name,lvl.Descr)) as LevelName,st.Name as StudyName, cl.Name as ClassName FROM fac_tb f, dept_tb d, programme_tb p, session_tb s, semester_tb sm, schoollevel_tb lvl, study_tb st,studentclass_tb cl WHERE f.FacID = d.FacID AND d.DeptID = p.DeptID AND s.SesID = $SesID AND ((sm.Num > 0 && sm.Num = $SemID) || (sm.ID = $SemID && sm.Num = 0)) AND p.ProgID = $ProgID AND lvl.Level= $LevelID AND lvl.StudyID = f.StudyID AND lvl.SchoolTypeID = (SELECT Type FROM school_tb) AND lvl.StudyID = st.ID AND st.ID = $StudyID AND cl.ProgID = p.ProgID AND cl.ID=$ClassID LIMIT 1");
        if(!is_array($rstinfo)){
            return ['Failed'=>["Message"=>"Error Loading Result Info - ".$rstinfo,'ResultInfo'=>[0],'Title'=>$title]]; 
        }
        if($rstinfo[1] < 1){
            return ['Failed'=>["Message"=>"No Result Info Found",'ResultInfo'=>[0],'Title'=>$title]];
        }
        $rstinfo = $rstinfo[0]->fetch_assoc();
        $rstapprdet = $dbo->SelectFirstRow("resultapprove_tb","","ProgID=".$ProgID." AND Ses=".$SesID." AND Lvl=".$LevelID." AND Sem=".$SemID." LIMIT 1");

       $rstinfoid = is_array($rstapprdet)?$rstapprdet['RstInfoID']:"1";
       $grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = $rstinfoid");
        $portaldisplay = $grdstr['PortalResultDisplay'];
        $portaldisplay = trim($portaldisplay) == ""?[]:json_decode($portaldisplay,true);
        $arraysdis = [
            "GPA"=>["TCH"=>"TCH","TGP"=>"TGP","GPA"=>"GPA"],
            "CGPA"=>["CCH"=>"CCH","CGP"=>"CGP","CGPA"=>"CGPA"],
            "TOT"=>["OTS"=>"TOT"],
            "AVG"=>["OAS"=>"AVG"],
            "AVGClass"=>["AVGClass"=>"CLASS AVG"],
            "POS"=>["POS"=>"POS"],
            "POSClass"=>["POSClass"=>"CLASS POS"],
            "COP"=>["COP"=>"COP"]
          ];
          $header= [];
foreach($portaldisplay as $distype=>$enable){
  if((int)$enable == 1 && isset($arraysdis[$distype])){
    $header = array_merge($header,$arraysdis[$distype]);
  }
}

//form header

        //$rstinfo['SemName'] = (int)$rstinfo['Sem'] == 1?"FIRST":"SECOND";
        // $rstinfo['SemName'] = strtoupper($rstinfo['Sem']);

        //get the max number of result, for result padding
        $maxrst = $dbo->SelectFirstRow("result_tb r, studentinfo_tb s","MAX(r.TRC)","r.Lvl = $LevelID AND r.Sem = $SemID AND r.SesID = $SesID AND s.ProgID = $ProgID AND s.ClassID=$ClassID");
        if(!is_array($maxrst)){ //
            return ['Failed'=>["Message"=>"Error Determining Maximum Result Count",'ResultInfo'=>[0],'Title'=>$title]];
        }
        $maxrst = $maxrst[0];
        //get the results
        $q = "SELECT r.*, s.SurName ,s.FirstName,s.OtherNames, s.StartSes FROM coursereg_tb c LEFT JOIN result_tb r ON (c.RegNo = r.RegNo AND c.Lvl = r.Lvl AND c.Sem = r.Sem AND c.SesID = r.SesID) INNER JOIN studentinfo_tb s ON (r.RegNo = s.RegNo OR r.RegNo = s.JambNo) WHERE (r.Lvl = $LevelID AND r.Sem = $SemID AND r.SesID = $SesID AND s.ProgID = $ProgID AND s.ClassID = $ClassID) ORDER BY r.OAS DESC, r.RegNo ASC, s.SurName ASC ,s.FirstName ASC,s.OtherNames ASC, r.GroupID DESC";
        $rst = $dbo->RunQuery($q);
       // return ['Failed'=>["Message"=>$q,'ResultInfo'=>[0]]]; 
        if(!is_array($rst)){
            return ['Failed'=>["Message"=>"Reading Results Failed - ".$rst,'ResultInfo'=>[0],'Title'=>$title]]; 
        }

        if($rst[1] < 1){
            return ['Failed'=>["Message"=>"No Result Found",'ResultInfo'=>[0],'Title'=>$title]]; 
        }
        
        $nrst = [];
        $Seen = [];
        $Scoretitles = array_values($header);
        
        //form the seult array
        while($rstind = $rst[0]->fetch_assoc()){
            //$nwrst = [];
            $RegNo = $rstind['RegNo'];
            if(in_array($RegNo,$Seen)){
              continue;
            }
            $Seen[] = $RegNo;
          $Rst = $rstind['Rst'];
          $Rstinfo = json_decode($rstind['RstInfo'],true);
          
          //break down rst
$allrsts = array_values($Rstinfo);
$rstcnt = count($allrsts);
$diff = $maxrst - $rstcnt;
if($diff < 1)$diff = 0;
//if($rstcnt > $maxrst)$maxrst = $rstcnt;
          /* $brdwnrst = explode("&",$Rst);
          
          if(count($brdwnrst) > 0){
            $rstcnt = 0;
             foreach($brdwnrst as $indrst){
                $crst = explode("=",$indrst);
                $CID = $crst[0];
                $CRst = $crst[1];
                 $Crsts = explode("|",$CRst);
$tot = (float)$Crsts[0] + (float)$Crsts[1];
                 $allrsts[] = ["CourseCode"=>$Rstinfo[$CID]['CourseCode'],"Total"=>$tot,"Grade"=>$Crsts[3]];
                 $rstcnt++;
             }
             
          } */
if(count($allrsts) < 1){
    $allrsts = [0]; //meaning display nothing
}
$rstind['Result'] = $allrsts;
$rstind['Padding'] = [$diff];
$rstdet = [];
        foreach($header as $field=>$stitle){
            if(isset($rstind[$field])){
                $rstdet[] = $rstind[$field];
            }elseif($field == "POS"){
                $rstdet[] = GetStudentResultPosition($rstind,["ProgID"=>$ProgID,"StartSes"=>$rstind['StartSes']]);
            }elseif($field == "AVGClass"){
                $classrstdet = GetStudentOverallClassResultDetails($rstind,["ProgID"=>$ProgID,"ClassID"=>$ClassID],true);
                $rstdet[]=round($classrstdet[2]/$classrstdet[0],2);
            }elseif($field == "POSClass"){
                $rstdet[]=GetStudentResultPosition($rstind,["ProgID"=>$ProgID,"ClassID"=>$ClassID,"StartSes"=>$rstind['StartSes']],true);
            }else{
                $rstdet[] = "";
            }
        }
        $rstind["Scoring"] = $rstdet;
$nrst[] = $rstind;
        }
        //get details
        

//$rst = $rst[0]->fetch_all(MYSQLI_ASSOC);
        return ["Success"=>["ResultDetail"=>$nrst, "MaxTRC"=>$maxrst],'ResultInfo'=>$rstinfo,'Title'=>$title,"ScoringTit"=>$Scoretitles];
        
        //return ["Success"=>['ResultInfo'=>$rstinfo]];
        
    }else{
        return ['Failed'=>["Message"=>"InValid Parameter",'ResultInfo'=>[0],'Title'=>$title]]; 
    }
}

?>