<?php


//Get Local government - R013
function SaveCandidate($Param)
{
    session_start();
    Underscored($Param);
    $RegNo = "";
    /* if(!isset($_SESSION['RegNo']) || trim($_SESSION['RegNo']) == ""){ 
         if(!isset($Param['RegNo']) || trim($Param['RegNo']) == "")Error(11);
         $_SESSION['RegNo'] = $Param['RegNo'];
     }else{
         $Param['RegNo'] = $_SESSION['RegNo'];
     } */


   
    if (!isset($Param['RegNo']) || trim($Param['RegNo']) == "") {
        if (!isset($Param['RegNo_Appl']) || trim($Param['RegNo_Appl']) == "") Error(11);
        $RegNo = $Param['RegNo_Appl'];
    } else {
        $RegNo = $Param['RegNo'];
    }
    $rst = SaveCandidateReal($RegNo, $Param);
    if ($rst === true) {
        // $_SESSION['RegNo'] = $Param['RegNo'];

        return $Param;
    }
    Error(11, " : " . $rst);
}

//Private - Form Cand Queary
function SaveCandidateReal($RegNo, $Data)
{
    $entrancedet = Entrance($Data);

    $dbtbpre = $entrancedet['StudInfoPref'];
    $otherparam = trim($entrancedet['Param']);
    if ($otherparam != "") {
        $otherparamdet = json_decode($otherparam, true);
        if (isset($otherparamdet['FileDir']) && trim($otherparamdet['FileDir']) != "") $Data['FileDir'] = $otherparamdet['FileDir'];
    }
    global $dbo;
    global $Fields;
    $FileDir = isset($Data['FileDir']) && trim($Data['FileDir']) != "" ? $Data['FileDir'] : "PUTME";
    if (!isset($RegNo)) Error(15);
    //confirm if candidate already exist
    $CRegNo = $dbo->SqlSafe($RegNo);
    $cand = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "", "RegNo = '$CRegNo' OR JambNo = '$CRegNo'", MYSQLI_ASSOC);
    $Otherdet = [];
    $exist = false;
    if (is_array($cand)) {
        $exist = true;
        //exist
        //get the other details
        $Otherdet = (trim($cand['OtherDet']) != '') ? json_decode($cand['OtherDet'], true) : [];
    } else {
        $cand = [];
        //get all the field name
        $columns = $dbo->RunQuery("SHOW COLUMNS FROM {$dbtbpre}studentinfo_tb");
        while ($indcol = $columns[0]->fetch_assoc()) {
            if ($indcol['Field'] == "id") continue;
            if ($indcol['Type'] == "date") {
                $cand[$indcol['Field']] = date("Y-m-d");
            } elseif (substr($indcol['Type'], 0, 4) == "int(") {
                $cand[$indcol['Field']] = 0;
            } else {
                $cand[$indcol['Field']] = "";
            }
        }
        //not exist
    }
    // Error(11," : ".json_encode($cand));
    //package all data as required
    if (!is_array($Data)) Error(11);
    $candData = [];
    $cand['RegDate'] = date('Y-m-d');

    foreach ($Data as $UField => $Udata) {
        $UFieldarr = explode("_", $UField);
        $RealField = "";
        if (count($UFieldarr) > 1) {
            array_pop($UFieldarr);
            $RealField = implode("_", $UFieldarr);
        } else {
            $RealField = $UFieldarr[0];
        }

        //$candData[] = $RealField;
        $RealField = isset($Fields[$RealField]) ? $Fields[$RealField] : $RealField;
        //$candData = [];
        switch ($RealField) {
            case "Credentials":
                $filename = str_replace(array("/", '\\'), "_", $RegNo . "_credential");
                /* if(file_exists("../../../../".$dbo->Config['SubDir'].$dbo->Config['Require']."Image/")){
        Error(53," - ../../../../".$dbo->Config['SubDir'].$dbo->Config['Require']."Image/ : EXIST");
    }else{
        Error(53," - ../../../../".$dbo->Config['SubDir'].$dbo->Config['Require']."Image/ : NOT EXIST");
    } */
                //try uploading passport
                $rst = Uploader("../../../../" . $dbo->Config['SubDir'] . "Files/UserImages/$FileDir/", $UField, $filename);

                //Error(17," ".json_encode($rst));
                if (count($rst["Failed"]) > 0) Error(17, " : " . $rst["Failed"][$UField]);
                $Otherdet["Credentials"] = $rst["Success"][$UField];
                break;
            case "OtherCredentials":
                $filename = str_replace(array("/", '\\'), "_", $RegNo . "_other_credential");
                //
                //try uploading passport
                $rst = Uploader("../../epconfig/UserImages/$FileDir/", $UField, $filename);
                //Error(17," ".json_encode($rst));
                if (count($rst["Failed"]) > 0) Error(17, " : " . $rst["Failed"][$UField]);
                $Otherdet["OtherCredentials"] = $rst["Success"][$UField];
                break;
            case "Passport":
            case "Passport_Appl":

                $filename = str_replace(array("/", '\\'), "_", $RegNo);

                //try uploading passport
                $rst = Uploader("../../../../" . $dbo->Config['SubDir'] . "Files/UserImages/$FileDir/", $UField, $filename);
                //Error(17," ".json_encode($rst));
                if (count($rst["Failed"]) > 0) Error(17, " : " . $rst["Failed"][$UField]);
                if (isset($rst["Success"][$UField])) {

                    $parr = explode('/UserImages/', $rst["Success"][$UField]);
                    //resize image
                    $newimg = ResizeImage($rst["Success"][$UField], 300, 300);
                    $cand['Passport'] = count($parr) == 2 ? "UserImages/" . $parr[1] : $rst["Success"][$UField];
                }
                //$cand['Passport'] = substr($rst["Success"][$UField],3);
                break;
            case "FullName":
                //check if full name then break
                $CNames = explode(" ", $Udata);
                $cand['SurName'] = trim($CNames[0]);
                $cand['FirstName'] = trim($CNames[1]);
                $CNames[0] = "";
                $CNames[1] = "";
                $cand['OtherNames'] = trim(implode(" ", $CNames));
                break;
            case "LevelID":
                //Error("CE",$Udata);
                $StartSes = GetStartSesByLevel($Udata);
                $cand['StartSes'] = $StartSes;
                break;
            case "DOB":
                $cand['DOB'] = MysqlDateEncode($Udata);

                break;
            case "RegDate":
                $cand['RegDate'] = MysqlDateEncode($Udata);
                break;
            case "AdminDate":
                $cand['AdminDate'] = MysqlDateEncode($Udata);
                break;
            case "GenderMale":
                $cand['Gender'] =  ((int)$Udata == 1) ? "M" : "F";
                // $candData[] = $UField;
                break;
            case "StatusMarried":
                $cand['MaritalStatus'] =  ((int)$Udata == 1) ? "M" : "S";
                break;
            default:
                if (array_key_exists($RealField, $cand)) {
                    // if(isset($cand[$UFieldarr[0]]) || is_null($cand[$UFieldarr[0]])){
                    //array_key_exists
                    $cand[$RealField] = $Udata;
                    //$candData[] = $UFieldarr[0];

                } else {
                    if (trim($RealField) != "") $Otherdet[$RealField] = $Udata;
                    //Error(11,$UFieldarr[0]);
                }
        }
    }
    //Error(11," : ".json_encode($cand));
    $cand['OtherDet'] = json_encode($Otherdet);
    $sqlmd = $dbo->RunQuery("set @@sql_mode=''");
    if ($exist) {
        $upd = $dbo->Update("{$dbtbpre}studentinfo_tb", $cand, "id=" . $cand['id']);
        if (is_array($upd)) {
            return true;
        } else {
            return $upd;
        }
    } else {
        $ins = $dbo->Insert("{$dbtbpre}studentinfo_tb", $cand);
        if ($ins == "#") {
            return true;
        } else {
            return $ins;
        }
    }
}



//create a unique record entering - R016
function CreateUniqueRecord($Param)
{
    Underscored($Param);
    MapData($Param);
    $genPagesDir = "../../";
    $customPagesDir = "../../../../".$Param['__SubDir__'];
    $Param['Mail'] = file_exists($customPagesDir.$Param['Mail'])?$customPagesDir.$Param['Mail']:$genPagesDir.$Param['Mail'];
    //Error(11,' - '.$Param['Mail']);
    //Param - {UniqueName:['uname'],UniqueKey:[''],UniqueDetail:['']}
    global $dbo;
    if (!isset($Param['UniqueName']) || (is_string($Param['UniqueName']) && trim($Param['UniqueName']) == "") || (is_array($Param['UniqueName']) && count($Param['UniqueName']) < 1)) Error(11);
    if (!isset($Param['UniqueKey'])) $Param['UniqueKey'] = "";
    if (!isset($Param['UniqueDetails'])) $Param['UniqueDetails'] = "";
    //check for multiple UniqueName
    $Param['UniqueName'] = is_array($Param['UniqueName']) ? $Param['UniqueName'] : [$Param['UniqueName']];
    $Param['UniqueKey'] = is_array($Param['UniqueKey']) ? $Param['UniqueKey'] : [$Param['UniqueKey']]; //
    $Param['UniqueDetails'] = is_array($Param['UniqueDetails']) ? $Param['UniqueDetails'] : [$Param['UniqueDetails']];
    $Param['OtherInfo'] = is_array($Param['OtherInfo']) ? $Param['OtherInfo'] : [$Param['OtherInfo']];
    $UniqueEntry = [];

    foreach ($Param['UniqueName'] as $key => $uniquename) {
        if (trim($uniquename) == "") continue;
        //check if unique name already exist
        $uname = $dbo->SelectFirstRow("unique_tb", "", "UniqueName='$uniquename'");
        if (is_array($uname)) {
            $UniqueEntry[] = $uname;
            continue;
        }
        //get other details
        $uniquekey = isset($Param['UniqueKey'][$key]) ? $Param['UniqueKey'][$key] : "";
        if (trim($uniquekey) == "") { //if not set generate random value
            do {
                $uniquekey = $dbo->GenerateString(10, 10, " /\\&=?~`!@#$%^*()-+{}[]:;\"'<>,.");
            } while (is_array($dbo->SelectFirstRow("unique_tb", "", "UniqueKey='$uniquekey'")));
        } else {
            //check if already exist
            $exist = $dbo->SelectFirstRow("unique_tb", "", "UniqueKey='$uniquekey'");
            if (is_array($exist)) Error(18);
        }
        $uniquedet = isset($Param['UniqueDetails'][$key]) ? $Param['UniqueDetails'][$key] : $Param['UniqueDetails'][0];
        if (is_array($uniquedet)) $uniquedet = json_encode($uniquedet);
        $otherinfo = isset($Param['OtherInfo'][$key]) ? $Param['OtherInfo'][$key] : $Param['OtherInfo'][0];
        if (is_array($otherinfo)) $otherinfo = json_encode($otherinfo);
        //insert into database
        $inst = $dbo->Insert("unique_tb", ["UniqueName" => $uniquename, "UniqueKey" => $uniquekey, "UniqueDetails" => $uniquedet, "OtherInfo" => $otherinfo, "OnlineInfo" => '{}']);
        if ($inst == "#") {
            $UniqueEntry[] = ["UniqueName" => $uniquename, "UniqueKey" => $uniquekey, "UniqueDetails" => $uniquedet, "OtherInfo" => $otherinfo];

            if (isset($Param['SendMailUnique']) && (int)$Param['SendMailUnique'] > 0 && isset($Param['Mail']) && isset($Param['ToAddress'])) {
                $TAdress = is_array($Param['ToAddress']) ? $Param['ToAddress'][$key] : $Param['ToAddress'];
                $Mail = $Param['Mail'];
                $FName = isset($Param['FromName']) ? $Param['FromName'] : "";
                $Subject = isset($Param['Subject']) ? $Param['Subject'] : "";
                $mailparam = array_merge($Param, ["Mail" => $Mail, "ToAddress" => $TAdress, "FromName" => $FName, "Subject" => $Subject, "UniqueName" => $uniquename, "UniqueKey" => $uniquekey, "UniqueDetails" => $uniquedet, "OtherInfo" => $otherinfo, "OnlineInfo" => '{}']);
                $mailparam["UniqueName"] = $uniquename;

                $sends = SendMail($mailparam);
                if ($sends !== true) {
                    // Error();
                }
            }
        } else {
            //Error(18," : ".$inst);
        }
    }

    return $UniqueEntry;
}

//check a unique record entering - R017
function CheckUniqueEntry($Param)
{
    Underscored($Param);
    MapData($Param);
    global $dbo;
    if (!isset($Param['UniqueName']) || trim($Param['UniqueName']) == "" || !isset($Param['UniqueKey']) || trim($Param['UniqueKey']) == "") Error(11);
    $UniqueName = $dbo->SqlSafe($Param['UniqueName']);
    $UniqueKey = $dbo->SqlSafe($Param['UniqueKey']);
    //get the unique details
    $udet = $dbo->SelectFirstRow("unique_tb", "", "UniqueName='$UniqueName' AND UniqueKey='$UniqueKey'", MYSQLI_ASSOC);
    if (!is_array($udet)) Error(19);
    if ((int)$udet["Enable"] == 0) Error(20);
    $udet["OnlineInfo"] = is_null($udet["OnlineInfo"]) ? [] : json_decode($udet["OnlineInfo"], true);
    return $udet;
}

//update unique details - R018
function UpdateUniqueEntry($Param)
{
    Underscored($Param);
    MapData($Param);
    if (!isset($Param['UniqueID']) || (int)$Param['UniqueID'] == 0) Error(11);
    global $dbo;
    //get the unique details
    $undet = $dbo->SelectFirstRow("unique_tb", "UniqueName,UniqueKey,UniqueDetails,OtherInfo,OnlineInfo,Enable", "UniqueID=" . $dbo->SqlSafe($Param['UniqueID']), MYSQLI_ASSOC);
    if (!is_array($undet)) Error(19);
    $OnlineInfo = json_decode($undet['OnlineInfo'], true);
    //loop through all param and update as required
    foreach ($Param as $Pkey => $PVal) {
        if (isset($undet[$Pkey])) {
            $undet[$Pkey] = $PVal;
        } else {
            $OnlineInfo[$Pkey] = $PVal;
        }
    }
    $undet['OnlineInfo'] = json_encode($OnlineInfo);

    //run update
    $upd = $dbo->Update("unique_tb", $undet, "UniqueID=" . $dbo->SqlSafe($Param['UniqueID']));
    if (is_array($upd)) {
        return array_merge($undet, $OnlineInfo);
    } else {
        Error(4, " : " . $upd);
    }
}

//#R021
function VerifyCandidate($Param)
{
    //Error(11);
    Underscored($Param);
    global $__Root__;
  /*   $entrancedet = Entrance($Param);
    $dbtbpre = $entrancedet['StudInfoPref']; */
    if (!isset($Param['RegNo']) || trim($Param['RegNo']) == "") {
        if (!isset($Param['JambNo']) || trim($Param['JambNo']) == "") {
            Error(11);
        } else {
            $Param['RegNo'] = $Param['JambNo'];
        }
    }
    global $dbo;
    //get candidate from student info
    $cand = $dbo->SelectFirstRow("pstudentinfo_tb", "", "RegNo='" . trim($dbo->SqlSafe($Param['RegNo'])) . "' OR JambNo='" . trim($dbo->SqlSafe($Param['RegNo'])) . "'", MYSQLI_ASSOC);
    if (!is_array($cand)) Error(23); //candidate doesnot exist
    if ((int)$cand['RegLevel'] < 6) Error(24); //incomplete application
    if ((int)$cand['admitted'] < 1) Error(25); //Candidate Not Yet Admitted

    //check if account already created
    $stud = $dbo->SelectFirstRow("studentinfo_tb", "", "RegNo='" . trim($dbo->SqlSafe($Param['RegNo'])) . "' OR JambNo='" . trim($dbo->SqlSafe($Param['RegNo'])) . "'");
    if (is_array($stud)) {
        if (trim($stud['RegNo']) == "") $stud['RegNo'] = $stud['JambNo'];
        //confirm access code
        $accesscode = $dbo->SelectFirstRow("accesscode_tb", "", "JambNo='" . $stud['RegNo'] . "' OR JambNo = '" . $stud['JambNo'] . "'");
        if (is_array($accesscode)) {
            // Error(0,json_encode($accesscode));
            $cand["NRegNo"] = $accesscode['JambNo'];
            $cand["NextPageNum"] = 4;
            $rdata = "{Src:'{$__Root__}general/Slip.php?regno=" . urlencode($accesscode['JambNo']) . "&folder=Form&SubDir=" . urlencode($dbo->Config['SubDir']) . "',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
            $cand["NRedirectData"] = $rdata;
            $ardata = "{Src:'{$__Root__}general/Slip.php?RegNo=" . urlencode($accesscode['JambNo']) . "&folder=AcceptLetter&SubDir=" . urlencode($dbo->Config['SubDir']) . "',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
            $cand["ARedirectData"] = $ardata;
            return $cand;
            //Error(26); //Student Account Already Created
        }
    }
    //Error(23);
    //check if payment ordered
    //$cand = $dbo->SelectFirstRow("order_tb","","");
    if ((int)$cand['Accept'] == 1) {
        $cand["NextPageNum"] = 3;
        return $cand;
    }
    return $cand;




    // return ["NextPageNum"=>4];
}


//#R023
function CandidateToStudent($Param)
{
    //Error(0,": ");
    global $__Root__;
    //Error(23,json_encode($Param));
    /* $RegNo = $Param['RegNo'];
    $rd ="Slip.php?regno=".$RegNo."&folder=Form&paper=A4&orientation=P&MT=4&MB=30";
    // $canddet["RedirectURL"] = $rd;
     $rdata = "{Src:'Slip.php?regno={$RegNo}&folder=Form',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
     return ["NextPageNum"=>4,"RegNo"=>$RegNo,"RedirectURL"=>$rd,"RedirectData"=>$rdata]; */

    $vercand = VerifyCandidate($Param); //verify candidate


    if ($vercand["NextPageNum"] == 3) { //if verified successfully

        Underscored($Param);
        //if(!isset($Param['RegNo']) || trim($Param['RegNo']) == "")Error(11);
        global $dbo;

        //2. create candidate details in studinfo
        //get the structure of student info
        //$upcand = [];
        $existinstudinfo = 0; //candidate already exist in studentinfo_tb
        //get candidate detials incase already migrated manually to studentinfo_tb
        $upcand = $dbo->SelectFirstRow("studentinfo_tb", "", "RegNo = '" . $dbo->SqlSafe($Param['RegNo']) . "' OR JambNo = '" . $dbo->SqlSafe($Param['RegNo']) . "'", MYSQLI_ASSOC);
        if (!is_array($upcand)) { //if does not exist
            $upcand = [];
            //get all the field name
            $columns = $dbo->RunQuery("SHOW COLUMNS FROM studentinfo_tb");
            while ($indcol = $columns[0]->fetch_assoc()) {
                if ($indcol['Field'] == "id") continue;
                if ($indcol['Field'] == "RegNo") {
                    $upcand['RegNo'] = "";
                    continue;
                }
                if ($indcol['Field'] == "JambNo") {
                    $upcand['JambNo'] = $Param['RegNo']; //use what user entered (email or Phone)
                    continue;
                }
                if ($indcol['Field'] == "RegDate") $vercand[$indcol['Field']] = date('Y-m-d');
                if ($indcol['Field'] == "AutoGenReg") $vercand[$indcol['Field']] = 'FALSE';
                if ($indcol['Field'] == "AutoNum") $vercand[$indcol['Field']] = 0;
                /*  if($indcol['Field'] == "ClassID"){
                //add student to a class
                $vercand[$indcol['Field']] = 1;
            } */
                if (isset($vercand[$indcol['Field']])) {
                    $upcand[$indcol['Field']] = $vercand[$indcol['Field']];
                } else {
                    $upcand[$indcol['Field']] = '';
                }
            }
        } else {
            $upcand['RegDate'] = date('Y-m-d');
            $existinstudinfo = (int)$upcand['id'];
        }



        $JambNo = $upcand['JambNo'];
        /* Verification Type: FN- generate form number, JN - Preload JambNo(RegNo), PU - Preload JambNo and check entr Result, RN - JambNo but not Preload */
        $VType = "FN";
        if (isset($Param['FormID'])) {
            //get the form details
            $formcntr = $dbo->SelectFirstRow("form_tb", "", "ID=" . $Param['FormID']);
            if (is_array($formcntr)) {
                $VType = $formcntr['Type'];
            }
        }
        if ($VType == "FN") {
            //generate jambno
            //Use Random number instead of phone number
            do {
                //generate a random number
                $JambNo = strtoupper(substr($upcand['SurName'], 0, 2)) . mt_rand(100000, 999999);
                $chk = $dbo->SelectFirstRow("studentinfo_tb", "id", "RegNo='" . $dbo->SqlSafe($JambNo) . "' OR JambNo='" . $dbo->SqlSafe($JambNo) . "'");
            } while (is_array($chk));
        }

        if ($upcand['JambNo'] != $JambNo) {
            //update JambNo
            foreach (["order_tb", "payhistory_tb"] as $uptb) {
                $up = $dbo->Update($uptb, ["RegNo" => $JambNo], "RegNo='{$upcand['JambNo']}'");
            }
            $upcand['JambNo'] = $JambNo;
        }





        $currSes = CurrentSes();
        //$upcand['StartSes'] = $currSes['SesID'];
        //clean data
        if ((int)$upcand['StartSes'] == 0) {
            // $currSes = CurrentSes();
            $upcand['StartSes'] = $currSes['SesID'];
        }

        $progid = (int)$upcand['ProgID'];

        if ((int)$upcand['StudyID'] == 0) {
            //get the progid

            $facdet = $dbo->RunQuery("SELECT f.StudyID FROM fac_tb f, dept_tb d, programme_tb p WHERE f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = $progid");

            //Error("CE",$ClassID);
            if (is_array($facdet)) {
                $facrdet = $facdet[0]->fetch_assoc();
                $upcand['StudyID'] = $facrdet['StudyID'];
            }
        }

        $ClassID = (int)$upcand['ClassID'];
        if ($ClassID < 1) {
            //Add Student to Class
            //***************************
            //get the total already registered in the class
            $toreg = $dbo->SelectFirstRow("studentinfo_tb", "COUNT(id) as Tot", "ProgID=$progid AND StartSes={$upcand['StartSes']} AND RegLevel >= 6");

            if (is_array($toreg)) {
                $toreg['Tot'] = (int)$toreg['Tot'];
                //get total all the available classes
                $clases = $dbo->Select("studentclass_tb", "ID,Capacity", "ProgID=$progid");

                if (is_array($clases) && $clases[1] > 0) { //if clases exist
                    //get all calses
                    while ($indclass = $clases[0]->fetch_assoc()) {
                        $capaci = (int)$indclass['Capacity'];

                        $ClassID = $indclass['ID'];
                        if ((int)$toreg['Tot'] < $capaci) { // if  space available

                            break;
                        } else {
                            $toreg['Tot'] = $toreg['Tot'] - $capaci;
                            //$ClassID
                        }
                    }
                }
            }
            $upcand['ClassID'] = $ClassID;
            //***************************   
        }

        if ((int)$upcand['RegID'] == 0) $upcand['RegID'] = 1;
        if ((int)$upcand['AdmSes'] == 0) $upcand['AdmSes'] = $currSes['SesID'];
        if ((int)$upcand['ModeOfEntry'] == 0) $upcand['ModeOfEntry'] = "1";

        if ($existinstudinfo == 0) {
            //insert
            $ins = $dbo->InsertID2("studentinfo_tb", $upcand);
            if (!is_numeric($ins)) Error(28, "-" . $ins);
        } else {
            $ins = $dbo->Update("studentinfo_tb", $upcand, "id=" . $existinstudinfo);
            if (!is_array($ins)) Error(28, "-" . $ins);
            $ins = $existinstudinfo;
        }


        //4. create candidate details in accesscode
        //generate accesscode
        // $acccode = FormAC();
        $hasaccesscode = "";
        if ($existinstudinfo > 0) {
            $hasaccesscode = $dbo->SelectFirstRow("accesscode_tb", "AccessCode", "JambNo='" . $dbo->SqlSafe($JambNo) . "' LIMIT 1", MYSQLI_ASSOC);
        }
        if (!is_array($hasaccesscode)) {
            $acccode = "myschool";
            $ins2 = $dbo->InsertID2("accesscode_tb", ["RegNo" => "", "JambNo" => $JambNo, "AccessCode" => $acccode, "RegID" => $upcand['RegID']]);
            if (!is_numeric($ins2)) {
                $del = $dbo->Delete("studentinfo_tb", "id=" . $ins);
                Error(28, ": Generating Accesscode Failed");
            }
        } else {
            $acccode = $hasaccesscode['AccessCode'];
        }


        //5. Generate New RegNo and Update as required
        //get the sch settngs for regno generaton
        $sch = $dbo->SelectFirstRow('school_tb');
        if (isset($sch['AutoRegNoTrigger']) && $sch['AutoRegNoTrigger'] == "STUDACCOUNT") {
            $autoreg = AutoGenRegNo($JambNo, $upcand['RegID']);
            if (!is_array($autoreg) &&  $autoreg != "##") {
                Error(29, $autoreg);
            }
            $NewRegNo = is_array($autoreg) ? $autoreg[0] : $JambNo;
        } else {
            $NewRegNo = $JambNo;
        }





        $mailparam = array_merge($Param, ["ToAddress" => $upcand['Email'], "AC" => $acccode, "Optional" => true], $upcand);
        $mailparam["RegNo"] = $NewRegNo;
        //$sch = GetSchool();
        $MailData = [
            "Logo" => $dbo->Config["SubDir2"] . "Files/" . $sch['logo'],
            "SchoolName" => $sch['Name'],
            "SchoolAbbr" => $sch['Abbr'],
            "SurName" => $upcand['SurName'],
            "FirstName" => $upcand['FirstName'],
            "OtherNames" => $upcand['OtherNames'],
            "RegNo" => $JambNo,
            "AC" => $acccode,
            "BrandLogo" => $dbo->Config['Core2'] . "images/App/Images/eduporta.png"
        ];
        $dir = (isset($Param['Dir']) && trim($Param['Dir']) != "") ? $Param['Dir'] : "Apply/Account";
        $msg = '<div style="background-color: #eee; width:100%; height: auto; padding: 20px;font-family: \'Encode Sans Condensed\',\'Milo\',\'Open Sans\',sans-serif;">
            <div
                style="width:calc(100% - 30px); max-width:500px; min-height:400px; background-color:#fff; margin:auto; border-radius:10px; box-shadow:0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);">
                <div
                    style="border-radius:10px 10px 0px 0px;min-height: 40px; width: 100%;background-color:rgb(15, 133, 35);box-shadow:0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);">
                    <img style="height: 50px; display:inline-block; margin:10px 20px; vertical-align: middle"
                        src="{{Logo}}" /> <span
                        style="vertical-align:middle; display:inline-block; margin:10px 0px; font-size:1.3em; color:#fff">{{SchoolName}} <br/><span style="font-size:0.7em">Student Portal Account</span></span>
                </div>
    
                <div style="padding:20px">
                    <p>Congratulations <b>{{SurName}} {{FirstName}} {{OtherNames}}</b>,</p>
                       <p> Your {{SchoolAbbr}} Student Portal Account is created successfully</p>
                       <p>Your Username is</p>
                       <h1>{{RegNo}}</h1>
                       <p>Portal Access Code: <b style="color:red">{{AC}}</b></p>
                           
                        <p>Login to your {{SchoolAbbr}} Desk as follows:</p>
    
                       <ul>
    <!-- <li>Visit <a href="{{__Root__}}portals" target="_new">{{__Root__}}portals</a></li> -->
    <li>On the Home Screen Click on <b>Login</b></li>
    <!-- <li>On the <b>Login Page</b></li> -->
    <li>Supply your <br/>Username <b style="font-style: italic">{{RegNo}}</b></li>
    <li>Click the <b></b>Arrow Button</b> to verify your Username</li>
    <li>Supply your <br/>Access Code <b style="font-style: italic">{{AC}}</b></li>
    <li>Click the <b></b>Arrow Button</b> to Login</li>
                       </ul>
                </div>
            </div>
            <div style="width: auto; text-align: center; margin:30px">
                    <div class="bbwa-sponsors-img"><a href="#" style="display: inline-block;margin:2px 5px;vertical-align: middle;transition: filter 0.7s"><img style="min-height: 30px;max-height: 30px" src="{{Logo}}" /></a><a href="#" style="display: inline-block;margin:2px 5px;vertical-align: middle;transition: filter 0.7s"><img style="min-height: 20px;max-height: 20px" src="{{BrandLogo}}" /></a></div>
                    <div class="footer-note gen-text-shadow">&copy; {{SchoolAbbr}}</div>
                </div>
            </div>';
        if (count($MailData) > 0) {
            foreach ($MailData as $key => $val) {
                $msg = str_replace("{{" . $key . "}}", $val, $msg);
            }
        }
        $sends = $dbo->SendMail($sch['OpEmail'], $upcand['Email'], $sch['Abbr'] . " Student Credentials", $msg, $sch['OpEmail'], $sch['OpEmailPassw'], $sch['OpEmailLive'] == "FALSE" ? false : true);
        // $sends = SendMail($mailparam);
        if ($sends !== true) {
            //Error("CE","Sending Mail Failed");
        }

        //send sms
        //$sch = GetSchool();
        $msg = "Hello, " . $upcand['SurName'] . " " . $upcand['FirstName'] . ", your Student Account is Created Successfully \n Reg. No: {$NewRegNo} \n Access Code: $acccode";
        //Send Message
        $sendmail = $dbo->SendSMS($sch['Abbr'], $msg, $upcand['Phone'], "234", $sch['OpUName'], $sch['OpUPassw'], $sch['OpSMSLive'] == "FALSE" ? false : true);

        //send notificaton
        $notid = Notify($NewRegNo, $msg, "Congratulations !!!", "0");
        //update notification_tb
        //Error(0,": ".$notid);


        $rd = "Slip.php?folder=regno=" . $NewRegNo . "&Form&paper=A4&orientation=P&MT=4&MB=30";
        // $canddet["RedirectURL"] = $rd;
        $rdata = "{Src:'{$__Root__}general/Slip.php?regno={$NewRegNo}&folder=Form&SubDir=" . urlencode($dbo->Config['SubDir']) . "',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
        $ardata = "{Src:'{$__Root__}general/Slip.php?RegNo=" . urlencode($NewRegNo) . "&folder=AcceptLetter&SubDir=" . urlencode($dbo->Config['SubDir']) . "',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";

        //delete student entrance details if exist
        $delentrancedet = $dbo->Delete("pstudentinfo_tb", "RegNo='" . trim($dbo->SqlSafe($Param['RegNo'])) . "' OR JambNo='" . trim($dbo->SqlSafe($Param['RegNo'])) . "'");
        //Error("CE",$Param['RegNo']);
        //$cand["ARedirectData"] = $ardata;
        return ["NextPageNum" => 4, "NRegNo" => $NewRegNo, "NRedirectData" => $rdata, "ARedirectData" => $ardata, "__Notify__" => ["Title" => "Congratulations", "Msg" => $msg]];
    } else {
        return ["NextPageNum" => 2, "sjsj" => "jkdk"]; //not accepted
    }
}



//Internal - get the next time verification code is to be sent (needed for phone verification) - manage waist of sms unit
function NextSendTime($param)
{
    $str = "";
    // $Use = (int)$otpdet['OtpUse'];
    $Tries = (int)$param['Counter'];
    //if already used, generate new one
    // $otp = $Use > 0?mt_rand(100000,999999):$otpdet['OTP'];
    $Tries = $Tries < 1 ? 1 : $Tries;
    //$Tries = $Use > 0?0:$Tries; //if already used don't let user wait
    $now = new DateTime();
    $sendwait = ($Tries * $Tries) * 3 * 60; //in seconds
    $lastSend = new DateTime($param['VDate']);
    $diffInSeconds = $now->getTimestamp() - $lastSend->getTimestamp();

    //if user need to wait
    if ($diffInSeconds < $sendwait) {
        $wait = $sendwait - $diffInSeconds;
        $wait = gmdate("G:i:s", $wait);
        $waitarr = explode(":", $wait);

        if ((int)$waitarr[0] > 0) {
            $plur = (int)$waitarr[0] > 1 ? "s" : "";
            $str = $waitarr[0] . " hour" . $plur . " ";
        }
        if ((int)$waitarr[1] > 0) {
            $plur = (int)$waitarr[1] > 1 ? "s" : "";
            $str .= (int)$waitarr[1] . " minite" . $plur . " ";
        }
        if ((int)$waitarr[2] > 0) {
            $plur = (int)$waitarr[2] > 1 ? "s" : "";
            $str .= (int)$waitarr[2] . " second" . $plur;
        }
    }
    return $str;
}

//R043
function SendVerCode($Param)
{
    //Error(0,json_encode($Param));
    global $dbo;
    $entrancedet = Entrance($Param);

    $dbtbpre = $entrancedet['StudInfoPref'];
    // $isemail = (isset($Param['vertype']) && strtolower(trim($Param['vertype'])) == "email")?TRUE:FALSE;

    //Error(0,json_encode($dbo->Config));
    //Error(0,json_encode(array_merge($Param,$dbo->Config)));
    //check if the email sent
    if (isset($Param['RegNo_Appl']) && trim($Param['RegNo_Appl']) != "") {

        $regnotype = explode("@", $Param['RegNo_Appl']);
        $isemail = count($regnotype) > 1 ? TRUE : FALSE;
        $isemailstr = ($isemail) ? "Email Address" : "Phone Number";
        $dbkey = ($isemail) ? "Email" : "Phone";

        // $resendmsg = (isset($Param['Resend']) && $Param['Resend'] == true)?["__Alert__"=>"New Verification Code Sent Successfully"]:[];
        //get url part
        $emalarr = $isemail ? $regnotype : ["", ""];
        //check if the email already exist for an applicant
        $appldet = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "", "RegNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "' OR JambNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "'");
       // Error(76, json_encode($appldet));
        if (is_array($appldet)) {
            //Error("CE",$appldet['RegLevel']);
            //check if already admited
            if((int)$appldet['admitted'] > 0 && (int)$entrancedet['CheckAdm'] == 1)Error(76);
            //get the level
            $PageNum = $entrancedet['Verify'] == "STUDENT" && (int)$appldet['RegLevel'] < 4?4:$appldet['RegLevel'];

            //Error("CE",$PageNum);
            return ["PageNum" => $PageNum, "RegNo_Appl" => $Param['RegNo_Appl'], "MailBox" => $emalarr[1], "vertype" => $isemail ? "email" : "phone", "VerTypeStr" => $isemailstr];
        } else {
            
            //valid email
            //generate validation number and send it to the mail

            $VeriNum = $entrancedet['Verify'] == "PHONE" && !$isemail ? substr($Param['RegNo_Appl'], -6) : mt_rand(100000, 999999);
            
            //check if already exist in applicantver_tb
            $everdet = $dbo->SelectFirstRow("applicantver_tb", "", "Email='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "' OR Phone='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "'");
            $VerID = 0;
            $totsend = 0;
            if (is_array($everdet)) { //if exist
                // Error("CE",json_encode($everdet));
                $totsend = (int)$everdet['Counter'];
                if (isset($Param['Resend']) && $Param['Resend'] == true) {
                    //update counter
                    if (!$isemail & $entrancedet['Verify'] != "PHONE") { //if phone verification
                        $waitstr = NextSendTime($everdet); //get the next allowed resend time
                        if (trim($waitstr) != "") {
                            Error("CE", " Resend not allowed<br/>kindly wait for the next <strong class='appcolor'>" . $waitstr . "</strong>", [], "clock");
                        }
                    }
                    //update it
                    $upd = $dbo->Update("applicantver_tb", ["Pin" => $VeriNum, "VDate" => date("Y-m-d h:i:s"), "Counter" => ($totsend + 1)], "ID=" . $everdet['ID']);
                    if (!is_array($upd)) {
                        Error(48);
                    }
                } else { //if not a resend
                    $VeriNum = $everdet['Pin'];
                }
                $VerID = $everdet['ID'];
            } else {

                $ins = $dbo->InsertID("applicantver_tb", ["$dbkey" => $Param['RegNo_Appl'], "Pin" => $VeriNum, "VDate" => date("Y-m-d h:i:s")]);

                if (!is_numeric($ins)) {
                    Error(48);
                }
                $VerID = $ins;
            }

            //get school detatils
            $sch = GetSchool();
            // Error(0,$sch['logo']);
            if ($entrancedet['Verify'] == "NONE") {
                if (($isemail && (is_null($sch['OpEmail']) || is_null($sch['OpEmailPassw']))) || (!$isemail && (is_null($sch['OpUName']) || is_null($sch['OpUPassw'])))) {
                    Error(49);
                }
            }


            //get the mail markup
            //$mkupurl = "../../Pages/";
            if ($isemail) { //if to send email
                $lookup = "../../Pages/";
                if (file_exists("../../../../" . $dbo->Config["SubDir"] . "Pages/" . $Param['Dir'] . "/VerCode.html")) {
                    $lookup = "../../../../" . $dbo->Config["SubDir"] . "Pages/";
                }
                $msg = "Verification Code: <b>$VeriNum</b>";
                if (file_exists($lookup . $Param['Dir'] . "/VerCode.html")) {
                    $msg = file_get_contents($lookup . $Param['Dir'] . "/VerCode.html");
                    if ($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 ["Mail"=>$msg];
                //send the verification number to the applicant mail
                $sendmail = $dbo->SendMail($sch['OpEmail'], $Param['RegNo_Appl'], $sch['Abbr'] . " Applicant Verification", $msg, $sch['OpEmail'], $sch['OpEmailPassw'], $sch['OpEmailLive'] == "FALSE" ? false : true);
                // Error("CE","jkjj");

            } else {
                if ($entrancedet['Verify'] != "PHONE") {
                    $sendmail = $dbo->SendSMS($sch['Abbr'], $VeriNum, $Param['RegNo_Appl'], "234", $sch['OpUName'], $sch['OpUPassw'], $sch['OpSMSLive'] == "FALSE" ? false : true);
                    $rstdet = explode("|", $sendmail);
                    if (strtolower($rstdet[0]) == "success") {
                        $sendmail = TRUE;
                    }
                } else {
                    $sendmail = TRUE;
                }
                //if is sms verification

            }

            // Error(0,$sendmail);
            //return ["Mail"=>$msg];
            if ($sendmail !== TRUE) {
                Error(50, " : " . $sendmail);
            }
            if (isset($Param['Resend']) && $Param['Resend'] == true && $entrancedet['Verify'] != "PHONE") Error("CE", "New Verification Code Sent Successfully", [], "envelope");

            return ["RegNo_Appl" => $Param['RegNo_Appl'], "MailBox" => $emalarr[1], "vertype" => $isemail ? "email" : "phone", "VerTypeStr" => $isemailstr];

            //add the applicant
            //Error(0," - ".$VeriNum);
        }
    } else if (isset($Param['Appl_Phone'])) {
        Error(0, " Phone Verification");
    } else {
        Error(11);
    }
}



//R044
function VerifyApplicantEmail($Param)
{
    global $dbo;
    $entrancedet = Entrance($Param);
    $dbtbpre = $entrancedet['StudInfoPref'];
    if (!isset($Param['VerCode'])) Error(0);
    if (trim($Param['VerCode']) == "" || (int)$Param['VerCode'] == 0) Error(51);
    if (!isset($Param['RegNo_Appl']) || trim($Param['RegNo_Appl']) == "") {
        // return ["PageNum"=>1,"__Alert__"=>"Sorry, we could not Identify you. Enter your Email Address and Try Again"];
        return RedirectTo(1, "Sorry, we could not Identify you. Try Again");
    }
    $regarr = explode("@", $Param['RegNo_Appl']);
    if (count($regarr) > 1) { //if the type of regno is email
        $isphone = FALSE;
        $regtype = "Email";
    } else {
        $isphone = TRUE;
        $regtype = "Phone";
    }
    //get the PIN of the user
    $appldet = $dbo->SelectFirstRow("applicantver_tb", "", "Email='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "' OR Phone='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "'");
    if (!is_array($appldet)) {
        //return ["PageNum"=>1,"__Alert__"=>"Invalid Email Address, Enter your registered Email and Continue"];
        return RedirectTo(1, "Invalid Email Address, Enter your registered $regtype and Continue");
    }
    if ($Param['VerCode'] != $appldet['Pin']) Error(51);
    //Error("CE",json_encode($Param));
    if (!isset($Param['ToPageNum'])) $Param['ToPageNum'] = 3; //if the next page not sent set to 3
    //create the applicant registration entering
    //check if applicant entering already register
    $appldet = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "", "RegNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "' OR JambNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "'");
    if (!is_array($appldet)) {
        $insertdata = ["RegNo" => $Param['RegNo_Appl'], "RegLevel" => $Param['ToPageNum'], "OtherDet" => json_encode(["EntranceID" => $entrancedet['ID']])];
        if ($isphone) {
            $insertdata["Phone"] =  $Param['RegNo_Appl'];
        } else {
            $insertdata["Email"] =  $Param['RegNo_Appl'];
        }
        $sqlmd = $dbo->RunQuery("set @@sql_mode=''");
        $ins = $dbo->InsertID2("{$dbtbpre}studentinfo_tb", $insertdata);
        if (!is_numeric($ins)) {
            Error(48, "-" . $ins);
        }
    } else { //if entering exixt check if not same Entrance ID, update it
        $otherdet = !is_null($appldet['OtherDet']) && trim($appldet['OtherDet']) != "" ? json_decode($appldet['OtherDet'], true) : [];
        if (!isset($otherdet['EntranceID']) || $otherdet['EntranceID'] != $entrancedet['ID']) {
            //update it
            $otherdet['EntranceID'] = $entrancedet['ID'];
            $updcand = $dbo->Update("{$dbtbpre}studentinfo_tb", ['OtherDet' => json_encode($otherdet)], "id=" . $appldet['id']);
        }
    }

    return ["RegNo_Appl" => $Param['RegNo_Appl']];
}

//R045
function LoadEntrancePayment($Param)
{
    
    global $dbo;
    if (!isset($Param['RegNo_Appl']) || trim($Param['RegNo_Appl']) == "") {
        // return ["PageNum"=>1,"__Alert__"=>"Sorry, we could not Identify you. Enter your Email Address and Try Again"];
        return RedirectTo(1, "Sorry, we could not Identify you. Enter your Email Address and Try Again");
    }

    //get the payid for entrance payment
    //check if entrance id isset
    /*  $EntrContrID = (isset($Param["EntranceID"]) && (int)$Param["EntranceID"] > 0)?$Param["EntranceID"]:1;
    $entrancedet = $dbo->SelectFirstRow("putme","","ID=".$EntrContrID);
    if(!is_array($entrancedet))Error(52); */
    $entrancedet = Entrance($Param);
   
    $dbtbpre = $entrancedet['StudInfoPref'];
   
    if ($entrancedet['PayReg'] == "REG") { //if payment disabled
        if (!isset($Param['NextPageNum'])) $Param['NextPageNum'] = 5; //if the next page not sent set to 5
        //update the applicant RegLevel - not needed incase payment enable during the registration process
        // $upd = $dbo->Update("pstudentinfo_tb",["RegLevel"=>$Param['NextPageNum']],"id=".$appldet['id']);
        return RedirectTo($Param['NextPageNum']);
    }
    $PayID = $entrancedet['PayID'];
    //get the applicant details
    $appldet = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "", "RegNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "' OR JambNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "'", MYSQLI_ASSOC);

    if(!is_array($appldet)) Error("CE", "Invalid Applicant");
    
    if (trim($appldet['OtherDet']) != "" && !is_null($appldet['OtherDet'])) {
        $otherdetarr = json_decode($appldet['OtherDet'], true);
        if (is_array($otherdetarr)) {
            unset($appldet['OtherDet']);
            $appldet = array_merge($appldet, $otherdetarr);
        }
    }
    //get payment ref
    $payorder = $dbo->SelectFirstRow("order_tb", "", "RegNo='" . $dbo->SqlSafe($Param['RegNo_Appl']) . "' AND ItemID = $PayID");
    if (is_array($payorder)) {
        //check payment
        $paydet = HasPaidRef($payorder['TransNum']);
        //return ["Status"=>"Paid"];
        if ($paydet[0] == 1) { //payment not made
            if (!isset($Param['NextPageNum'])) $Param['NextPageNum'] = 5; //if the next page not sent set to 5
            //update the applicant RegLevel
            $upd = $dbo->Update("{$dbtbpre}studentinfo_tb", ["RegLevel" => $Param['NextPageNum']], "id=" . $appldet['id']);
            return RedirectTo($Param['NextPageNum'], "Required Payment Verified Successfully");
        }
    }
    

    //get the payment item details
    //$payitem = $dbo->SelectFirstRow("item_tb","","ID=".$PayID);
    //if(!is_array($payitem))Error(14); //invalid payment type
    $HighSem = HighestSemester();
    
    //get the payment amount
    $Pamt = GetPaymentAmt(["LoginName" => $Param['RegNo_Appl'], "SemesterID" => ($HighSem['Num'] + 1), "LevelID" => 1, "SemesterPartID" => 3, "PayID" => $PayID, "StudentDetails" => $appldet]);
    if (!is_array($Pamt)) Error(12);

    //set payment options
    $PBank = $PCard = $PWallet = false;
    $PayOption = $Pamt['PayDetails']['PayOption'];
    //('ALL','CARD','BANK','WALLET','BANK-CARD','BANK-WALLET','CARD-WALLET')
    if(isset($PayOption)){
        if(strstr($PayOption,"BANK") !== FALSE || $PayOption == 'ALL')$PBank = true;
        if(strstr($PayOption,"CARD") !== FALSE || $PayOption == 'ALL')$PCard = true;
        if(strstr($PayOption,"WALLET") !== FALSE || $PayOption == 'ALL')$PWallet = true;
    }
   
    //marge all details
    return array_merge($Pamt['StudentDetails'], $Pamt['PayDetails'], ["Amount" => $Pamt['Amount'], "FAmount" => $Pamt['FAmount'], "RegNo_Appl" => $Param['RegNo_Appl'], "BankPre" => $dbtbpre,"PayBank"=>$PBank,"PayCard"=>$PCard,"PayWallet"=>$PWallet]);
    //Error("CE",json_encode($Pamt));

}

//R047
function AddReferee($Param)
{
    $entrancedet = Entrance($Param);
    $dbtbpre = $entrancedet['StudInfoPref'];
    Underscored($Param);
    MapData($Param);
    global $dbo;

    if (!isset($Param['RegNo']) || trim($Param['RegNo']) == "") Error(11);
    $RegNo = $Param['RegNo'];
    //check the referee name
    if (!isset($Param['RefereeName']) || (!is_array($Param['RefereeName']) && trim($Param['RefereeName']) == "")) Error(54);

    //get school detatils
    $sch = GetSchool();

    //turn all expected referee details to array if not array
    foreach (['RefereeName', 'RefereeEmail', 'RefereePhone'] as $refdet) {
        $Param[$refdet] = !isset($Param[$refdet]) ? [""] : (is_array($Param[$refdet]) ? $Param[$refdet] : [$Param[$refdet]]);
    }


    foreach ($Param['RefereeName'] as $refkey => $refVale) {
        //check if already exist 
        $RefName = $refVale;
        $RefEmail = isset($Param['RefereeEmail'][$refkey]) ? $Param['RefereeEmail'][$refkey] : $Param['RefereeEmail'][0];
        $RefPhone = isset($Param['RefereePhone'][$refkey]) ? $Param['RefereePhone'][$refkey] : $Param['RefereePhone'][0];
        //$RefPhone 
        $refexit = $dbo->SelectFirstRow("referee_tb", "", "Email='" . $dbo->SqlSafe($RefEmail) . "' AND ApplID='" . $dbo->SqlSafe($RegNo) . "'");
        if (is_array($refexit)) continue;

        $VeriNum = mt_rand(100000, 999999);
        /* $lookup = "../../Pages/";
        if(file_exists("../../../../".$dbo->Config["SubDir"]."Pages/".$Param['Dir']."/RefMail.html")){
            $lookup = "../../../../".$dbo->Config["SubDir"]."Pages/";
        } */
        $msg = "Referee Code: <b>$VeriNum</b>";
        $Param['SchoolName'] = $sch['Name'];
        $Param['VerPin'] = $VeriNum;
        $Param['RefName'] = $RefName;
        MailMessage($msg, $Param, "RefMail.html");
        /* if(file_exists($lookup.$Param['Dir']."/RefMail.html")){
           $msg = file_get_contents($lookup.$Param['Dir']."/RefMail.html");
           if($msg != ""){
               $Param['SchoolName'] = $sch['Name'];
               $Param['VerPin'] = $VeriNum;
               $Param['RefName'] = $RefName;
               foreach($Param as $pkey=>$pval){
                   $msg = str_replace("{{".$pkey."}}",$pval,$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 ["Mail"=>$msg];
        //send the verification number to the applicant mail
        $sendmail = $dbo->SendMail($sch['OpEmail'], $RefEmail, $Param['Subject'], $msg, $sch['OpEmail'], $sch['OpEmailPassw'], $sch['OpEmailLive'] == "FALSE" ? false : true);
        //return ["Mail"=>$msg];
        if ($sendmail !== true) {
            Error(50, " : " . $sendmail);
        }
        //insert
        $inst = $dbo->InsertID("referee_tb", ["Name" => $RefName, "Email" => $RefEmail, "Phone" => $RefPhone, "AccessCode" => $VeriNum, "ApplID" => $RegNo]);
        if (!is_numeric($inst)) {
            //Error("CE",$inst);
        }
    }



    //check if RegLevel Set, Update in pstudentinfo
    if (isset($Param['RegLevel'])) {
        $upd = $dbo->Update("{$dbtbpre}studentinfo_tb", ["RegLevel" => $Param['RegLevel']], "RegNo='" . $dbo->SqlSafe($RegNo) . "' OR JambNo = '" . $dbo->SqlSafe($RegNo) . "'");
    }

    return ["RegNo_Appl" => $RegNo];
}

//OlevelExamTypes R048
function OlevelExamType($Param)
{
    global $dbo;
    $olvlextype = $dbo->Select("olevelexamtype_tb");
    if (!is_array($olvlextype)) Error(4);
    return $dbo->FetchAll($olvlextype[0], MYSQLI_ASSOC);
}

//R049
function SaveOlevelDetails($Param)
{
    Underscored($Param);
    global $dbo;
    $entrancedet = Entrance($Param);
    $dbtbpre = $entrancedet['StudInfoPref'];
    /* GATEWAY STANDARD ACADEMY, UKANAFUN`~2016`~4042817020`~2`~1 */
    /* ENGLISH LANGUAGE=B3;MATHEMATICS=B2;BIOLOGY=B2;CHEMISTRY=B3;PHYSICS=C5;AGRICULTURAL SCIENCE=A1;CIVIC EDUCATION=B3;MARKETTING=B2;GEOGRAPHY=B3 */
    /* 1=4||6=3||7=3||8=4||9=6||13=1||37=4||44=3||4=4 */
    //Error(11,$Param['RegNo']);
    $appldet = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "", "RegNo='" . $dbo->SqlSafe($Param['RegNo']) . "' OR JambNo='" . $dbo->SqlSafe($Param['RegNo']) . "'", MYSQLI_ASSOC);
    if (!is_array($appldet)) {
        // return ["PageNum"=>1,"__Alert__"=>"Sorry, we could not Identify you. Enter your Email Address and Try Again"];
        return RedirectTo(1, "Sorry, we could not Identify you. Enter your Email Address and Try Again");
    }
    //check if not Awaiting Result
    if (!isset($Param['ExamType']) || (int)$Param['ExamType'] < 1) Error("CE", "Hoop!!, Invalid First Sitting Exam Type Specified");
    //if((int)$Param['ExamType'] > 1){ //if not awaiting result
    $FsitExmDet = [];
    $SsitExmDet = [];
    $ssitseen = false;
    $ssitallseen = true;
    $RsDetFiled = ["SchName", "ExamYear", "ExamNum", "ExamType", "ExamBatch"];
    foreach ($RsDetFiled as $rstDetKey) {
        if (($Param["ExamType"] > 1) && (!isset($Param[$rstDetKey]) || trim($Param[$rstDetKey]) == "" || (($rstDetKey == "ExamType" || $rstDetKey == "ExamBatch") && (int)$Param[$rstDetKey] < 1))) {
            Error("CE", "Hoop!!, Invalid First Sitting Result Details Supplied");
        }
        //get only the year
        if ($rstDetKey == "ExamYear") {
            $arr = explode("/", $Param[$rstDetKey]);
            $Param[$rstDetKey] = isset($arr[2])?$arr[2]:$Param[$rstDetKey];
        }
        //if it is not Awaiting result add it
        /*  if((int)$Param["ExamType"] > 1){
            $FsitExmDet[] = $Param[$rstDetKey];
        }else{ //if awaiting result
            if($rstDetKey == "ExamType"){
                $FsitExmDet[] = $Param[$rstDetKey]; 
            }else{
                $FsitExmDet[] = "";
            }
        } */
        $FsitExmDet[] = $Param[$rstDetKey];

        //if it is set set seen to true
        if (isset($Param[$rstDetKey . "2"]) && trim($Param[$rstDetKey . "2"]) != "") {
            if ($rstDetKey . "2" == "ExamType2" || $rstDetKey . "2" == "ExamBatch2") { //if combobox
                if ((int)$Param[$rstDetKey . "2"] > 0) {
                    $ssitseen = true;
                } else {
                    $ssitallseen = false;
                }
            } else {
                $ssitseen = true;
            }
        } else {
            $ssitallseen = false;
        }
        if ($rstDetKey . "2" == "ExamYear2" && trim($Param[$rstDetKey . "2"]) != "") {
            $arr2 = explode("/", $Param[$rstDetKey . "2"]);
            $Param[$rstDetKey . "2"] = isset($arr2[2])?$arr2[2]:$Param[$rstDetKey . "2"];
        }
        $SsitExmDet[] = $Param[$rstDetKey . "2"];
    }



    //if not awaiting result OlvRstLB is not required
    if ((int)$Param["ExamType"] > 1) {
        //check if valid first sit result
        if (!isset($Param['OlvRstLB']) || count($Param['OlvRstLB']) < 1) Error(0);
    }



    //get all olvlsubj
    $AllSubj = $dbo->Select("olvlsubj_tb");
    $AllOlvSubj = $dbo->FetchAllByID($AllSubj[0]);
    if (!is_array($AllOlvSubj)) Error(4, " : Reading O/A Level Subjects");
    //get all olvlsubj
    $AllGrd = $dbo->Select("olvlgrade_tb");
    $AllOlvGrade = $dbo->FetchAllByID($AllGrd[0]);
    if (!is_array($AllOlvSubj)) Error(4, " : Reading O/A Level Grades");


    if ((int)$Param["ExamType"] > 1) { //if not awaiting result
        $FSitRst = FormOlvlRst($Param['OlvRstLB'], $AllOlvSubj, $AllOlvGrade);
        //check if satisfy count condition
        $MinimumRst = 7;
        $MaxmumRst = 9; //should come from database
        $totrst = count($FSitRst[0]);
        if ($totrst < $MinimumRst || $totrst > $MaxmumRst) Error(55, " :First Sitting (Minimum: $MinimumRst , Maximum: $MaxmumRst)");
    } else {
        $FSitRst = [["AR"], ["AR"]];
    }



    $DBRstDet = implode("`~", $FsitExmDet);
    $DBRstStr = implode(";", $FSitRst[0]);
    $DBRstID = implode("||", $FSitRst[1]);

    //Check second sitting
    //if atleast one of the result details is supplied
    if ($ssitseen) {
        //if not all suplied
        if (!$ssitallseen && (int)$Param["ExamType2"] > 1) Error("CE", "Hoop!!, Invalid Second Sitting Result Details Supplied");
        if ((int)$Param["ExamType2"] > 1) { //if not awaiting result
            $SSitRst = FormOlvlRst($Param['OlvRstLB2'], $AllOlvSubj, $AllOlvGrade);
            $totrst = count($SSitRst[0]);
            if ($totrst < $MinimumRst || $totrst > $MaxmumRst) Error(55, " :Second Sitting (Minimum: $MinimumRst , Maximum: $MaxmumRst)");
        } else {
            $SSitRst = [["AR"], ["AR"]];
        }
        $DBRstDet .= "###" . implode("`~", $SsitExmDet);
        $DBRstStr .= "###" . implode(";", $SSitRst[0]);
        $DBRstID .= "###" . implode("||", $SSitRst[1]);
    }
    /*  }else{
        //Awaiting result
    } */


    $UpdateArr = ["OlevelRstDetails" => $DBRstDet, "OlevelRst" => $DBRstStr, "OlevelRst2" => $DBRstID];
    if (isset($Param['RegLevel'])) {
        $UpdateArr['RegLevel'] = $Param['RegLevel'];
    }

    $upd = $dbo->Update("{$dbtbpre}studentinfo_tb", $UpdateArr, "id=" . $appldet['id']);
    if (!is_array($upd)) Error(56,": ".$upd);
    return ["RegNo_Appl" => $Param['RegNo']];
}

//internal form olvresult $Param['OlvRstLB']
function FormOlvlRst($OlvRstLB, $AllOlvSubj, $AllOlvGrade)
{
    //form rst arrays
    $RstStr = [];
    $RstIDs = [];

    foreach ($OlvRstLB as $Rst) {
        if ((int)$Rst['state'] != 1) continue;
        $SubID = explode("_", $Rst['id']);
        $SubID = isset($SubID[1]) ? $SubID[1] : $SubID[0];
        //if subject not exist continue
        if (!isset($AllOlvSubj[$SubID])) continue;

        //grade id
        $GradeID = $Rst['value'];
        //if subject grade
        if (!isset($AllOlvGrade[$GradeID])) continue;

        $RstStr[] = $AllOlvSubj[$SubID]['SubName'] . "=" . $AllOlvGrade[$GradeID]['Grade'];
        $RstIDs[] = $SubID . "=" . $GradeID;
    }
    return [$RstStr, $RstIDs];
}

//R050
function GetEntranceUploads($Param)
{
    $entdet = Entrance($Param);
    //Error("CE",json_encode($Param));
    if (is_null($entdet['Uploads']) || trim($entdet['Uploads']) == "") return [];
    //Error("CE","hhh");
    $upl = json_decode($entdet['Uploads'], true);
    $uplarr = [];
    foreach ($upl as $Dir => $indupl) {
        if(is_string($Dir)){
            if ($indupl[0] == false) continue;
            //check if condition exist
            if(isset($indupl[3]) && trim($indupl[3]) != ""){
                /* $condData = explode("=",$indupl[3]);
                if(count($condData) >= 2){
                    $field = trim($condData[0]);
                    $val = trim($condData[1]);
                    if(isset($Param[$field]) && $Param[$field] != $val)continue;
                } */
                if(!CheckUploadCondition($indupl[3],$Param))continue;
            }
            $req = isset($indupl[2]) && $indupl[2] == true ? "true" : "false";
            $uplarr[] = ["Dir" => $Dir, "Title" => $indupl[1], "Required" => $req,"MinSize"=>20480,"MaxSize"=>0,"Accept"=>"image/*"];
        }else{
            if (isset($indupl['Display']) && $indupl['Display'] == false) continue;
            if(isset($indupl['Condition']) && !CheckUploadCondition($indupl['Condition'],$Param))continue;
            $Dir = isset($indupl['Dir']) && trim($indupl['Dir']) != ''?$indupl['Dir']:"Uploads";
            $Title = isset($indupl['Title']) && trim($indupl['Title']) != ''?$indupl['Title']:"Upload File";
            $req = isset($indupl['Required']) && $indupl['Required'] == true?'true':'false';
            $minsize = isset($indupl['MinSize'])?$indupl['MinSize']:20480;
            $maxsize = isset($indupl['MaxSize'])?$indupl['MaxSize']:0;
            $accept = isset($indupl['Accept']) && trim($indupl['Accept']) != ""?$indupl['Accept']:'image/*';
            $uplarr[] = ["Dir" => $Dir, "Title" => $Title, "Required" => $req,"MinSize"=>$minsize,"MaxSize"=>$maxsize,"Accept"=>$accept];
        }
        
    }
    return $uplarr;
}

function CheckUploadCondition($cond,$Param){
    $condData = explode("=",$cond);
                if(count($condData) >= 2){
                    $field = trim($condData[0]);
                    $val = trim($condData[1]);
                    return !(isset($Param[$field]) && $Param[$field] != $val);
                }
                return true;
}

//R051
function PerformEntranceUpload($Param)
{
    Underscored($Param);
    
    if (!isset($Param['RegNo'])) Error(23);
    global $dbo;
    $entrancedet = Entrance($Param);
    $dbtbpre = $entrancedet['StudInfoPref'];
    //Error(23,$Param['RegNo']);
    //confirm applicant
    $appldet = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "", "RegNo='" . $dbo->SqlSafe($Param['RegNo']) . "' OR JambNo='" . $dbo->SqlSafe($Param['RegNo']) . "'", MYSQLI_ASSOC);
    if (!is_array($appldet)) {
        // return ["PageNum"=>1,"__Alert__"=>"Sorry, we could not Identify you. Enter your Email Address and Try Again"];
        return RedirectTo(1, "Applicant Identification Failed. Try Again");
    }

    $otherdet = !is_null($appldet['OtherDet']) && trim($appldet['OtherDet']) != "" ? json_decode($appldet['OtherDet'], true) : [];
    if (isset($otherdet['EntranceID'])) $Param['EntranceID'] = $otherdet['EntranceID'];
    //get the entrance settings
    $entdet = Entrance($Param);

    if (is_null($entdet['Uploads']) || trim($entdet['Uploads']) == "") return ["RegNo_Appl" => $Param['RegNo']]; //file upload not required
    //Error("CE","hhh");
    $upl = json_decode($entdet['Uploads'], true);
    $commit = true; //determine if all file upload is successfull
    $uploaded = []; //hold all successful uploaded file path
    $ApplDir = [];
    foreach ($upl as $Dirc => $indupl) {
        if(is_string($Dirc)){
            if ($indupl[0] == false) continue; //if disabled
           $Dir = $Dirc;
        }else{
            if ($indupl['Display'] == false) continue; //if disabled
            $Dir = isset($indupl['Dir']) && trim($indupl['Dir']) != ''?$indupl['Dir']:"Uploads";
        }

         //form the filename
        $filename = str_replace(array("/", '\\'), "_", $Param['RegNo']); //which is the regno
        //Error(23,$Param[$Dir . "_Appl"]);
            //Error("CE",$filename);
            $fileType = isset($Param[$Dir . "_Appl"]) && trim($Param[$Dir . "_Appl"]) != "" && trim($Param[$Dir . "_Appl"]) != "?"?$Param[$Dir . "_Appl"]:"image/gif,image/jpeg,image/jpg,image/pjpeg,image/png";
            //backward compactibility
            $fileType = $fileType == "image/*"?"image/gif,image/jpeg,image/jpg,image/pjpeg,image/png":"";
            //check if dir exist
            $rst = Uploader("../../../../" . $dbo->Config['SubDir'] . "Files/UserImages/" . $Dir . "/", $Dir . "_Appl", $filename,$fileType);
    
            if (count($rst["Failed"]) > 0) {
                //unset allready uploaded files
                if (count($uploaded) > 0) {
                    foreach ($uploaded as $ufile) {
                        unset($ufile);
                    }
                }
                Error(17, " : " . $rst["Failed"][$Dir . "_Appl"]);
            }
            $sucessfiles = explode(";", $rst["Success"][$Dir . "_Appl"]);
            $uploaded[] = array_merge($uploaded, $sucessfiles);
           // Error(17, " S : " . $rst["Success"][$Dir . "_Appl"]);
            
            //Error("CE",$newimg);
            //get the filename
            $ApplDir[$Dir] = [];
            foreach ($sucessfiles as $suc) {
                $newimg = ResizeImage($suc, 300, 300); //resize image
                $filearr = explode("/", $suc);
                $ApplDir[$Dir][] = array_pop($filearr);
            }
        

        //$uplarr[] = ["Dir"=>$Dir,"Title"=>$indupl[1]];
    }

    $Otherdet = trim($appldet['OtherDet']) != "" ? json_decode($appldet['OtherDet'], true) : [];
    $Otherdet["Uploads"] = $ApplDir;
    //Error(27,json_encode($ApplDir));
    $UpdateArr = ["OtherDet" => json_encode($Otherdet), "RegLevel" => $Param['RegLevel']];
    //update pstudentinfo 
    $upd = $dbo->Update("{$dbtbpre}studentinfo_tb", $UpdateArr, "id=" . $appldet['id']);
    //if(!is_array($upd))Error(56);
    return ["RegNo_Appl" => $Param['RegNo']];
}

//R064
function AutoAdmission($param = [])
{
    Underscored($param);
    $entrancedet = Entrance($param);
    $dbtbpre = $entrancedet['StudInfoPref'];
    global $dbo;

    //get the school settings
    $StudentSet = $dbo->SelectFirstRow("studentset_tb");
    if (is_array($StudentSet)) {
        //get the candidate details
        $CandDet = $dbo->SelectFirstRow("{$dbtbpre}studentinfo_tb", "id,SurName,FirstName,Phone,admitted,ProgID,ClassID", "RegNo='" . $param['RegNo'] . "' OR JambNo='" . $param['RegNo'] . "'");

        if (!is_array($CandDet)) {

            return ["RegOnly" => [1], "RegAdmit" => [0]];
        }
        if ($StudentSet['AutoAdmission'] == "ADMIT") {
            $ClassID = 0;
            //auto admit 
            if ((int)$CandDet['ClassID'] == 0) {
                $ProgID = (int)$CandDet['ProgID'];

                //get the first classid 
                $classdet = $dbo->SelectFirstRow("studentclass_tb", "ID", "ProgID=" . $ProgID);
                if (is_array($classdet)) {
                    $ClassID = $classdet['ID'];

                    //update student class
                    //$updst = $dbo->Update("pstudentinfo_tb",["ClassID"=>$ClassID],"id=".);
                }
            }

            //Error("CE",$ClassID);
            $admit = $dbo->RunQuery("UPDATE {$dbtbpre}studentinfo_tb SET admitted=1,ClassID=$ClassID WHERE id=" . $CandDet['id']);
            if (is_array($admit)) {
                return ["RegOnly" => [0], "RegAdmit" => [1]];
            } else {
                return ["RegOnly" => [1], "RegAdmit" => [0]];
            }
        }
    } else {
        return ["RegOnly" => [1], "RegAdmit" => [0]];
    }
}
?>