<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
 //check priv
 AllowUser("ptype");


 //get params
 /* var data = "SelType="+rcellval+"&Name="+escape(typename)+"&Currency="+currency+"&Ref="+escape(itemref)+"&PayScope="+escape(payscope)+"&ModuleTB="+moduletb+"&ModuleTBID="+mcellval+"&discolumns="+rawescape(discolumns)+"&ruleset="+rawescape(rulesets); */
 //exit($_POST['ruleset']);descr
extract($_POST);
//function to Proccess the rule set
function ProccessRuleSet(){
	global $discolumns;
	global $ruleset;
	global $dbo;
	//convert datastrings to array
	$duscolumnsarr = $dbo->DataArray($discolumns);
	
	
	$rulesetarr = $dbo->DataArray($ruleset);
	
	if(count($duscolumnsarr) == 0 || count($rulesetarr) == 0)exist('{"Error":"Invalid Ruleset"}');
	 //get the maximum row
	$maxrw = (int)$rulesetarr['MaxDataRow'];
	if($maxrw < 1)return "";
	
	//get all the payment items
	$allpayitem = $dbo->Select("payitem_tb");
	if(!is_array($allpayitem) || $allpayitem[1] < 1)exist('{"Error":"Internal Error, Reading Payment Item Failed"}');
	$payitems = ["More Condition"];
	while($payitem = $allpayitem[0]->fetch_assoc()){
		$payitems[$payitem['ID']] = $payitem['ItemName'];
	}
	
	/*  PItems=1&PLevel=2&PCond=3&CondOp=4&PVal=5&Fpay=6&FpayComplete=7&Spay=8&SpayComplete=9&PTot=10 */
	$formedstr = [];
	
	//loop tru every rows
	for($rid=1; $rid <= $maxrw; $rid++){
	   //loop tru each displayed columns
	   //check if banner 
		if(trim($rulesetarr[$rid."_banner"]) != "#"){
			$formedstr[] = "##".$rulesetarr[$rid."_banner"]; //add the banner
			continue;
		}
		//get the Item
		if(!isset($rulesetarr[$rid."_".$duscolumnsarr['PItems']]) || trim($rulesetarr[$rid."_".$duscolumnsarr['PItems']]) == "" || trim($rulesetarr[$rid."_deleted"]) == "true")continue;
		$pitem = $rulesetarr[$rid."_".$duscolumnsarr['PItems']];

		

		//if(trim($pitem) == "")continue; //if no payment item selected ignore and continue
		if(!isset($payitems[$pitem]) && (int)$pitem > 0)exit('#Invalid Payment Item Selected in Ruleset. Unable to Read Payment Item Name');
		if((int)$pitem > -1)$pitemnm = $payitems[$pitem];
	
	   
		if((int)$pitem > -1){ //if not more condition operation
			//get the total amount
		if(!isset($rulesetarr[$rid."_".$duscolumnsarr['PTot']]))exit('#Invalid Amount Set in Ruleset. Ruleset Total Amount (FULL) is Compulsary');
		$ptotamt = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['PTot']]);
	
		//get the level - if not set all will be selected
		$plvl = "";
		if(!isset($rulesetarr[$rid."_".$duscolumnsarr['PLevel']])){
			$plvl = "-1=".$ptotamt;  
		}else{
			//check if multiple selected
		   $clvl = trim($rulesetarr[$rid."_".$duscolumnsarr['PLevel']]);
	if($clvl == "-1" || strpos($clvl,":-1:") !== FALSE){
		$plvl = "-1=".$ptotamt;
		//$plvl = "-1exist=".$clvl;
	}else{
	  $plvl = implode("=".$ptotamt."~",explode("::",trim($clvl,":")))."=".$ptotamt;
	}
		  
		}
		}
		
	
		$pcond = "";$popr = "";$pval = "";
		//if condition set
		if(isset($rulesetarr[$rid."_".$duscolumnsarr['PCond']]) && (int)$rulesetarr[$rid."_".$duscolumnsarr['PCond']] > 0){
		  $pcondid = (int)$rulesetarr[$rid."_".$duscolumnsarr['PCond']];
		  if((int)$pitem < 0 && $pcondid < 1)continue; //if it is a more condition operation and no condition set skip the rule
		  $condarr = array("None","StateId","Gender","MaritalStatus","StartSes","ModeOfEntry","ProgID","FacID","StudyID","FacGrpID","Degree","AdmSes","ClassID");
      $pcond = $condarr[$pcondid];
      
      //"1=IS&2=IS NOT&3=IS OR LESS THAN&4=IS OR GREATER THAN&5=LESS THAN&6=GREATER THAN"
	     $condoparr = [1=>"==","!=","<=",">=","<",">"];
		  //get the operator
		  $popr = !isset($rulesetarr[$rid."_".$duscolumnsarr['CondOp']]) || (int)$rulesetarr[$rid."_".$duscolumnsarr['CondOp']] == 1?"==":$condoparr[(int)$rulesetarr[$rid."_".$duscolumnsarr['CondOp']]];
	
		  //get value
		  $pval = "";
		  //if no value set, will render the entire conditon invalid
			if(!isset($rulesetarr[$rid."_".$duscolumnsarr['PVal']]) || trim($rulesetarr[$rid."_".$duscolumnsarr['PVal']]) == ""){
				$pcond = "";
			}else{
			  $pval = $rulesetarr[$rid."_".$duscolumnsarr['PVal']];
			}
	
		}
	
		//form the condition string
	if($pcond != ""){
		$pcond = (int)$pitem > -1?$pcond.$popr.$pval."?":$pcond.$popr.$pval;
	}
	$partstatus = $_POST['partstatus'];
	$partshare = $_POST['partshare'];
	$maxsem = $_POST['maxsem'];
//exit("".$partstatus);

	if((int)$pitem > -1){
			//form the parts
			$partstr = [];
	if($partstatus == "FALSE"){ //if no part structure - if FULL Payment only
		$partstr = ["3"];
	}else{
	   //check if it half
		if($partshare == "HALF"){

			//loop trou all sem
			for($d=1;$d<=$maxsem;$d++){
				if(isset($rulesetarr[$rid."_".$duscolumnsarr['F'.$d."F3"]])){
					$fpay = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['F'.$d."F3"]]);
					$fpayfrac = $fpay/$ptotamt;
					$partstr[] = $d."=".$fpayfrac;
						  }
			}
		  /* //get the FPay
		  if(isset($rulesetarr[$rid."_".$duscolumnsarr['Fpay']])){
	$fpay = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['Fpay']]);
	$fpayfrac = $fpay/$ptotamt;
	$partstr[] = "1=".$fpayfrac;
		  }
	
	//get the SPay
	if(isset($rulesetarr[$rid."_".$duscolumnsarr['Spay']])){
		$spay = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['Spay']]);
		$spayfrac = $spay/$ptotamt;
		$partstr[] = "2=".$spayfrac;
			  } */
		}else{ //if quater
		
			//loop trou all sem
			for($d=1;$d<=$maxsem;$d++){
				foreach([1,2,3] as $partnum){
					if(isset($rulesetarr[$rid."_".$duscolumnsarr['F'.$d."F".$partnum]])){
						$fpay = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['F'.$d."F".$partnum]]);
						$fpayfrac = $fpay/$ptotamt;
						$partstr[] = $d."_".$partnum."=".$fpayfrac;
							  }
				}
				
			}

			//get the FPay
		/*   if(isset($rulesetarr[$rid."_".$duscolumnsarr['Fpay']])){
			$fpay = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['Fpay']]);
			$fpayfrac = $fpay/$ptotamt;
			$partstr[] = "1_1=".$fpayfrac;
				  }
			
			//get the SPay
			if(isset($rulesetarr[$rid."_".$duscolumnsarr['Spay']])){
				$spay = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['Spay']]);
				$spayfrac = $spay/$ptotamt;
				$partstr[] = "2_1=".$spayfrac;
					  }
			
					  
	
			//get the FPayComp
		  if(isset($rulesetarr[$rid."_".$duscolumnsarr['FpayComplete']])){
			$fpaycomp = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['FpayComplete']]);
			$fpaycompfrac = $fpaycomp/$ptotamt;
			$partstr[] = "1_2=".$fpaycompfrac;
				  }
			
			//get the SPayComp
			if(isset($rulesetarr[$rid."_".$duscolumnsarr['SpayComplete']])){
				$spaycomp = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['SpayComplete']]);
				$spaycompfrac = $spaycomp/$ptotamt;
				$partstr[] = "2_2=".$spaycompfrac;
					  }

					  //get the FPayFull
			if(isset($rulesetarr[$rid."_".$duscolumnsarr['FpayFull']])){
				$fpayfull = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['FpayFull']]);
				$fpayfracfull = $fpayfull/$ptotamt;
				$partstr[] = "1_3=".$fpayfracfull;
					  }


					  //get the SPayFull
			if(isset($rulesetarr[$rid."_".$duscolumnsarr['SpayFull']])){
				$spayfull = (float)str_replace(",","",$rulesetarr[$rid."_".$duscolumnsarr['SpayFull']]);
				$spayfracfull = $spayfull/$ptotamt;
				$partstr[] = "2_3=".$spayfracfull;
					  } */
	
		}
	}
	
	//form the part string
	$partstr = implode("~",$partstr);
	
	//get the status
	$status = isset($rulesetarr[$rid."_".$duscolumnsarr['PStatus']])?$rulesetarr[$rid."_".$duscolumnsarr['PStatus']]:1;
	
	//get the period
	$period = isset($rulesetarr[$rid."_".$duscolumnsarr['PPeriod']])?$rulesetarr[$rid."_".$duscolumnsarr['PPeriod']]:"";

	$optional = isset($rulesetarr[$rid."_".$duscolumnsarr['POption']])?$rulesetarr[$rid."_".$duscolumnsarr['POption']]:0;
	
	$formedstr[] = $pcond.'{"ID":'.$pitem.',"Name":"'.$pitemnm.'"}|'.$plvl."|".$partstr."|".$status."|".$period."|".$optional;
	
}else{
	
	$laststr = $formedstr[count($formedstr) - 1];
	
	//explode to get the condtional part
	$condpart = explode("?",$laststr);
	if(count($condpart) > 1){
		$condpart[0] .= "&&" . $pcond;
		$formedstr[count($formedstr) - 1] = implode("?",$condpart);
	}else{
		$formedstr[count($formedstr) - 1] = $pcond."?".$laststr;
	}
}
	//return $pcond.'{"ID":'.$pitem.',"Name":"'.$pitemnm.'"}|'.$plvl."|".$partstr."|".$status;
	
	}
	
	return implode("***",$formedstr);
	 }
	 $multiorder = ($multiorder==0 || $PayScope == "w")?"FALSE":"TRUE";
//exit($multiorder);
$rule = ProccessRuleSet();

$SelType = (int)$SelType;
$controltbarr = [1=>"putme","form_tb","schoolpayment_tb"];
$ModuleTB = $controltbarr[$ModuleTB];
$paytypeData = ["ItemName"=>trim($Name),"ItemDescr"=>$descr,"PayBrkDn"=>$rule,"Currency"=>$Currency,"studType"=>$PayScope,"merchantID"=>0,"PaymentID"=>$Ref,"MerchantKey"=>"","ControlTable"=>$ModuleTB,"ControlTableID"=>$ModuleTBID,"PayGatewayID"=>$GID,"CollectBank"=>$CollectBank,"MultiOrder"=>$multiorder];
//exit(json_encode($paytypeData));
if($SelType == 0){ //if no selection, i.e add new pay
  //check if name already exist
  $nexit = $dbo->SelectFirstRow("item_tb","","TRIM(UCASE(ItemName))='".strtolower(trim($Name))."'");
  if(is_array($nexit))exit('#Adding Type Failed, Type Name Already Exist');
  /* `ID`, `ItemName`, `ItemDescr`, `PayBrkDn`, `Currency`, `studType`, `merchantID`, `PaymentID`, `MerchantKey`, `MerchantName`, `ControlTable`, `ControlTableID` */
  $ins = $dbo->InsertID("item_tb",$paytypeData);
  if(is_numeric($ins)){ //if inserted successfully
   exit("~".$ins);
  }else{
    exit("#Adding New Payment Type Failed");
  }

}else{ //if selected
   $upd = $dbo->Update("item_tb",$paytypeData,"ID=".$SelType);
   if(is_array($upd)){
    exit("~".$SelType);
   }else{
    exit("#Updating Payment Type Failed - ".$upd);
   }
}



?>