<?php
//Eduporta api engine parameter V1
//*********************************** */

//Request Mapping
$Request = [
    "R000" => ["DoNothing",""],
    "R001" => ["GetSchoolDetails","school"],
    "R002" => ["GetStudentDetails","student"],//LoginName
    "R003" => ["CheckPassword","student"], //Verify Accesscode
    "R004" => ["GetApplications","application"],
    "R005" => ["GetPageElements","application"],
    "R006" => ["GetPaymentTypes","payment"],
    "R007" => ["GetPaymentAmt",""],
    "R008" => ["InitalizePayment","payment"],
    "R009" => ["VerifyPayment","payment"],
    "R010" => ["GetCandidate",""],
    "R011" => ["GetStateOfOrigin","state"],
    "R012" => ["GetLGAreas","state"],
    "R013" => ["SaveCandidate","candidate"],
    "R014" => ["GetFaculty",""],
    "R015" => ["GetProgrammeByFaculty",""],
    "R016" => ["CreateUniqueRecord","candidate"],
    "R017" => ["CheckUniqueEntry","candidate"],
    "R018" => ["UpdateUniqueEntry","candidate"],
    "R019" => ["SendMail",""],
    "R020" => ["GetSchoolDegrees",""],
    "R021" => ["VerifyCandidate","candidate"],
    "R022" => ["AcceptAdmission","acceptance"],
    "R023" => ["CandidateToStudent","candidate"],
    "R024" => ["GetAllApplications","application"],
    "R025" => ["ClearAllSessions",""],
    "R026" => ["GetSchoolSession",""],
    "R027" => ["GetStudentLevelSemester",""],
    "R028" => ["GetAllPaymentTypes","payment"],
    "R029" => ["OlevelGrades",""],
    "R030" => ["OlevelSubjects",""],
    "R031" => ["GetAllPaymentTypes2","payment"],
    "R032" => ["GetHighestPayment","payment"],
    "R033" => ["GetStudentCourses","course"],
    "R034" => ["RegisterCourses","course"],
    "R035" => ["UndoCourseRegistration","course"],
    "R036" => ["LoadCourseReg","course"],
    "R037" => ["LoadCoursesRegHistory","course"],
    "R038" => ["LoadPaymentHistory","payment"],
    "R039" => ["GetStudentCurrentLevelSemester",""],
    "R040" => ["WalletDetails","payment"],
    "R041" => ["LoadResultHistory","result"],
    "R042" => ["LoadResultDetails","result"],
    "R043" => ["SendVerCode","candidate"],
    "R044" => ["VerifyApplicantEmail","candidate"],
    "R045" => ["LoadEntrancePayment","candidate"],
    "R046" => ["Entrance",""],
    "R047" => ["AddReferee","candidate"],
    "R048" => ["OlevelExamType","candidate"],
    "R049" => ["SaveOlevelDetails","candidate"],
    "R050" => ["GetEntranceUploads","candidate"],
    "R051" => ["PerformEntranceUpload","candidate"],
    "R052" => ["LoadAcceptancePayment","acceptance"],
    "R053" => ["Acceptance","acceptance"],
    "R054" => ["ChangeEntranceVerField",""],
    "R055" => ["PaymentAnalysis","payment"],
    "R056" => ["UpdateOrderDet","payment"],
    "R057" => ["GetStatistics","student"],
    "R058" => ["GetAllLevels",""],
    "R059" => ["GetClassByProg",""],
    "R060" => ["Troubleshoot",""],
    "R061" => ["PayWithWallet","payment"],
    "R062" => ["PerformWalletTrans","payment"],
    "R063" => ["OrderDetailsByRef","payment"],
    "R064" => ["AutoAdmission","candidate"],
    "R065" => ["GetProgress","student"],
    "R066" => ["MenuLinkDetails","application"],
    "R067" => ["LoadNotification","media"],
    "R068" => ["GetStudentCoursesEdit","course"],
    "R069" => ["UpdateCourses","course"],
    "R070" => ["GetUnPaidOrderByReg","payment"],
    "R071" => ["GetOrderDetailsByRef","payment"],
    "R072" => ["RestoreTransactionID","payment"],
    "R073" => ["GetCountries",""],
    "R074" => ["GetStates",""]
];

//Field mapping
$Fields = [
    "State" => "StateId",
    "Address" => "Addrs"
];

$GLOBALS['Fields'] = $Fields;

//Error Mapping
$Errors = ["CE"=>"",0=>"Invalid Parameter",1=>"Invalid Version Requested",2=>"Extablishing Database Connection Failed",3=>"Invalid Request ID",4=>"Internal Error, Query Failed",5=>"Invalid Login Name (Reg. Number / Email) Supplied",6=>"Invalid Registration Number",7=>"Invalid Access Code",8=>"Student Identification Failed",9=>"Empty Set",10=>"Application Not Found or Invalid Application Selected",16=>"No Page Setup for the Selected Application",11=>"Invalid Request Parameter",12=>"Reading Payable Amount Failed",13=>"Required Payment Not Made",14=>"Invalid Payment Type",15=>"Candidate Identification Failed",17=>"File Upload Failed",18=>"Unique Key Already Exist, Change it and try again",19=>"Wrong Credentials Supplied",20=>"Account is Inactive",21=>"Sending Mail Failed",22=>"Application Already Closed",23=>"Invalid Candidate or Student Account Already Created",24=>"Candidate Application is Incomplete",25=>"Candidate Not Yet Admitted",26=>"Student Account Already Created",27=>"Wrong Payment, This Payment is for another Payer",28=>"Creating Student Account Failed",29=>"Auto-Registration Number Engine Failed",30=>"Reading Student Level Failed",31=>"Reading Student Semester Failed",32=>"Reading Courses Failed",33=>"No Course Found",34=>"You have exceeded the maximum credit hour",35=>"Course Registration Failed",36=>"No Course Selected",37=>"Undo Operation Failed",38=>"No Registration Found",39=>"No Payment History Found",40=>"Registration will be done Automatically, upon successfull Payment of Fee",41=>"Wallet Not Configured",42=>"Wallet Disabled",43=>"No Result Found",44=>"Invalid Result",45=>"Reading Approval Details Failed",45=>"Reading Result Settings Failed",46=>"Invalid Payment Verification type Configured, Contact the ICT Team",47=>"Payment Not made",48=>"Saving Verification Code failed",49=>"School Mail Account not Setup",50=>"Error occur while sending Verification Number",51=>"Invalid Verification Code Supplied",52=>"No Entrance Setup Found, Contact the ICT Team",53=>"Application Closed",54=>"Invalid Referee Details Supplied",55=>"Invalid Result Selection",56=>"Saving O/A Level Result Failed",57=>"No Acceptance Setup Found, Contact the ICT Team",57=>"Invalid Payment Reference",58=>"Payment Initialization Record Not Found",59=>"Payment Already Made",60=>"Invalid Payment BreakDown",61=>"Payment Details Update Failed",62=>"Invalid Payment Amount",63=>"Insurficient Wallet Fund",64=>"Payment from Wallet Failed",65=>"Payment Reference Not Found",66=>"Error Loading Notification",67=>"NO NOTIFICATION YET",68=>"Edit not allowed: Course Registered in another Session",69=>"Edit not allowed: Result already uploaded",70=>"Reading Course/Subject Settings Failed",71=>"Registration Closed",72=>"Invalid Student or No Pending Transaction Exist",73=>"Invalid Pin",74=>"Expired Pin",75=>"Maximum Usage Reached",76=>"Already Admitted, Use the Student Account Module to continue your admission process",77=>"Wrong Setup. Contact the ICT Team",78=>"Operation not Allowed, advice to suspend studies",79=>"Account Suspended, contact the ICT team",80=>"Required payment not made, Advice to suspend studies"];

$GLOBALS['Errors'] = $Errors;   

//Error Responce Handler
function InternalError($errindex = -1,$msg="",$param = [],$logo = "exclamation-triangle",$ErrorImage="images/bbwa/error-img.png"){
    global $Errors;
    global $epcoredir;
    $epcoredir = isset($epcoredir)?$epcoredir:'';
    $ErrObj = ["Error"=>["Code"=>-1,"Message"=>"Unknown Error","Logo"=>$logo]];
    $Errors[$errindex] = isset($Errors[$errindex])?$Errors[$errindex].$msg:$msg;
    if(isset($Errors[$errindex])){
        $ErrObj["Error"]["Code"] = $errindex;
        $ErrObj["Error"]["Message"] = $Errors[$errindex];
        $ErrObj["Error"]["Logo"] = $logo;
        $ErrObj["Error"]["ErrorImage"] = $ErrorImage;
        $ErrObj["Error"]["Markup"] = '<div class="page-error {{Error_Class}}">
        <div class="PageData w3-hide">
        {{Error_Data}}
        </div>
        <div class="page-error-img zoomInShort animated delay-0-1s"><img src="'.$epcoredir.$ErrorImage.'" /></div>
        <div  class="page-error-txt zoomInShort animated delay-0-3s">'.$errindex.' : '.$Errors[$errindex].'</div>
        </div>';
        //"ErrorImage"=>"images/bbwa/error-img.png"
        if(count($param) > 0){
            //merge the other user define parameter
            $ErrObj["Error"] = array_merge($ErrObj["Error"],$param); 
            if(!isset($ErrObj["Error"]["PageClass"]))$ErrObj["Error"]["PageClass"] = "";
        }
    }
    return $ErrObj;
}
function Error($errindex = -1,$msg="",$param = [],$logo = "exclamation-triangle"){
    exit(json_encode(InternalError($errindex,$msg,$param,$logo)));
}
//get file type
function file_mime_type($file, $encoding=true) {
    $mime=false;

    if (function_exists('finfo_file')) {
        $finfo = finfo_open(FILEINFO_MIME);
        $mime = finfo_file($finfo, $file);
        finfo_close($finfo);
    }
    else if (substr(PHP_OS, 0, 3) == 'WIN') {
        $mime = mime_content_type($file);
    }
    else {
        $file = escapeshellarg($file);
        $cmd = "file -iL $file";

        exec($cmd, $output, $r);

        if ($r == 0) {
            $mime = substr($output[0], strpos($output[0], ': ')+2);
        }
    }

    if (!$mime) {
        return false;
    }

    if ($encoding) {
        return $mime;
    }

    return substr($mime, 0, strpos($mime, '; '));
}
if(!function_exists('Uploader')){
//#Uploader - upload file send via aim Ajax Post
function Uploader($path = "../aim-files/",$sfile="",$filename = "",$mimetypes = "image/gif,image/jpeg,image/jpg,image/pjpeg,image/png"){
    $rptfailed = $rptsuccess = [];$single=false;$seen=false;
    $mimetypes = (is_string($mimetypes) && trim($mimetypes) == "")?"image/gif,image/jpeg,image/jpg,image/pjpeg,image/png":$mimetypes;
      $mimetypes = !is_array($mimetypes)?explode(",",strtolower($mimetypes)):$mimetypes;
   // $rptfailed[$key] = "aaa";
   $ddd = "ss";
   foreach($_FILES as $key=>$file){
   
    $filename = trim($filename) == ""?$key:$filename;
       if(trim($sfile) != ""){
        
           if(trim($key) != trim($sfile)){
           // $ddd = $key;
               continue;
           }
           
           $single = true;
       }
       $seen = true;
       
   //if($_FILES[$nme]){ //get passport
      $fileTmpLoc = $file["tmp_name"];
      //check if multiple file sent
      if(is_array($fileTmpLoc)){
        
          foreach($fileTmpLoc as $ind=>$val){
            $file_name = $file["name"][$ind];
            $file_temp = $val;
            //get mime type
            $mimet = file_mime_type($file_temp,false);
            if(in_array($mimet,$mimetypes)){
            $file_dest = rtrim($path,"/\\")."/";
            $file_fname = $filename."_".$ind;
            $rnamarr = explode(".",$file_name);
            $file_ext = $rnamarr[count($rnamarr) - 1];
            //Handle blob file extention for now
            if($file_ext == "blob")$file_ext = "png";
            $performu = PerformUpload($file_name,$file_temp,$file_dest,$file_fname,$file_ext);
            if($performu !== true){
                $rptfailed[$key] .= $performu . ";";
            }else{
                $rptsuccess[$key] .= $file_dest . $file_fname.".".$file_ext.";";
            }
        }else{
            $rptfailed[$key] .= "Invalid File Type" . ";";
        }
          }
          if(isset($rptfailed[$key]))$rptfailed[$key] = rtrim($rptfailed[$key],";");
          if(isset($rptsuccess[$key]))$rptsuccess[$key] = rtrim($rptsuccess[$key],";");
      }else{
        $mimet = file_mime_type($fileTmpLoc,false);
        if(in_array($mimet,$mimetypes)){
        $rnamarr = explode(".",$file["name"]);
        $file_ext = $rnamarr[count($rnamarr) - 1];
        //Handle blob file extention for now
        if($file_ext == "blob")$file_ext = "png";
        $performu = PerformUpload($file["name"],$fileTmpLoc,rtrim($path,"/\\")."/",$filename,$file_ext);
        if($performu !== true){
            if(!isset($rptfailed[$key]))$rptfailed[$key]="";
            $rptfailed[$key] .= $performu;
        }else{
            if(!isset($rptsuccess[$key]))$rptsuccess[$key]="";
            $rptsuccess[$key] .= rtrim($path,"/\\")."/" . $filename.".".$file_ext;
        }
    }else{
        $rptfailed[$key] .= "Invalid File Type";
    }
      }
      $seen = true;
      if($single)break;
   //}
  }
  if(!$seen){
    //$sfile
   
    //$rptfailed[$sfile] = "No File Founds - ".$ddd;
}
  return array("Failed"=>$rptfailed,"Success"=>$rptsuccess);
}
}
if(!function_exists('PerformUpload')){
    function PerformUpload($file_name,$file_temp,$file_dest,$file_fname,$file_ext){
    $rnam = $file_name;
      
     //return "yommy";
      if($file_temp){
          if(!file_exists($file_dest)){
              
              $mkd = mkdir($file_dest,0777,true);
              if(!$mkd){
                return "Cannot create distination Directory";
              }
          }
          //../asset/customer/passport/6411311.jpg
          if(!move_uploaded_file($file_temp, $file_dest."$file_fname.$file_ext")){ //upload file
             // exit("#Operation Aborted: Passport Upload Failed");
             return "Moving file to destination failed";
          }else{
           return true;
          }
      }
      return "Invalid File";
}
}


?>