<?php
extract($_POST);
$configdir = "../../../../../".$subdir;
require_once("../../../general/config.php"); 
if(!isset($_POST['SchID'])){exit('{"Error":"INVALID SCHOOL SELECTED"}');}
//get all the study of the curent school
$studies = $dbo->Select("study_tb","","SchoolType=(select Type from school_tb limit 1) and StudySchID = ".$_POST['SchID']);
if(!is_array($studies)){exit('{"Error":"'.$studies.'"}');}
if($studies[1] < 1){exit('{"Error":"NO STUDY CONFIGURED"}');}
$Data = [];
while($indstud = $studies[0]->fetch_array()){
    //get all the students
    /* $totstud = $dbo->RunQuery("Select count(s.id) as TotalStud, '".$indstud['Name']."' as StudyName From studentinfo_tb s, programme_tb p, dept_tb d, fac_tb f where f.StudyID = {$indstud['ID']} AND d.FacID = f.FacID AND p.DeptID = d.DeptID AND s.ProgID = p.ProgID AND s.RegLevel = 6 AND IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != '' ");
    //Select count(s.id) as TotalStud, 'StudyName' as StudyName From studentinfo_tb s, programme_tb p, dept_tb d, fac_tb f where f.StudyID = 5 AND d.FacID = f.FacID AND p.DeptID = d.DeptID AND s.ProgID = p.ProgID AND s.RegLevel = 6 AND IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != '' 
    if(!is_array($totstud) || $totstud[1] < 1){
       $Data[] = [$indstud['Name'],1];
    }else{
        $recs = $totstud[0]->fetch_array();
        $tot = (int)$recs['TotalStud'] == 0?1:(int)$recs['TotalStud'];
       $Data[] = [$indstud['Name'],$tot]; 
    } */
    $inData = [
        "StudyName"=>"Study - ".$indstud['Name'],
        "Data"=>[["Faculty","Number of Student"]]
    ];
    //get all student by fac and study
    $allfac = $dbo->RunQuery("Select * from fac_tb where StudyID=".$indstud['ID']);
    $overall = 0;
    if(is_array($allfac) && $allfac[1] > 0){
       
        //$inData = [["Faculty","Number of Student"]];
        while($indFac = $allfac[0]->fetch_array()){
            //get total number of student in the faculty
        
        $totstud = $dbo->RunQuery("Select count(s.id) as TotalStud, '".$indFac['FacName']."' as FacName From studentinfo_tb s, programme_tb p, dept_tb d where d.FacID = {$indFac['FacID']} AND p.DeptID = d.DeptID AND s.ProgID = p.ProgID AND s.RegLevel = 6 AND IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != '' ");
        if(!is_array($totstud) || $totstud[1] < 1){
            $inData['Data'][] = [$indFac['Abbr'],1];
         }else{
             $recs = $totstud[0]->fetch_array();
             $tot = (int)$recs['TotalStud'] == 0?1:(int)$recs['TotalStud'];
             $inData['Data'][] = [$indFac['Abbr'],$tot]; 
             $overall += $tot;
         }


        }
        
    }
    $inData["Overall"] = number_format($overall);
    $Data[] =  $inData;
}
echo json_encode($Data);
?>