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

//Request Mapping
$Request = [
    "R000" => "DoNothing",
    "R001" => "GetSchoolDetails",
    "R002" => "GetStudentDetails",//LoginName
    "R003" => "CheckPassword", //Verify Accesscode
    "R004" => "GetApplications",
    "R005" => "GetPageElements",
    "R006" => "GetPaymentTypes",
    "R007" => "GetPaymentAmt",
    "R008" => "InitalizePayment",
    "R009" => "VerifyPayment",
    "R010" => "GetCandidate",
    "R011" => "GetStateOfOrigin",
    "R012" => "GetLGAreas",
    "R013" => "SaveCandidate",
    "R014" => "GetFaculty",
    "R015" => "GetProgrammeByFaculty",
    "R016" => "CreateUniqueRecord",
    "R017" => "CheckUniqueEntry",
    "R018" => "UpdateUniqueEntry",
    "R019" => "SendMail",
    "R020" => "GetSchoolDegrees",
    "R021" => "VerifyCandidate",
    "R022" => "AcceptAdmission",
    "R023" => "CandidateToStudent",
    "R024" => "GetAllApplications",
    "R025" => "ClearAllSessions",
    "R026" => "GetSchoolSession",
    "R027" => "GetStudentLevelSemester",
    "R028" => "GetAllPaymentTypes",
    "R029" => "OlevelGrades",
    "R030" => "OlevelSubjects",
    "R031" => "GetAllPaymentTypes2",
    "R032" => "GetHighestPayment",
    "R033" => "GetStudentCourses",
    "R034" => "RegisterCourses",
    "R035" => "UndoCourseRegistration",
    "R036" => "LoadCourseReg",
    "R037" => "LoadCoursesRegHistory",
    "R038" => "LoadPaymentHistory",
    "R039" => "GetStudentCurrentLevelSemester",
    "R040" => "WalletDetails",
    "R041" => "LoadResultHistory",
    "R042" => "LoadResultDetails",
    "R043" => "SendVerCode",
    "R044" => "VerifyApplicantEmail",
    "R045" => "LoadEntrancePayment",
    "R046" => "Entrance",
    "R047" => "AddReferee",
    "R048" => "OlevelExamType",
    "R049" => "SaveOlevelDetails",
    "R050" => "GetEntranceUploads",
    "R051" => "PerformEntranceUpload",
    "R052" => "LoadAcceptancePayment",
    "R053" => "Acceptance",
    "R054" => "ChangeEntranceVerField",
    "R055" => "PaymentAnalysis",
    "R056" => "UpdateOrderDet",
    "R057" => "GetStatistics",
    "R058" => "GetAllLevels",
    "R059" => "GetClassByProg"
];

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

//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",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"];

//Error Responce Handler
function InternalError($errindex = -1,$msg="",$param = [],$logo = "exclamation-triangle"){
    global $Errors;
    $ErrObj = ["Error"=>["Code"=>-1,"Message"=>"Unknown Error","Logo"=>$logo]];
    if(isset($Errors[$errindex])){
        $ErrObj["Error"]["Code"] = $errindex;
        $ErrObj["Error"]["Message"] = $Errors[$errindex].$msg;
        $ErrObj["Error"]["Logo"] = $logo;
        $ErrObj["Error"]["ErrorImage"] = "images/bbwa/error-img.png";
        //"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, '; '));
}
//#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 - ".$mimet;
    }
      }
      $seen = true;
      if($single)break;
   //}
  }
  if(!$seen){
    //$sfile
   
    //$rptfailed[$sfile] = "No File Founds - ".$ddd;
}
  return array("Failed"=>$rptfailed,"Success"=>$rptsuccess);
}

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";
}

?>