<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
//check priv
AllowUser("ptype");
if(!isset($_POST['PayID']) || trim($_POST['PayID']) == "")exit("#Invalid Payment Type Selected");
//get the id
$PayID = (int)$_POST['PayID'];
//get the payment type details
$PayTypeDet = $PayID > 0?$dbo->SelectFirstRow("item_tb","","ID=".$PayID,MYSQLI_ASSOC):[];
if((!is_array($PayTypeDet) || count($PayTypeDet) == 0) && (!isset($_POST['Type']) || (int)$_POST['Type'] == 0))exit("#Reading Payment Type Details Failed");
   //control table
   $controltbarr = [1=>"putme","form_tb","schoolpayment_tb"];
   if(!isset($_POST['Type']) || (int)$_POST['Type'] == 0){ //represent payment analysis is loaded when the payment type is se;ected

$ownermodule = array_search($PayTypeDet['ControlTable'],$controltbarr);
$ownermodule = $ownermodule === FALSE?3:$ownermodule;
$MID = $PayTypeDet['ControlTableID'];
   }else{
    $PayTypeDet['ControlTable'] = $controltbarr[$_POST['Type']];
    $ownermodule = $_POST['Type'];
    $MID = $_POST['MID'];
   }

//exit("#".$ownermodule);
$PayTypeDet['OwnerModule'] = $ownermodule;

//get the payment control details
$paycntrdet = $dbo->SelectFirstRow($PayTypeDet['ControlTable'],"","ID=".$MID);

//if(!is_array($paycntrdet))exit("#Reading Owner Module Settings Failed - ".$PayTypeDet['ControlTable']);
//if(!is_array($paycntrdet) || $paycntrdet[0] < 1)exit("#Reading Owner Module Settings Failed - ".$_POST['Type']);
$partpayshare = is_array($paycntrdet) && isset($paycntrdet['PartPayShare'])?$paycntrdet['PartPayShare']:"HALF";
$partpaystatus = is_array($paycntrdet) && isset($paycntrdet['PartPay'])?$paycntrdet['PartPay']:"FALSE";
$payanalysis = trim(isset($PayTypeDet['PayBrkDn'])?$PayTypeDet['PayBrkDn']:"");
$dump = [];

if($payanalysis != ""){
    
//get individual payment items
$payanalysisarr = explode("***",$payanalysis);
//exit($payanalysisarr);

if(count($payanalysisarr) > 0){
    
    foreach($payanalysisarr as $indpayanal){
       
        $newarr = [];
        //breakdown conditional part
   $condpratsbrkdn = explode("?",$indpayanal);
   $CondAttrID=0;$CondVal="";$useop = "";
   if(count($condpratsbrkdn) > 1){ //if conditon exist
  
   //Proccess Condition Section
 //******************************************** */
 $cond = $condpratsbrkdn[0];
 $currop = [1=>"==","!=","<=",">=","<",">"];
 $condbrkdn=[];
 foreach($currop as $k=>$opr){
    $condbrkdn = explode($opr,$cond);
    if(count($condbrkdn) == 2){
        $useop = $k;break;
    }
 }
 //breakdown condition
 
 //for now != not handled @@@@@@@@@@@@@@@@@@@@@@
 $CondAttrID=0;$CondVal="";
 if($useop !== ""){
    $condarr = array("None","StateId","Gender","MaritalStatus","StartSes","ModeOfEntry","ProgID","FacID","StudyID");
     //array("None","State of Origin","Gender","Marital Status","Set/Batch","Mode Of Entering","Department","Faculty/School","Study")
    $CondAttr = $condbrkdn[0]; $CondVal = $condbrkdn[1];
$CondAttrID = array_search($CondAttr,$condarr);
if($CondAttrID === FALSE){$CondAttrID=0;$CondVal="";}
 }
 
 //******************************************** */

    $indpayanalr = $condpratsbrkdn[1];
   }else{
    
    $indpayanalr = $condpratsbrkdn[0];
   }
     //get the individual breakdown items
     $indbrkdnitarr = explode("|",$indpayanalr);
     //exit(count($indbrkdnitarr)."");
     if(count($indbrkdnitarr) > 2){
       
       $itemname = $indbrkdnitarr[0];
       $lvlamt = $indbrkdnitarr[1];
       $parts = $indbrkdnitarr[2];
       $status = isset($indbrkdnitarr[3])?$indbrkdnitarr[3]:"1";
       $period = isset($indbrkdnitarr[4])?$indbrkdnitarr[4]:"";

 //Proccess ItemName Section
 //******************************************** */
$itemnameobj = json_decode($itemname,true);
$id = 0; $itemnamer = "";
if(is_array($itemnameobj)){ //if valid json name
    $id = $itemnameobj['ID'];
    if($id < 0)continue; //meaning is a technical included payment item e.g Transaction Charge i.e they cannot be modified by user
    $itemnamer = $itemnameobj['Name'];
}else{//if not valid, assume is the old format
 //add it to the payitem_tb and modify the break down
  $newid = $dbo->InsertID2("payitem_tb",["ItemName"=>$itemname]);
if(is_numeric($newid))$id = $newid;
$itemnamer = $itemname;
}
//Form the new item name string
$ItemNameString = json_encode(["ID"=>$id,"Name"=>$itemnamer]);
//******************************************** */


//Proccess Levels Section
//******************************************** */ 
$otherlvlamts = []; //hold the level and its coresponding amt if defferent from the first
$otherlvlshare = [];
$firstAmt = 0; //hold the am
 $lvls = [];
//breakdown levels
if(trim($lvlamt) != ""){
   
 $lvlamtarr = explode("~",$lvlamt); //breakdown all levels
 
 foreach($lvlamtarr as $indlvlamt){ //loop through
    $indlvlamtarr = explode("=",$indlvlamt); //get the level and its amt
if(count($indlvlamtarr) == 2){ //if valid
 $lvlID = (int)$indlvlamtarr[0]; //level id
 $lvlAmt = (float)$indlvlamtarr[1]; //amt
 if($lvlID < 0){ //if any level rule is set (meaning all the level applies) - set only it and descard other settings if exist
    $lvls = [];
    $lvls[$lvlAmt] = [$lvlID];
    break;
 }
 if(isset($lvls[$lvlAmt])){ //check if entering for the amt is already entered
   $lvls[$lvlAmt][] = $lvlID;
 }else{ //f not start its entering
    $lvls[$lvlAmt] = [$lvlID];
 }
 
 //check if the current level amt is not equal to the previous one
 /* if($lvlAmt != $firstAmt && $firstAmt != 0){
     //add to new level entreing
     $otherlvlamts[$lvlID] = $lvlAmt;
     $otherlvlshare[$lvlID] = [];
     continue;
 }
$lvls[] = $lvlID; //add to levels array
 if($firstAmt == 0)$firstAmt = $lvlAmt; //use the first level amount as the amount
if($lvlID < 0)$firstAmt = $lvlAmt; //set the amt if all level found */
}else{
 //if not valid level amt
}
 }
}
//******************************************** */

//Proccess Part Payment Section
//******************************************** */
$partsharearr = [];
foreach($lvls as $firstAmt=>$idarr){
    //$partsharearr = [];
//if(!isset($partsharearr[$firstAmt])){
   // $partsharearr[$firstAmt] = $partpayshare == "HALF"?["",""]:["","","",""];
    $partsharearr[$firstAmt] = [];
//} 
$partseen = [];
$quatertype = false; //help determine if the sent structure is quaterly
//break it down
$partsarr = explode("~",$parts);
foreach($partsarr as $indpart){
   
    //$partsharearr[$firstAmt] = [];
  //get the part and the share
  $partshare = explode("=",$indpart);
//if(count($partshare) == 2){
  $key = $partshare[0];
$keyst = explode("_",$key);
   if($quatertype == false && count($keyst) > 1)$quatertype = true;
  //perform for all level $lvls[$lvlAmt] = [$lvlID]
  
   if(trim($key) == '3'){ //if its full payment
    $partsharearr[$firstAmt][0] = $firstAmt;
    $partseen[0] = $partsharearr[$firstAmt][0];
    //break;
   }
   //$partsharearr[$firstAmt][3] = $partsharearr[$firstAmt][2];
   //if it is part half (first)
   
   if(trim($key) == '1' || trim($key) == '1_1'){
    $partsharearr[$firstAmt][0] = isset($partshare[1])?round((float)$partshare[1]*$firstAmt):$firstAmt;
    $partseen[0] = $partsharearr[$firstAmt][0];
   }

   //if it is part half (second)
   if(trim($key) == '2' || trim($key) == '1_2'){
    $partsharearr[$firstAmt][1] = isset($partshare[1])?round((float)$partshare[1]*$firstAmt):$firstAmt;
    $partseen[1] = $partsharearr[$firstAmt][1];
  
   }

   if(trim($key) == '2_1'){
    $partsharearr[$firstAmt][2] = isset($partshare[1])?round((float)$partshare[1]*$firstAmt):$firstAmt;
    $partseen[2] = $partsharearr[$firstAmt][2];
   }

   if(trim($key) == '2_2'){
    $partsharearr[$firstAmt][3] = isset($partshare[1])?round((float)$partshare[1]*$firstAmt):$firstAmt;
    $partseen[3] = $partsharearr[$firstAmt][3];
   }

   //reform based on the partpay share
   $totpart = count($partseen);
   
   if($partpayshare == "HALF" && $quatertype == true){
        $partsharearr[$firstAmt][0] = !isset($partsharearr[$firstAmt][0])?0:$partsharearr[$firstAmt][0];
        $partsharearr[$firstAmt][1] = !isset($partsharearr[$firstAmt][1])?0:$partsharearr[$firstAmt][1];
        $partsharearr[$firstAmt][2] = !isset($partsharearr[$firstAmt][2])?0:$partsharearr[$firstAmt][2];
        $partsharearr[$firstAmt][3] = !isset($partsharearr[$firstAmt][3])?0:$partsharearr[$firstAmt][3];
        $partsharearr[$firstAmt] = [$partsharearr[$firstAmt][0] + $partsharearr[$firstAmt][1],$partsharearr[$firstAmt][2] + $partsharearr[$firstAmt][3]]; //first payment
       
   }

   if($partpayshare == "HALF" && $totpart < 2){
    $partsharearr[$firstAmt][1]="";
    
    }

     if($partpayshare != "HALF" && $totpart < 3){
     
    if(isset($partsharearr[$firstAmt][1]) && trim($partsharearr[$firstAmt][1]) != ""){
      $partsharearr[$firstAmt][2] =$partsharearr[$firstAmt][1];
      $partsharearr[$firstAmt][1] = "";
      
    }else{
        $partsharearr[$firstAmt][1] = "";
      $partsharearr[$firstAmt][2] = isset($partsharearr[$firstAmt][2])?$partsharearr[$firstAmt][2]:"";
    }
    $partsharearr[$firstAmt][3] = isset($partsharearr[$firstAmt][3])?$partsharearr[$firstAmt][3]:"";;
   

 }else{
   // $partsharearr[$firstAmt][3] = $dtarrstr;
 }

   }

  

}

   
//}
}

//******************************************** */
foreach($lvls as $firstAmt=>$idarr){
     //form new array
     if(count($idarr) < 1){
        $idarr = 0;
     }else if(count($idarr) == 1){
        $idarr = $idarr[0];
     }else{
        $idarr = ":".implode("::",$idarr).":";
     }
     $newarr = [$id,$idarr,$CondAttrID,$useop,$CondVal,$period];
     $sm = 0;
     ksort($partsharearr[$firstAmt]);
     foreach($partsharearr[$firstAmt] as $indamt){ //loop through individual amt
        if($partpaystatus == "TRUE")$newarr[] = trim($indamt) != ""?number_format($indamt,2):"";
        //$newarr[] = trim($indamt) != ""?$indamt:"";
        $sm += $indamt;
     }
    // $newarr = array_merge([$id,$lvls,$CondAttrID,$useop,(int)$CondVal],$partsharearr);
     $newarr[] = number_format($firstAmt,2);
     $newarr[] = $status;
     
     $dump[] = $newarr;
    }

     }


     
//check if other level amt exist

    }
}

echo json_encode($PayTypeDet);
echo "~~!!";
//echo json_encode($partsharearr);
//echo $partpayshare.json_encode($dump);
//echo $partpayshare;
$studys = $dbo->RunQuery("SELECT ID, Name FROM study_tb WHERE SchoolType = (SELECT Type FROM school_tb LIMIT 1)");
    // $studyData = [];
    
     if(is_array($studys) && $studys[1] > 0){
         $qstrs = "";
         while($indstudys = $studys[0]->fetch_assoc()){
            //$qstrs .= "A"; continue;
             $qstrs .= " UNION SELECT '-1' as Level, 'ANY' as Name";
             
             $qstrs .= " UNION ";
            
             //get all programme in the faculty
             $qstrs .= "select Level, CONCAT('LEVEL ',Level) as Name from schoollevel_tb where StudyID = {$indstudys['ID']}  and SchoolTypeID = (select Type from school_tb limit 1)";
             //$studyData[$indstudys['ID']] = $indstudys['Name'];
            // continue;
         }
         $qstrs = ltrim($qstrs," UNION ");
        }
$headerd = array(
    "*PItems"=>array("ITEM","#select ID,ItemName from payitem_tb UNION select '#' as ID, '".$dbo->SqlSafe('<a href="javascript:Page.OpenByTabName(\'psetting\')"><i class="fa fa-plus"></i> Add Payment Item</a>')."' as ItemName"),
    /* "*PStudys"=>array("STUDY",$dbo->DataString(TextBoxSQL("select ID,Name from study_tb WHERE SchoolType = (select Type from school_tb limit 1)"))),
   "*PLevel"=>array("LEVEL","#select Level, Name from schoollevel_tb where StudyID = ?PStudys? and SchoolTypeID = (select Type from school_tb limit 1) order by Level",true), */
   //"*PLevel"=>array("LEVEL","@cportal/Pages/Scripts/Payment/paytypecond.php PayTypeLevel",true),
   "*PLevel"=>array("LEVEL",$dbo->DataString(TextBoxSQL($qstrs)),true),
   "*PCond"=>array("CONDITION",$dbo->DataString(
    array("None","State of Origin","Gender","Marital Status","Set/Batch","Mode Of Entering","Department","Faculty/School","Study")
   )),
   "*CondOp"=>array("OPERATOR","1=IS&2=IS NOT&3=IS OR LESS THAN&4=IS OR GREATER THAN&5=LESS THAN&6=GREATER THAN"),
   "*PVal"=>array("VALUE","@cportal/Pages/Scripts/Payment/paytypecond.php PayTypeCondValue Cond=?PCond?"));
   $headerd["*PPeriod"]=array("PERIOD","_CALENDAR_RANGE_");
   $totdis = "";
   if($partpaystatus == "TRUE"){
   $headerdamt = $partpayshare == "HALF"?["*Fpay"=>"FIRST","*Spay"=>"SECOND"]:["*Fpay"=>"FIRST 1","*FpayComplete"=>"FIRST 2","*Spay"=>"SECOND 1","*SpayComplete"=>"SECOND 2"];
   $headerd = array_merge($headerd,$headerdamt);
   //$totdis = ",disable=PTot";
   $totdis = "";
   }
   $headerd["*PTot"] = "FULL";
   $headerd["*PStatus"]=array("ENABLED","YES|NO");
  
  
  SpreadSheet("rowselect=false,style=width:calc(100% - 16px);margin:auto;margin-top:0px;margin-bottom:6px,id=paytypeanal,multiselect=false,cellfocus=,cellblur=Payment.PaymentType.FormatAmt,cellkeypress=Payment.PaymentType.TotalAmt,dynamiccolumn=false,dynamicrow=true,minrow=11,rowfilter=true$totdis,filtertitle=FILTER RULE LIST,filterstyle=width:calc(100% - 16px);margin:auto;margin-top:10px,disable=PID",$headerd,$dump);
  TextBoxGroup("width:calc(100% - 16px);margin:auto;text-align:center");
  Note();
  echo "Simulate to view Payment Breakdown based on the Ruleset (Student Payment Analysis Slip) <br/>****** Save Updates before Performing Simulation ******";
  _Note();
  _TextBoxGroup();
  FlatButton("text=Run a Simulation on the Payment Type, style=margin:auto; margin-top:5px; width:500px,onclick=Payment.PaymentType.Test(),logo=tasks,id=testpaytypebtn");

   

//echo $PayID;


?>