<?php

//donothing
//#R000
function DoNothing($Param)
{
    return [];
}





//Internal
if (!function_exists('HighestSemester')) {
    function HighestSemester()
    {
        global $dbo;
        //get highest semester
        $highsem = 0;
        $higestsem = $dbo->SelectFirstRow("semester_tb", "ID,IF(Num=0,ID,Num) as Num", "Enable = 1 ORDER BY Num DESC, ID DESC LIMIT 1");
        if (!is_array($higestsem)) {
            /* $higestsem['Num'] = $higestsem['Num'] == 0?$higestsem['ID']:$higestsem['Num'];
    }else{ */
            $higestsem = ["ID" => 2, "Num" => 2, "Sem" => "Second", "Descr" => "Second Semester"];
        }
        return $higestsem;
    }
}





//Get Candidate Details - R010
function GetCandidate($Param)
{
    session_start();

    global $dbo;
    $BankPre = "p";
    $PrintFolder = "Candidate";
    //check if entrance id set
    if (isset($Param['EntranceID'])) {
        //get the bank pre
        $BankPreObj = $dbo->SelectFirstRow("putme", "StudInfoPref,Param", "ID=" . $Param['EntranceID'], MYSQLI_ASSOC);
        if (is_array($BankPreObj)) $BankPre = $BankPreObj['StudInfoPref'];
        if (trim($BankPreObj['Param']) != "") {
            $ParamDet = json_decode($BankPreObj['Param'], true);
            if (isset($ParamDet['PrintDir'])) $PrintFolder = $ParamDet['PrintDir'];
        }
    }

    global $__Root__;
    Underscored($Param);
    MapData($Param);
    //Error(15, " : ".json_encode($Param));
    if (isset($Param['RegNo']) && trim($Param['RegNo']) != "") {
        //check if regno is phone or email
        $regarr = explode("@", $Param['RegNo']);
        $isemail = [];
        $isphone = [];
        if (count($regarr) > 1) { //if the type of regno is email, allow phone number
            $isphone = [1];
        } else {
            $isemail = [1];
        }
        $RegNo = $dbo->SqlSafe($Param['RegNo']);

        //get candidate details from pstudent info
        $canddet = $dbo->SelectFirstRow("{$BankPre}studentinfo_tb", "", "RegNo='$RegNo' OR JambNo='$RegNo'", MYSQLI_ASSOC);
        if (!is_array($canddet)) { //if not found in pstudent info
            //the check in payee_tb
            $canddet = $dbo->SelectFirstRow("payee_tb", "", "PayeeID='$RegNo'");
            if (is_array($canddet)) {
                $cand = [];
                //get all the field name
                $columns = $dbo->RunQuery("SHOW COLUMNS FROM pstudentinfo_tb");
                while ($indcol = $columns[0]->fetch_assoc()) {
                    if ($indcol['Field'] == "id") continue;
                    $cand[$indcol['Field']] = "";
                }


                $CNames = explode(" ", $canddet['Name']);
                $cand['SurName'] = trim($CNames[0]);
                $cand['FirstName'] = trim($CNames[1]);
                $CNames[0] = "";
                $CNames[1] = "";
                $cand['OtherNames'] = trim(implode(" ", $CNames));
            } else {
                Error(15, json_encode($Param));
            }
            $canddet = $cand;
            $canddet["Occupation"] = "";
            $canddet["Degree"] =  "";
            $canddet["AreaofSpecial"] = ""; //ResearchTopic
            $canddet["ResearchTopic"] = "";
            $canddet["FormerName"] = "";
            $canddet["StudyModeFullTime"] = "";
            $canddet["StudyModePartTime"] = "";
            $canddet["StudyMode"] = "";
            $canddet["FacultyName"] = "";
            $canddet["ProgrammeName"] = "";
            $canddet["Address"] = "";
            $canddet["OtherAddress"] = "";
            //$canddet["StudyID"] = "";
        } else {
            //return ["RegNo"=>"ab_keje@yahoo.com","SurName"=>$canddet["SurName"]];
            $otherdet = trim($canddet['OtherDet']) == "" ? [] : json_decode($canddet['OtherDet'], true);
            //$RtnData["CandFullName"] = $canddet['SurName']." ".$canddet['FirstName']." ".$canddet['OtherNames'];
            //$RtnData["CandFullName"] = $canddet['SurName']." ".$canddet['FirstName']." ".$canddet['OtherNames'];

            $canddet["DOB"] = MysqlDateDecode($canddet['DOB']);
            $canddet["GenderMale"] = $canddet['Gender'] != "F" ? "checked" : "";
            $canddet["GenderFemale"] = $canddet['Gender'] == "F" ? "checked" : "";
            $canddet['Gender'] = $canddet['Gender'] != "F" ? "Male" : "Female";
            $canddet["Occupation"] = isset($otherdet['Occupation']) ? $otherdet['Occupation'] : "";
            $canddet["FormerName"] = isset($otherdet['FormerName']) ? $otherdet['FormerName'] : "";
            $degree = "";
            if (isset($otherdet['Degree'])) {
                $degree = $dbo->SelectFirstRow("school_degrees_tb", "", "ID=" . $otherdet['Degree']);
                $degree = is_array($degree) ? $degree['Name'] : "";
            }

            $canddet["Degree"] = $degree;
            $canddet["AreaofSpecial"] = isset($otherdet['AreaofSpecial']) ? $otherdet['AreaofSpecial'] : ""; //ResearchTopic
            $canddet["ResearchTopic"] = isset($otherdet['ResearchTopic']) ? $otherdet['ResearchTopic'] : "";
            $canddet["StatusMarried"] = $canddet['MaritalStatus'] != "S" ? "checked" : "";
            $canddet["StatusSingle"] = $canddet['MaritalStatus'] == "S" ? "checked" : ""; //StudyModeFullTime
            $canddet["StudyModeFullTime"] = (isset($otherdet['StudyModeFullTime']) && (int)$otherdet['StudyModeFullTime'] == 1) ? "checked" : "";
            $canddet["StudyModePartTime"] = (isset($otherdet['StudyModePartTime']) && (int)$otherdet['StudyModePartTime'] == 1) ? "checked" : "";
            $canddet["StudyMode"] = $canddet["StudyModeFullTime"] == "checked" ? "Full Time" : "Part Time";
            //$canddet["Nationality"] = $canddet['Nationality'];
            $canddet["StateID"] = $canddet['StateId'];
            $canddet["Address"] = $canddet['Addrs'];
            $canddet["OtherAddress"] = isset($otherdet['OtherAddress']) ? $otherdet['OtherAddress'] : "";
            if (isset($canddet["ProgID"]) && (int)$canddet["ProgID"] > 0) {
                $admidet = $dbo->SelectFirstRow("fac_tb f, programme_tb p, dept_tb d", "f.FacName,p.ProgName", "p.ProgID=" . $canddet["ProgID"] . " AND p.DeptID = d.DeptID AND f.FacID = d.FacID", MYSQLI_ASSOC);
                if (!is_array($admidet)) {
                    $canddet["FacultyName"] = "";
                    $canddet["ProgrammeName"] = "";
                } else {
                    $canddet["FacultyName"] = $admidet["FacName"];
                    $canddet["ProgrammeName"] = $admidet["ProgName"];
                }
            }
        }
        //get studyid from programme id
        if (isset($canddet["ProgID"]) && (int)$canddet["ProgID"] > 0 && (int)$canddet["StudyID"] < 1) {
            $canddet["StudyID"] = GetStudyID($canddet["ProgID"]);
        }

        if ((int)$canddet["StudyID"] == 0 && isset($Param["StudyID"]) && (int)$Param["StudyID"] > 0) $canddet["StudyID"] = $Param["StudyID"];
        $rd = $dbo->Config['Core']."general/Slip.php?folder={$PrintFolder}&BankPre={$BankPre}&regno=" . $RegNo . "&paper=A4&orientation=P&MT=4&MB=30&SubDir=" . urlencode($dbo->Config['SubDir']);
        $canddet["RedirectURL"] = $rd;
        $sub = urlencode($dbo->Config['SubDir']);
        $canddet["RedirectData"] = "{Src:'{$dbo->Config['Core']}general/Slip.php?folder={$PrintFolder}&BankPre={$BankPre}&regno={$RegNo}&SubDir={$sub}',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
        $canddet["AllowPhone"] = $isphone;
        $canddet["AllowEmail"] = $isemail;
        $canddet["RegNo"] = $Param['RegNo'];
        return $canddet;
    } else {
        //Error(15, " : ".json_encode($Param));
        Error(15);
    }
    //return $_SESSION;

}

//function to get studyid by progid
function GetStudyID($progid)
{
    global $dbo;
    $study = $dbo->SelectFirstRow("fac_tb f, dept_tb d, programme_tb p", "f.StudyID", "f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = $progid");
    if (is_array($study)) return $study['StudyID'];
    return 0;
}





//Private
//Resolve underscore parameter name
function Underscored(&$Param)
{
    foreach ($Param as $Key => $Val) {
        //check if system data
        if (substr($Key, 0, 2) == "__") continue;
        //break down keys
        $Keyus = explode("_", $Key);
        if (count($Keyus) > 1) {
            array_pop($Keyus);
            $remkey = implode("_", $Keyus);
            //if(!isset($Param[$remkey]))
            $Param[$remkey] = $Val;
        }
    }
}

//private
//Handle _EPAPI_MAPPING_
function MapData(&$Param)
{
    if (!isset($Param['_EPAPI_MAPPING_'])) return;
    $mappins = is_array($Param['_EPAPI_MAPPING_']) ? $Param['_EPAPI_MAPPING_'] : [$Param['_EPAPI_MAPPING_']];
    if (count($mappins) > 0) {
        foreach ($mappins as $imap) {
            //get multiple mapping
            $multmapp = explode(";", $imap);
            foreach ($multmapp as $map) {
                $mapdata = explode("=>", $map);
                if (count($mapdata) > 1) {
                    //main map
                    $mainmap = "";
                    foreach ($mapdata as $indmap) {
                        $indmap = trim($indmap);
                        if ($indmap != "") {
                            if ($mainmap == "") {
                                $mainmap = $indmap;
                            } else {
                                if (isset($Param[$mainmap])) {
                                    $Param[$indmap] = $Param[$mainmap];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

//Get all faculties - R014
function GetFaculty($Param)
{
    // Error(4,$Param['ProgID']);
    global $dbo;
    $studycond = (isset($Param['StudyID']) && (int)$Param['StudyID'] > 0) ? "StudyID=" . $dbo->SqlSafe($Param['StudyID']) : "1=1";
    $facs = $dbo->Select("fac_tb", "", $studycond);
    //Error(4,$studyid);
    if (!is_array($facs)) Error(4);
    return $dbo->FetchAll($facs[0], MYSQLI_ASSOC);
}

//Get all programmes by deptid - R015
function GetProgrammeByFaculty($Param)
{
    global $dbo;
    if (!isset($Param['FacID']) || (int)$Param['FacID'] < 1) Error(11);
    $FacID = $Param['FacID'];
    $facs = $dbo->Select("programme_tb p, dept_tb d", "p.*", "d.FacID=" . $dbo->SqlSafe($FacID) . " AND p.DeptID = d.DeptID");
    if (!is_array($facs)) Error(4);
    return $dbo->FetchAll($facs[0], MYSQLI_ASSOC);
}



//Send Mail - R019
function SendMail($Param)
{

    Underscored($Param);
    MapData($Param);
    if (!isset($Param['ToAddress']) || !isset($Param['Mail'])) {
        if (isset($Param['Optional']) && $Param['Optional'] == true) {
            return ["Status" => "Not Sent", "ToAddress" => ""];
        }
        Error(11);
    }
    //if(file_exists($Param['Mail'])){
    //Error(21," : Exist");
    $Mail = file_get_contents($Param['Mail']);
    $Param['Mail'] = "";
    //fill in placeholders
    foreach ($Param as $field => $val) {
        if (!is_string($val) && !is_numeric($val)) continue;
        $Mail = str_replace("{{" . $field . "}}", $val, $Mail);
    }

    //Error(11,json_encode($Param));

    // }
    if (!isset($Param['FromName'])) $Param['FromName'] = "Eduporta";
    if (!isset($Param['Subject'])) $Param['Subject'] = "";
    $Param['ToAddress'] = is_array($Param['ToAddress']) ? $Param['ToAddress'] : [$Param['ToAddress']];
    $sent = 0;
    foreach ($Param['ToAddress'] as $toaddr) {
        if (trim($toaddr) == "") continue;
        $sendmail = genPHPMEmail($toaddr, $Param['FromName'], $Param['Subject'], $Mail);
        if ($sendmail !== true) {
            if (isset($Param['Optional']) && $Param['Optional'] == true) {
                return ["Status" => "Not Sent", "ToAddress" => ""];
            }
            Error(21, " : " . $toaddr);
        }
        $sent++;
    }
    if ($sent > 0) {
        return ["Status" => "Sent", "ToAddress" => $Param['ToAddress']];
    }
    if (isset($Param['Optional']) && $Param['Optional'] == true) {
        return ["Status" => "Not Sent", "ToAddress" => ""];
    }
    Error(21, " : No Sent Mail");
}

//private mailing
//generate emil
function genPHPMEmail($mailto = "", $from_name = "Eduporta", $subject = "Eduporta Mail", $msg = "Eduporta")
{
    if (trim($mailto) == "") return "No Destination Mail Address Supplied";
    $mailto = $mailto;
    $from_name = $from_name;
    $from_mail = "taquatech@gmail.com";
    $subject = $subject;
    $message = $msg;
    $boundary = "XYZ-" . date('dmYis') . "-ZYX";
    $header = "--$boundary\r\n";
    $header .= "Content-Transfer-Encoding: 8bits\r\n";
    $header .= "Content-Type: text/html; charset=ISO-8859-1\r\n\r\n";
    $header .= "$message\r\n";
    $header .= "--$boundary\r\n";

    $header2 = "MIME-Version: 1.0\r\n";
    $header2 .= "From: " . $from_name . " \r\n";
    $header2 .= "Return-Path: " . $from_mail . " \r\n";
    // $header2 .= 'Cc: ubonge80@gmail.com' . "\r\n";
    $header2 .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
    $header2 .= "$boundary\r\n";
    $getRespons = mail($mailto, $subject, $header, $header2, "-r" . $from_mail);
    if ($getRespons) {
        return true;
    } else {
        return "Not Sent";
    }
}

//#R020
function GetSchoolDegrees($param)
{

    global $dbo;
    //get all school degrees
    $deg = $dbo->Select("school_degrees_tb", "ID as DegID, Name as DegName");
    if (!is_array($deg)) Error(4);
    return $dbo->FetchAll($deg[0], MYSQLI_ASSOC);
}






//R025
function ClearAllSessions()
{
    $_SESSION = [];
    session_destroy();
    return 'true';
}

//R026
function GetSchoolSession($param = [])
{
    global $dbo;
    $ses = $dbo->SelectFirstRow("session_tb", "", "Enable=1 ORDER BY Current DESC, SesID DESC", MYSQLI_ASSOC);
    if (!is_array($ses)) {
        Error(9, " : No Academic Session Found");
    }
    return $ses;
}

function GetSessionName($SesID = 0)
{
    global $dbo;
    $ses = $dbo->SelectFirstRow("session_tb", "", "SesID=$SesID", MYSQLI_ASSOC);
    if (!is_array($ses)) {
        return "--";
    }
    return $ses['SesName'];
}
//Internal
function HasLogin(&$Param)
{
    session_start();
    if (!isset($Param['LoginName']) || trim($Param['LoginName']) == "") {
        if (isset($_SESSION['LoginName']) && trim($_SESSION['LoginName']) != "") {
            $Param['LoginName'] = $_SESSION['LoginName'];
        } else {
            Error(5);
        }
    }
}

//Internal
function GetStudentLevelSemesterWhenSchoolStart($RegNo)
{
    global $dbo;
    $lastLevel = $lastSem = 1;
    $sch = GetSchool("SchStartSes,SchStartSem");

    //use the school start ses to determin student lowest level
    $lastLevel = StudLevelSes($RegNo, $sch['SchStartSes']);
    //get the sem num
    $SchSemID = (int)$sch['SchStartSem'];
    if ($SchSemID > 0) {
        $semnum = $dbo->SelectFirstRow("semester_tb", "Num", "ID=$SchSemID");
        if (is_array($semnum) && (int)$semnum['Num'] > 0) {
            $lastSem = $semnum['Num'];
        }
    }
    return [(int)$lastLevel, (int)$lastSem];
}
//R027
function GetStudentLevelSemester($Param)
{
    global $dbo;
    HasLogin($Param);

    $studDet = $dbo->SelectFirstRow("studentinfo_tb", "OtherDet,StudyID,ModeOfEntry", "RegNo='" . $dbo->SqlSafe($Param['LoginName']) . "' OR JambNo='" . $dbo->SqlSafe($Param['LoginName']) . "'");
    if (!is_array($studDet)) Error(8);

    //get the last course registration
    $lstcreg = $dbo->SelectFirstRow("coursereg_tb", "Lvl,Sem", "RegNo='" . $dbo->SqlSafe($Param['LoginName']) . "' ORDER BY SesID DESC, Lvl DESC, Sem DESC", MYSQLI_ASSOC);
    //Error(8,json_encode($lstcreg));

    $maxsem = 2;
    //get the maximum semester number
    $semma = $dbo->SelectFirstRow("semester_tb", "count(ID)", "Enable = 1");
    if (is_array($semma)) {
        $maxsem = (int)$semma[0];
    }
    //$mofentryID = GetMOEID($studDet['ModeOfEntry']);
    $lastLevel = (int)GetMOEID($studDet['ModeOfEntry']);
    $lastSem = 1;
    //manage direct entry student

    if (is_array($lstcreg)) {

        //last det
        $lastLevel = $lstcreg['Lvl'];
        $lastSem = (int)$lstcreg['Sem'];
        if (!isset($Param['Current']) || $Param['Current'] != TRUE) { //get next

            /* if($lastSem > 1)$lastLevel++;
        $lastSem = ($lastSem > 1)?1:$lastSem++; */
            if ($lastSem >= $maxsem) {
                $lastLevel++;
                $lastSem = 1;
            } else {
                $lastSem++;
            }
        }
    } else {

        //get the degree starting
        $degreelvlseen = false;
        $OtherDet = $studDet['OtherDet'];
        if (trim($OtherDet) != "") {
            $OtherDet = json_decode($OtherDet, true);
            if (isset($OtherDet['Degree'])) {

                //get the degree details
                $degdet = $dbo->SelectFirstRow("school_degrees_tb", "", "ID=" . $OtherDet['Degree']);
                if (is_array($degdet)) {
                    $lastLevel = $degdet["StartLevel"];
                    $degreelvlseen = true;
                }
            }
        }

        if (!$degreelvlseen) {
            list($lastLevel, $lastSem) = GetStudentLevelSemesterWhenSchoolStart($Param['LoginName']);
            //Error("CE",$lastLevel);
        }
    }
    //get the student current Level details
   /*   $leveldet = $dbo->SelectFirstRow("schoollevel_tb", "*,coalesce(IF(Descr='',Name,Descr),Name) as LevelName, ID as LID,Level as LevelID", "Level=$lastLevel AND StudyID=" . $studDet['StudyID'], MYSQLI_ASSOC);
    if (!is_array($leveldet)) {
        $years = StudYearOfStudy($Param['LoginName']); //get the years of study
        $spill = $lastLevel - $years;
        if ($spill > 0) {
            $exyearst = ExtraLevelString();
            $leveldet = ["ID" => 0, "Level" => $lastLevel, "Name" => $exyearst . " " . $spill, "SchoolTypeID" => 1, "StudyID" => $studDet['StudyID'], "Descr" => $exyearst . " " . $spill, "LevelName" => $exyearst . " " . $spill, "LID" => 0, "LevelID" => $lastLevel];
        } else {
            Error(30);
        }
    } */ 
    $leveldet = GetLevelNameI($lastLevel,$studDet['StudyID'],$Param['LoginName']);
    //get the student semester det
    $semdet = $dbo->SelectFirstRow("semester_tb", "*, coalesce(IF(Descr='',Sem,Descr),Sem) as SemesterName, IF(Num=0,ID,Num) as SemID", "Num > 0 && Num=$lastSem", MYSQLI_ASSOC);
    if (!is_array($semdet)) Error(31);
    //(Num > 0 && Num={$Param['SemesterID']}) || ID={$Param['SemesterID']}
    return array_merge($leveldet, $semdet);
}


//R039
function GetStudentCurrentLevelSemester($Param)
{
    $Param['Current'] = TRUE;
    return GetStudentLevelSemester($Param);
}


//#R029
function OlevelGrades($Param)
{
    global $dbo;
    $facs = $dbo->Select("olvlgrade_tb");
    //Error(4,$studyid);
    if (!is_array($facs)) Error(4);
    return $dbo->FetchAll($facs[0], MYSQLI_ASSOC);
}

//#R030
function OlevelSubjects($Param)
{
    global $dbo;
    $facs = $dbo->Select("olvlsubj_tb");
    //Error(4,$studyid);
    if (!is_array($facs)) Error(4);
    return $dbo->FetchAll($facs[0], MYSQLI_ASSOC);
}



//get the level by its is (Internal)
function GetStudentLevelName($LvlID, $StudyID = 5, $ProgID=NULL)
{
    global $dbo;
    if(!is_null($ProgID)){
        $yearofSt = YearOfStudy($ProgID);
        if((int)$LvlID > (int)$yearofSt){//spill over
            $spill = $LvlID - $yearofSt;
        if ($spill > 0) {
            $exyearst = ExtraLevelString();
            return $exyearst . " " . $spill;
        }
        }
    }
    //get the student current Level details
    $leveldet = $dbo->SelectFirstRow("schoollevel_tb", "IF(Descr = '',Name,Descr) as LevelName", "Level=$LvlID AND StudyID=" . $StudyID, MYSQLI_ASSOC);
    if (!is_array($leveldet)) return "--";
    //return $LvlID."  ".$StudyID;
    return $leveldet['LevelName'];
}

//get the level by its is (Internal)
function GetStudentSemesterName($SemID)
{
    global $dbo;
    //get the student semester det
    // $semdet = $dbo->SelectFirstRow("semester_tb","IF(Descr='',Sem,Descr) as SemesterName","(Num > 0 && Num=$SemID) || ID=$SemID",MYSQLI_ASSOC);
    $semdet = $dbo->SelectFirstRow("semester_tb", "IF(Descr='',Sem,Descr) as SemesterName", "Num=$SemID", MYSQLI_ASSOC);
    if (!is_array($semdet)) return "Session";
    return $semdet['SemesterName'];
}






//get payment amt - R007
function GetPaymentAmt($Param)
{
    session_start();
    global $dbo;
    if (!isset($Param['PayID']) || (int)$Param['PayID'] == 0) Error(11);
    if (!isset($Param['LevelID']) || (int)$Param['LevelID'] == 0) $Param['LevelID'] = 1;
    if (!isset($Param['SemesterID']) || (int)$Param['SemesterID'] == 0) $Param['SemesterID'] = 1;
    if (!isset($Param['SemesterNum']) || (int)$Param['SemesterNum'] == 0) $Param['SemesterNum'] = 1;
    if (!isset($Param['SemesterPartID']) || (int)$Param['SemesterPartID'] == 0) $Param['SemesterPartID'] = 3;
    if (!isset($Param['PayDate']) || trim($Param['PayDate']) == "") $Param['PayDate'] = NULL;
    $studdet = [];
    if (!isset($Param['LoginName']) || trim($Param['LoginName']) == "") {
        //Error(5); 
        if (isset($_SESSION['LoginName']) && trim($_SESSION['LoginName']) != "") {
            $Param['LoginName'] = $_SESSION['LoginName'];
        } else {
            //Error(5);
        }
    }

    if (isset($Param['LoginName']) && trim($Param['LoginName']) != "") {

        // $studdet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='".$dbo->SqlSafe($Param['LoginName'])."' OR JambNo='".$dbo->SqlSafe($Param['LoginName'])."'",MYSQLI_ASSOC);
        if (isset($Param['StudentDetails']) && count($Param['StudentDetails']) > 0) {
            $studdet =  $Param['StudentDetails'];
            if(isset($studdet['OtherDet'])){
                $otherdet = json_decode($studdet['OtherDet'],true);
                if(is_array($otherdet))$studdet = array_merge($studdet,$otherdet);
            }    
        } else {
            $studdet = GetBasicInfo($Param['LoginName'], "", "a", 1, MYSQLI_ASSOC);
            //    if(!is_array($studdet))Error(8);
            if (is_array($studdet)) {
                if (trim($studdet['OtherDet']) != "") {
                    $studdet = array_merge($studdet, json_decode($studdet['OtherDet'], true));
                }
            } else { //if student details not exist remove from session
                unset($_SESSION['LoginName']);
            }
        }
    }

    //get the payment breakdown from db
    if (isset($Param["PayDetails"])) {
        $paydet = $Param["PayDetails"];
    } else {
        $paydet = $dbo->SelectFirstRow("item_tb", "ID as PayID, ItemName as PayName, ItemDescr as PayDescr, PayBrkDn as BreakDown,PayOption", "ID=" . $Param['PayID'] . " LIMIT 1", MYSQLI_ASSOC);
    }

    if (!is_array($paydet)) Error(46);
    // if($Param['PayID'] == 6)Error(4, json_encode([$Param['LevelID'], $Param['SemesterID'], $studdet, $Param['SemesterPartID']]));
    $paybrd = PaymentBreakDown($paydet['BreakDown'], $Param['LevelID'], $Param['SemesterID'], $studdet, $Param['SemesterPartID']);
    if (!is_array($paybrd)) Error(12);
    return ["Amount" => $paybrd[0], "FAmount" => $paybrd[1], "StudentDetails" => $studdet, "PayDetails" => $paydet];
}



//R046
//Check if Entrance module is enabled
function Entrance($Param)
{
    global $dbo;
    
    
    //check if entrance id isset
    $EntrContrID = (isset($Param["EntranceID"]) && (int)$Param["EntranceID"] > 0) ? $Param["EntranceID"] : 1;
    $entrancedet = $dbo->SelectFirstRow("putme", "", "ID=" . $EntrContrID, MYSQLI_ASSOC);
    
    if (!is_array($entrancedet)) Error(52);
    
    if ((!isset($Param['IgnoreStatus']) || (int)$Param['IgnoreStatus'] != 1) && $entrancedet['Status'] == "CLOSED") Error(53, '<br/>' . $entrancedet['Title']);
    $VerDisStrArr = ["STUDENT" => "Entrance Number", "PHONE" => "Phone Number"];
    $otherparam = $entrancedet['Param'];//EntranceNumLabel
    if(trim($otherparam) != ""){
        $paramobj = json_decode($otherparam,true);
        if(!is_null($paramobj) && isset($paramobj['EntranceNumLabel']))$VerDisStrArr['STUDENT'] = $paramobj['EntranceNumLabel'];
    }


    //return ["in"=>$entrancedet];
    $entrancedet['VerDisStr2'] = $entrancedet['Verify'] == "PHONE" ? "Enter the last six(6) digit of your Phone Number" : "Enter the verification code sent to you";
    $entrancedet['isphoneonly'] = $entrancedet['Verify'] == "PHONE" ? "_" : "";
    $entrancedet['VerDisStr'] = isset($VerDisStrArr[$entrancedet['Verify']]) ? $VerDisStrArr[$entrancedet['Verify']] : "Phone Number or Email Address";
    $entrancedet['NewEmail'] = $entrancedet['Verify'] == "STUDENT" ? "_" : "";

    //$entrancedet['AllowCreateEmail'] =  $entrancedet['Verify'] == "STUDENT" ? [] : [1];
    //Error("CE", json_encode($entrancedet));
    return array_merge($entrancedet, $Param);
}




//Internal Modul
//Redirect Apply Page
function RedirectTo($pageNum = 1, $Alert = "")
{
    $rtn = ["PageNum" => $pageNum];
    if (trim($Alert) != "") {
        $rtn["__Alert__"] = $Alert;
    }
    return $rtn;
}


//R054
function ChangeEntranceVerField($Param)
{
    //Error(2);
    return $Param;
}

//Resize Image Using the Image LB
function ResizeImage($imagepth, $width, $height)
{
    global $dbo;
    //include the image resize lib
    if (!file_exists("../../../../" . $dbo->Config['SubDir'] . $dbo->Config['Require'] . "Image/image.php")) Error("CE", "Image Proccessor Not Found");
    require_once "../../../../" . $dbo->Config['SubDir'] . $dbo->Config['Require'] . "Image/image.php";
    //get the image size
    list($iwidth, $iheight, $type, $attr) = getimagesize($imagepth);
    if ($iwidth <= $width) return;
    $magicianObj = new imageLib($imagepth);
  
    //return $magicianObj->resizeImage($width, $height, 'landscape', true);
    $magicianObj->resizeImage($width, $height, 'landscape', true);
    
    $magicianObj->saveImage($imagepth, 100);
}

//Auto calculate dimention
function AutoFitInto($padW, $padH, $width, $height, $margin = 0)
{
    $orientation = "";
    $Ratio = $width / $height;
    //determin if its landscape or portraite
    if ($height > $width) {
        $orientation = "p";
        //check if height is greater than pad hight
        if ($height >= $padH) {
            $height = $padH - $margin;
            //calculate new width
            $width = floor($Ratio * $height);
        }
        if ($width >= $padW) {
            $width = $padW - $margin;
            //calculate new width
            $height = floor($width / $Ratio);
        }
    } else if ($width > $height) {
        $orientation = "l";
        //check if width is greater than pad width
        if ($width >= $padW) {
            $width = $padW - $margin;
            //claculate $height
            $height = floor($width / $Ratio);
        }

        if ($height >= $padH) {
            $height = $padH - $margin;
            //calculate new width
            $width = floor($Ratio * $height);
        }
    }
    //if square
    if ($orientation == "") {
        //$style = GetValue("style",$atrrValStr);
        if ($height >= $padH) {
            $height = $padH - $margin;
            //calculate new width
            $width = $height;
        }

        if ($width >= $padW) {
            $width = $padW - $margin;
            $height = $width;
        }
    }
    return array($width, $height, $orientation);
}





//Internal
//Prepare Mail Message
function MailMessage(&$msg = "", $Data = [], $markup = "", $dir = "")
{
    global $dbo;
    global $Param;
    $dir = $dir == "" ? $Param['Dir'] : $dir;
    if (trim($markup) != "") {
        $lookup = "../../Pages/" . $dir;
        if (file_exists("../../../../" . $dbo->Config["SubDir"] . "Pages/" . $dir . "/" . $markup)) $lookup = "../../../../" . $dbo->Config["SubDir"] . "Pages/" . $dir;
        if (file_exists($lookup . "/" . $markup)) {
            $msg = file_get_contents($lookup . $dir . "/" . $markup);
        }
    }

    if ($msg != "") {
        if (count($Data) > 0) {
            foreach ($Data as $key => $val) {
                $msg = str_replace("{{" . $key . "}}", $val, $msg);
            }
        }
        /* $msg = str_replace(["{{Logo}}","{{SchoolName}}","{{ApplEmail}}","{{VerPin}}","{{Abbr}}","{{SubDir}}","{{Core}}","{{Dir}}"],[$dbo->Config["SubDir2"]."Files/".$sch['logo'],$sch['Name'],$Param['RegNo_Appl'],$VeriNum,$sch['Abbr'],$dbo->Config['SubDir2'],$dbo->Config['Core2'],$Param['Dir']],$msg); */
    }
    return $msg;
}


//Get all levels - R058
function GetAllLevels($Param)
{

    // Error(4,$Param['ProgID']);
    global $dbo;
    $studycond = (isset($Param['StudyID']) && (int)$Param['StudyID'] > 0) ? "StudyID=" . $dbo->SqlSafe($Param['StudyID']) : "1=1";
    $facs = $dbo->Select("schoollevel_tb", "Level as LevelID,Descr as LevelName", $studycond);
    //Error(4,$studyid);
    if (!is_array($facs)) Error(4);

    return $dbo->FetchAll($facs[0], MYSQLI_ASSOC);
}

//Get all classes by progid - R059
function GetClassByProg($Param)
{
    global $dbo;
    if (!isset($Param['ProgID']) || (int)$Param['ProgID'] < 1) Error(11);
    $ProgID = $Param['ProgID'];
    $clases = $dbo->Select("studentclass_tb", "", "ProgID=" . $dbo->SqlSafe($ProgID));
    if (!is_array($clases)) Error(4);
    return $dbo->FetchAll($clases[0], MYSQLI_ASSOC);
}

function IsAccountActive($Param)
{
}

//R073
function GetCountries($param=[]){
    global $dbo;
      //select all
      $cnt = $dbo->Select("new_country_tb","ID as CID, Name as CName");
    //   Error(4," jjj");
      if(!is_array($cnt))Error(4);
      return $dbo->FetchAll($cnt[0],MYSQLI_ASSOC);
    
}

//R074
function GetStates($param=[]){
    global $dbo;
    if(!isset($param['CID']))Error(0);
      //select all
      $cnt = $dbo->Select("new_states_tb","ID as SID, Name as SName","CountryID=".$param['CID']);
    //   Error(4," jjj");
      if(!is_array($cnt))Error(4);
      return $dbo->FetchAll($cnt[0],MYSQLI_ASSOC);
    
}


