<?php
session_start();
//sleep(3);

$param = isset($_POST['Param'])?json_decode(urldecode($_POST['Param']),true):[];
unset($_POST["Param"]);
$_POST = array_merge($_POST,$param);

$epcoredir = isset($_POST['Core'])?$_POST['Core']:"";
$GLOBALS['epcoredir'] = $epcoredir;
$err = '<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.'{{Error_Image}}" /></div>
<div  class="page-error-txt zoomInShort animated delay-0-3s">{{Error_Code}} : {{Error_Message}}</div>
</div>';
$GLOBALS['err'] = $err;
//confirm if parameter sent
if(!isset($_POST['ApplyID']) || (int)$_POST['ApplyID'] == 0){
    exit(str_replace(array('Error_Code','Error_Message'),array('10','Invalid Application'),$err));
}

function ReplyError($Error_Code,$Error_Message,$Error_Image){
  global $err;
  exit(str_replace(array('{{Error_Code}}','{{Error_Message}}','{{Error_Image}}'),array($Error_Code,$Error_Message,$Error_Image),$err));
}



include "api.php";
$LRegNo = isset($_SESSION['LRegNo'])?$_SESSION['LRegNo']:'';
$_SESSION = $_POST;
$_SESSION['LRegNo'] = $LRegNo;
$_SESSION['LoginName'] = $LRegNo;

//get the school subdomain using the formbuilder
$subdir = $_POST['SubDir'];

if(isset($_SESSION['Config']) && trim($_SESSION['Config']) != ""){
$config = $_SESSION['Config'];
}else{
//get the school config settings
$config = file_get_contents("../../../{$subdir}config.json");
$_SESSION['Config'] = $config; //keep in session for faster load
}

if($config == "")exit(str_replace(array('{{Error_Code}}','{{Error_Message}}','{{Error_Image}}'),array('--1','Reading Setup Failed',"images/bbwa/error-img.png"),$err));
$config = substr($config,strpos($config,"{")) ;
$config = json_decode($config,true);
if($config === null)exit(str_replace(array('{{Error_Code}}','{{Error_Message}}','{{Error_Image}}'),array('--2','Invalid Config Structure',"images/bbwa/error-img.png"),$err));
//reset the controls url, to be relative to this form builder scritp
$cmk = $config["ControlMarkup"];
//exit(str_replace(array('{{Error_Code}}','{{Error_Message}}'),array('--2',$config["ControlMarkup"]),$err));
if(substr(trim($cmk),0,strlen('epcore/')) == 'epcore/'){
  $config["ControlMarkup"] = "../".substr(trim($cmk),strlen('epcore/') - 1);
}else{
  $cmkarr = explode('/epcore/',$cmk);
if(count($cmkarr) == 2){
  $config["ControlMarkup"] = "../".$cmkarr[1];
}
}

$epapi = new epapi($config);

$epapi->OnErrorWriteStart();
echo $err;
$epapi->OnErrorWriteExit();



$_POST = array_merge($_SESSION,$_POST);
//convert json values to object
foreach($_POST as $key=>$val){
  if(is_string($val) && substr(trim($val),0,1) == "{"){
      $jobj = json_decode($val,true);
      if(!is_null($jobj))$_POST[$key] = $jobj;
  }
  }

//request Form
$pageform = $epapi->Request(["RequestID"=>"R005","Param"=>json_encode($_POST)]);

//print_r($_POST);
//echo "*******************";
  /*  print_r($pageform);
exit(); */   

$epapi->OnErrorWriteStart();
echo $err;
$epapi->OnErrorWriteExit();

$markup = $pageform['PageMarkup'];
$epapi->WriteStart();
if(file_exists($markup)){
   include $markup; 
}else{
    $obj = json_decode($markup,true);
    $rtnmk = "";
    if(is_null($obj)){
      $rtnmk = $markup;
    }else{
      $rtnmk = $epapi->BuildForm($obj,true);
    }
    $rtn = [];
    if(isset($_POST['__Alert__'])){
      $rtn = ["Alert"=>$_POST['__Alert__'],"Markup"=>$rtnmk];
    }else{
      $rtn =  ["ApplyGroupID"=>$pageform['ApplyGroupID'],"ApplyID"=>$pageform['ApplyID'],"NextPageNum"=>$pageform['NextPageNum'],"NowPageNum"=>$pageform['NowPageNum']];
    }
    if(isset($pageform['__Notify__']))$rtn['__Notify__'] = $pageform['__Notify__'];
    if(isset($rtn['Error'])){
      ReplyError($rtn['Error']['Code'],$rtn['Error']['Message'],$rtn['Error']['ErrorImage']);
    }
 
    //"Markup"=>$rtnmk,
   //echo json_encode($obj)."d";
    echo $rtnmk."@@!!~~#@".json_encode($rtn);
    
}

$epapi->WriteEnd();  ?>