<?php


//Get student details R002
function GetStudentDetails($Param){
    //sleep(4);
    
    session_start();
    /* if(!isset($Param['LoginName']) || trim($Param['LoginName']) == ""){
          if(isset($_SESSION['LoginName']) && trim($_SESSION['LoginName']) != ""){
            $Param['LoginName'] = $_SESSION['LoginName'];
          }else{
            Error(5);
          }
    } */
    HasLogin($Param);
    global $dbo;
    global $__Root__;
    //global $Config;
    $LoginName = $dbo->SqlSafe($Param['LoginName']);
    
    $studdet = $dbo->RunQuery("SELECT s.SurName, s.FirstName, s.OtherNames, IF(TRIM(s.RegNo)='',s.JambNo,COALESCE(s.RegNo,s.JambNo)) as RegNo, s.id, s.Passport, s.Email, s.Phone, f.FacName, p.ProgName, s.OtherDet, s.Enable FROM studentinfo_tb s, fac_tb f, dept_tb d, programme_tb p WHERE s.ProgID = p.ProgID AND p.DeptID = d.DeptID AND d.FacID = f.FacID AND ( s.RegNo = '$LoginName' OR s.JambNo = '$LoginName')");
    if(!is_array($studdet))Error(4,": Reading Student Details Failed");
    if($studdet[1] < 1)Error(6,": ".$LoginName);
    $studdet = $studdet[0]->fetch_assoc();
    if((int)$studdet['Enable'] == 0 && (!isset($Param['Scope']) || $Param['Scope'] !='MAIN') )Error(79);
    $_SESSION['LID'] = $studdet['id'];
    $_SESSION['LRegNo'] = $studdet['RegNo'];
    $studdet["DegreeName"] = "--";
    if(trim($studdet['OtherDet']) != ""){
        $odet = json_decode($studdet['OtherDet'],true);
        //remove data that are not neccessary
       foreach(["PayRef","PayID"] as $unes){
        if(isset($odet[$unes]))unset($odet[$unes]);
       }
        if(!is_null($odet)){
            $studdet = array_merge($studdet,$odet);
            //get the degree details
            if(isset($studdet['Degree'])){
                $degdet = $dbo->SelectFirstRow("school_degrees_tb","","ID=".$studdet['Degree']);
                if(is_array($degdet)){
                    $studdet["DegreeName"] = $degdet['Name'];
                }else{
                    $studdet["DegreeName"] = "--";
                }
            }
        }
       
    }
    //reprocess image url
    $passp = "logo.png";
    if(trim($studdet['Passport']) != ""){
        $passp = $studdet['Passport'];
        $passparr = explode("?",$passp);
        $passp = $passparr[0];
        $passparra = explode("/",$passp);
        if($passparra[0] == ".."){
            $passparra[0] = "";
        }else if($passparra[0] == "UserImages"){
           array_unshift($passparra,'Files');
        }

        $passp = ResolveFilePath(implode("/",$passparra));
        
    }
    
    // $studdet['Image'] = $dbo->ImageToDataURI()
    if(file_exists("../../../../".$dbo->Config["SubDir"].$passp)){
$studdet['DataUrIImage'] = $passp != ""?$dbo->ImageToDataURI("../../../../".$dbo->Config["SubDir"].$passp):"";
    $studdet['Image'] = $passp;
    }else{
        //get the directory where it is checking from
        $struimagesarr = explode("/",str_replace("Files/UserImages/","",trim($passp)));
        $curentfolder = $struimagesarr[0];
        $seclookupfolders = $curentfolder == "Student"?"PUTME":"Student";
        $struimagesarr[0] = $seclookupfolders;
        $nepassp = "Files/UserImages/" . implode("/",$struimagesarr);
        if(file_exists("../../../../".$dbo->Config["SubDir"].$nepassp)){
            $studdet['DataUrIImage'] = $nepassp != ""?$dbo->ImageToDataURI("../../../../".$dbo->Config["SubDir"].$nepassp):"";
            $studdet['Image'] = $nepassp;
            //update the newly found
            $uppassp = $dbo->Update("studentinfo_tb",["Passport"=>str_replace("Files/","",trim($nepassp))],"id=".$studdet['id']);

        }else{ //if not found
           $studdet['DataUrIImage'] = $dbo->ImageToDataURI("../../images/bbwa/logo.png");
        $studdet['Image'] = $dbo->Config["Core"]."images/bbwa/logo.png"; 
        }
        
        
    }
    $studdet['LoginName'] = $LoginName;
    $studdet['allowPIN'] = "truegg";
    $rdata = "{Src:'{$__Root__}general/Slip.php?regno={$studdet['RegNo']}&folder=Form&SubDir=" . urlencode($dbo->Config['SubDir']) . "',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
    $studdet['PrintRecord'] = $rdata;
    $adata = "{Src:'{$__Root__}general/Slip.php?regno={$studdet['RegNo']}&folder=AcceptLetter&SubDir=" . urlencode($dbo->Config['SubDir']) . "',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
    $studdet['PrintAccept'] = $adata;
    //Error("CE",json_encode($studdet));
    //$studdet['ff'] = "../../../../".$Config["SubDir"].$passp;
    return $studdet;
    

}

//verify user password
function CheckPassword($Param){
    //Error(7);
    session_start();
    if(!isset($Param['LRegNo']))Error(8);
    if(!isset($Param['AccessCode']) || trim($Param['AccessCode']) == "")Error(5);
    global $dbo;
    $AccessCode = $dbo->SqlSafe($Param['AccessCode']);
    $RegNo = isset($_SESSION['LRegNo']) && trim($_SESSION['LRegNo']) != ""?$dbo->SqlSafe($_SESSION['LRegNo']):$dbo->SqlSafe($Param['LRegNo']);
    $passw = $dbo->RunQuery("SELECT JambNo FROM accesscode_tb WHERE JambNo = '$RegNo'AND AccessCode = '$AccessCode'");
    if(!is_array($passw))Error(4,": Authenticating Access Code Failed.");
    if($passw[1] < 1)Error(7);
    $passw = $passw[0]->fetch_assoc();
    $_SESSION['ALID'] = $_SESSION['LID'];
    $_SESSION['ALRegNo'] = $Param['LRegNo'];
    $_SESSION['LoginName'] = $Param['LRegNo'];
    return $passw;
}


//get the student stat - #R057
function GetStatistics($param){
    global $dbo;
    $lastlvl = 1; $lastsem = 1;
    //list()
    if(!isset($param['LevelID']) || !isset($param['SemID'])){
        
        $lastdet = GetStudentLevelSemester($param);
        $lastlvl = $lastdet['LevelID']; $lastsem = $lastdet['SemID'];
    }else{
        
        $lastlvl = $param['LevelID']; $lastsem = $param['SemID'];
    }
    $rtn = ["Course"=>"off","Payment"=>"off","Result"=>"off"];
   // return $rtn;
    //check if courseregistered
    $lstcreg = $dbo->SelectFirstRow("coursereg_tb","ID","RegNo='".$dbo->SqlSafe($param['LoginName'])."' AND Lvl=$lastlvl AND Sem=$lastsem LIMIT 1",MYSQLI_ASSOC);
    if(is_array($lstcreg))$rtn['Course'] = "on";

    $progID = GetStudentProgIDForPay($param['LoginName']);

    //check if payment
    $lstpay = $dbo->SelectFirstRow("payhistory_tb","ID","RegNo='".$dbo->SqlSafe($param['LoginName'])."' AND Lvl=$lastlvl AND Sem >= $lastsem AND SemPart > 1 AND ProgID=$progID LIMIT 1",MYSQLI_ASSOC);
    if(is_array($lstpay))$rtn['Payment'] = "on";

    //check if result
    $lstrst = $dbo->SelectFirstRow("result_tb","ID","RegNo='".$dbo->SqlSafe($param['LoginName'])."' AND Lvl=$lastlvl AND Sem = $lastsem LIMIT 1",MYSQLI_ASSOC);
    if(is_array($lstrst))$rtn['Result'] = "on";
    return $rtn;
}

//R065
//get student academic progress
function GetProgress($param=[]){
    global $dbo;
    //get expected total year of the student programm
    $progdet = $dbo->SelectFirstRow('studentinfo_tb s, programme_tb p','p.*',"s.ProgID = p.ProgID AND (s.RegNo='".$dbo->SqlSafe($param['LoginName'])."' OR s.JambNo='".$dbo->SqlSafe($param['LoginName'])."') LIMIT 1");
    $paypecprogress = $cpecprogress = $cpecprogress =20;
    $paycolor = $ccolor = $rcolor ="#f44336aa";
    if(is_array($progdet)){
        $yearofStudy = (int)$progdet['YearOfStudy'];
        //get the total semester
        $higestsem = HighestSemester();
        $totexpPay = $yearofStudy * $higestsem['Num'];
        //get paid records so far
        $rq = $dbo->RunQuery("SET SESSION sql_mode = '' ");
        $totpaid =  $dbo->Select("payhistory_tb p","count(p.Sem) as TotPay","p.RegNo='{$param['LoginName']}' and p.PayScope != 'w' GROUP BY Lvl,Sem",MYSQLI_ASSOC);
        /* $totpaid = $dbo->SelectFirstRow("payhistory_tb","SUM(SemPart) as TotPay","RegNo='".$dbo->SqlSafe($param['LoginName'])."' AND ProgID=".$progdet['ProgID']); */
        $totCalc = 0;
        if(is_array($totpaid) && $totpaid[1] > 0){
            while($indtotpaid = $totpaid[0]->fetch_assoc()){
               $totCalc += (int)$indtotpaid['TotPay']; 
            }
            
            if($totexpPay > 0){
                $paypecprogress = ceil(($totCalc/$totexpPay) * 125);
            }
        }
        
        if($paypecprogress > 40)$paycolor = "";

        //ge total course registered
        $totcreg =  $dbo->SelectFirstRow("coursereg_tb","COUNT(ID) as TotCourse","RegNo='".$dbo->SqlSafe($param['LoginName'])."'");
        if(is_array($totcreg)){
            $possiblesem = $dbo->SelectFirstRow("semester_tb","COUNT(ID) as TotSem");
            $totcr = (int)$totcreg['TotCourse'];
            $totexpc = $yearofStudy * (int)$possiblesem['TotSem'];
            if($totexpc > 0){
                $cpecprogress = ceil(($totcr/$totexpc) * 125);
            }
        }
        if($cpecprogress > 65)$ccolor = "";
       
        //result records
        $totrst =  $dbo->Select("result_tb","","RegNo='".$dbo->SqlSafe($param['LoginName'])."'");
        if(is_array($totrst) && $totrst[1] > 0){
            $Found = [];
            $cnt = 0;
            while($studRsti = $totrst[0]->fetch_assoc()){
                if(isset($Found[$studRsti['Lvl']."_".$studRsti['Sem']."_".$studRsti['SesID']]))continue;
    $Found[$studRsti['Lvl']."_".$studRsti['Sem']."_".$studRsti['SesID']] = true;
    $cnt++;
            }
            $totr = $cnt;
            
            $totexpr = $yearofStudy * (int)$possiblesem['TotSem'];
          
            if($totexpr > 0){
                $tpecprogress = ceil(($totr/$totexpr) * 125);
            }
        }
     
        if($tpecprogress > 40)$rcolor = "";
    }
   
   
    return ["PayProgress"=>$paypecprogress,"PayProgressColor"=>$paycolor,"PayDisTxt"=>$totCalc."/".$totexpPay,"CProgress"=>$cpecprogress,"CProgressColor"=>$ccolor,"CDisTxt"=>$totcr."/".$totexpc,"RProgress"=>$tpecprogress,"RProgressColor"=>$rcolor,"RDisTxt"=>$totr."/".$totexpr];

}
