<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
//$mysqli = new mysqli()
function PadNum($Num){
  $Num = $Num."";
  $pad = 3 - strlen($Num);
  $rst = ($pad > 0)?str_repeat("0",$pad).$Num:$Num;
  //$rst = ($pad > 0)?str_pad($Num,$pad,"0",STR_PAD_LEFT):$Num;
  return $rst;
}
function MessageBack($str,$exitt = true){
    $str = EscapeString($str);
Box("style=color:red;width:100%;text-align:center; margin-top:20px;");
    Box("style=font-size:2em");Icon("exclamation-triangle");_Box();
    Text("text=$str,style=color:inherit;text-transform:uppercase;font-size:1.0em");
_Box();
if($exitt){
    exit();
}
}

//check priv
//AllowUser("manualp");

$inserted = false;
$RegNo = $dbo->SqlSafe($_POST['RegNo']);
$PayID = $dbo->SqlSafe($_POST['PayID']);
$Lvl = $dbo->SqlSafe($_POST['Lvl']);
$PayPol = $dbo->SqlSafe($_POST['PayPol']);
$paynow = isset($_POST['paynow'])?true:false;
$pre = $_POST['studType'];
//exit(json_encode($_POST));
$PayPolArr = explode("_",$PayPol);
$Sem = "";$SemPart = "3";
if(count($PayPolArr) > 1){
   $SemPart = $PayPolArr[1];
}
//exit($SemPart);
$Sem = $PayPolArr[0];
$idpref = isset($_POST['idpref'])?$_POST['idpref']:"";
$progID = GetStudentProgIDForPay($_POST['RegNo']);
$payhist = $dbo->Select4rmdbtbFirstRw("order_tb","","RegNo = '$RegNo' AND Lvl = $Lvl AND ItemID = $PayID AND Sem = $Sem AND SemPart = $SemPart AND ProgID = $progID ORDER BY Sem desc, SemPart desc");
// $payhist = $dbo->Select4rmdbtbFirstRw("order_tb","","RegNo = '$RegNo' AND Lvl = $Lvl AND ItemID = $PayID AND (Sem > $Sem  OR (Sem = $Sem AND SemPart >= $SemPart)) ORDER BY Sem desc, SemPart desc");
$itemdet = $dbo->Select4rmdbtbFirstRw("item_tb","","ID={$PayID}");
$PayBrkDn = "";
if(is_array($itemdet)){ //get the payment general structure from item_tb
    $ItemPayBrkDn = $itemdet['PayBrkDn'];
}else{
    // Display Error message (Cannot get Payment details)
    MessageBack("payment type not found");
}
//$payhist = $dbo->RunQuery("SELECT * FROM order_tb WHERE RegNo = '$RegNo' AND Lvl = $Lvl AND PayID = $PayID AND Sem = $Sem AND SemPart = $SemPart");
//$Amt = 0.0;
$PayStatus = 0;
$orderinfodel = 0; //use to indicate if student place order and payment not made
$TransNum = "";
$topPaid = 0;
$offlineRequest = false; //use to determine if offline payment already requested
if(is_array($payhist)){ //if payment or order found
   // exit(json_encode($payhist));
if($payhist['Channel'] == "OFFLINE")$offlineRequest = true; //if order info found and channel is offline, means offline approval request already made
if((int)$payhist['Paid'] == 0){
    $orderinfodel = 1;
}
   if((int)$payhist['Sem'] > (int)$Sem &&  (int)$payhist['Paid'] == 1){ //if higher payment found
       //MessageBack("Invalid Payment Policy Selected: Complete Payment Already Made");
       $topPaid = 1;
   }
   if((int)$payhist['SemPart'] > (int)$SemPart && (int)$payhist['Paid'] == 1){ //if higher payment found
      // MessageBack("Invalid Payment Policy Selected: Complete Semester Payment Already Made");
      $topPaid = 1;
   }
   $PayStatus = (int)$payhist["Paid"]; //get payment status
   $Amt = (float)$payhist["Amt"];
   $paybrkdwn = trim($payhist['BrkDwn']); //get the payment brekdown
   
   $paybrkdwn = $paybrkdwn == ""?FormBreakDown():array($Amt,-1,$paybrkdwn); //leaving the formated amt parameter as -1 help determine that break down is gotten from order_tb
   //store the transnum to use in client for printing
   $TransNum = $payhist['TransNum'];
}else{ //if no order found 
 
   $paybrkdwn = FormBreakDown();
   //print_r($paybrkdwn);
   //exit();
   $Amt = $paybrkdwn[0];
}
//exit(json_encode($paybrkdwn));
if($inserted){
    Hidden("pninserted",$RegNo);
}
$AdManualPay = SchoolPayDet();
$AdManualPay = (is_array($AdManualPay))?$AdManualPay['AdminManualPay']:"TRUE";
if($PayStatus != 1 && $idpref != ""){ //if student has not made payment
 //Box("style=background-color:;width:270px;height:auto;margin-top:3px"); 
         // Box("style=display:block;width:inherit");
         Line();
         TextBoxGroup();
         Switcher("id={$idpref}disanalysis,state=1,text=Auto Amount,style=width:100%;font-size:1.2em,info=System generated Amount,ontext=yes,offtext=no,align=right,onchange=Payment.PayNow.AutoAmount");
         _TextBoxGroup();
         // _Box();
       // _Box();

      Box("style=width:100%;height:auto;margin:5px 0px 10px 0px;display:none,id={$idpref}manualamt");
      TextBoxGroup();
        TextBox("title=Amount,style=width:250px,logo=money,id={$idpref}manualamttb,textchange=Payment.PayNow.ChangeAmount,info=Enter the Amount");
        _TextBoxGroup();

    _Box();
}
if(!is_array($paybrkdwn)){
  if($paybrkdwn == "#"){
      //check if wallet payment
      if($itemdet['studType'] == 'w'){
        Line();
        Box("style=width:100%;height:auto;margin:5px 0px 10px 0px;display:block,id=wmanualamt");
        TextBoxGroup();
          TextBox("title=Amount,style=width:250px,logo=money,id=wmanualamttb,textchange=Payment.ManualPay.ChangeAmountW,info=Enter the Amount");
          _TextBoxGroup();
  
      _Box();
      }else{
        MessageBack("Payment Structure Defination not Found");  
      }
      
    }else if($paybrkdwn == "##"){MessageBack("Student/Payer details not found");}else{
        MessageBack($paybrkdwn); 
    }
}//else{ //if analysis found
   $fBrkDwn = $paybrkdwn[2];
   $totAmt = $paybrkdwn[0];
   $famt = $paybrkdwn[1];
   $calcTot = 0;
   $fBrkDwnarr = explode("***",$fBrkDwn);
   if(count($fBrkDwnarr) > 0){
       $minheight = $paynow?"100":"150";
      // Line();
       Box("style=background-color:;width:95%;max-height:{$minheight}px;margin:auto;margin-top:10px;border-bottom:solid thin #CCC; overflow:auto;overflow-X:hidden,class=greyShadow,id={$idpref}autoamt"); 
       $analysis = __Table("rowselect=true,style=width:100%;font-size:0.8em,id=panalytbl");
          $analysis .= __THeader(array("Description","Amount"));
          foreach($fBrkDwnarr as $indbrkdn){
           if(trim($indbrkdn) != ""){ 
               $indbrkdnarr = explode("~",$indbrkdn);
               if(count($indbrkdnarr) > 2){
                   $descr = $indbrkdnarr[0];        
                   $indamt = (float)$indbrkdnarr[1];
                   $calcTot += $indamt;
                   $analysis .= __TRecord(array($descr,$indamt),"");   
               }
           }
       }
                  
          

          $analysis .= ___Table();
         
          if($famt != -1 && $calcTot != $Amt){ //if analysis is newly generated
             //check if generated amt is amt
             //MessageBack("Cannot Load Payment Analysis",false);
            $analysis = __Table("rowselect=true,style=width:100%;font-size:0.8em,id=panalytbl");
            $analysis .= __THeader(array("Description","Amount"));
            $analysis .= __TRecord(array($itemdet['ItemName'],$Amt),"");
            $analysis .= ___Table();
          }else{
              if($calcTot != $Amt){ //if calculated Amount is not equals to the Saved Amount
                //dont show the analysis
                //MessageBack("Invalid Payment Analysis<br />(Amount Miss-match)",false);
                $analysis = __Table("rowselect=true,style=width:100%;font-size:0.8em,id=panalytbl");
            $analysis .= __THeader(array("Description","Amount"));
            $analysis .= __TRecord(array($itemdet['ItemName'],$Amt),"");
            $analysis .= ___Table();
              }else{ //display the analysis
                
              }
           
          }
          if($itemdet['studType'] != 'w')echo $analysis;
        
        //set the state for switcher and get receipt
         if($PayStatus == 1){
            $state = "on";
           
        }else{ //if student has not make payment
            $state = "off";
        }

        if($idpref == ""){ //if loaded from manual pay
            //check if receipt exist
            
            $pth = "Files/Payment/Receipt/".str_replace("/","_",$RegNo)."_".$PayID."_".$Lvl."_".$Sem."-".$SemPart.".jpg";
            //MessageBack($configdir.$pth);
            if(file_exists($configdir.$pth)){
                Hidden("preceipt",$pth);
            }else{
                //get the RegNo and Jamb No to check 
                $det = GetBasicInfo($RegNo, "", "a", 0);
               // print_r($det);
               // Hidden("preceipt",$det);
                if(is_array($det)){
                    $RegNon = $det['RegNo'];
                    if(trim($RegNon) != "" && $RegNo == $RegNon){//initially used REgNo
                      $pth = "Files/Payment/Receipt/".str_replace("/","_",$det['JambNo'])."_".$PayID."_".$Lvl."_".$Sem."-".$SemPart.".jpg";
                      if(file_exists($configdir.$pth)){
                         Hidden("preceipt",$pth);
                      }
                    }
                }
            }

            //return receipt details if offline payment
            if($offlineRequest){
                if(is_array($payhist)){ //if order details found
                    Hidden("ReceiptNum",$payhist['ReceiptNum']);
                    Hidden("ReceiptBank",$payhist['ReceiptBank']);
                    Hidden("ReceiptBranch",$payhist['ReceiptBranch']);
                    Hidden("ReceiptDate",MysqlDateDecode($payhist['ReceiptDate']));
                }
            }
            }

        Hidden($idpref."delorder",$orderinfodel);
        Hidden($idpref."CurTransNum",$TransNum);
        Hidden($idpref."TopPaid",$topPaid);
        Hidden($idpref."MainPayStatus",$PayStatus);
        Hidden($idpref."isOffline",$offlineRequest?1:0);
        _Box();
        
        
        if($AdManualPay == "TRUE" && $idpref == ""){ //if manual payment is enabled
       // echo "<div style=\"width:100%; height:1px;margin:10px 0px\" class=\"altBgColor2\" > </div>"; 
       Line();
        //Box("style=background-color:;width:270px;height:auto;margin-top:3px");
        if($PayStatus == 1){
            $chn = $offlineRequest?"OFFLINE":"ONLINE";
            
            TextBoxGroup();
            TextBoxGroupItem();
             echo 'AMOUNT';
             TextBoxGroupItemMore();
             echo '<b>'.number_format($Amt,2,'.',',').'</b>';
            _TextBoxGroupItem();
            TextBoxGroupItem();
             echo 'STATUS';
             TextBoxGroupItemMore();
             echo '<b>APPROVED/PAID</b>';
            _TextBoxGroupItem();
            TextBoxGroupItem();
             echo 'CHANNEL';
             TextBoxGroupItemMore();
             echo '<b>'.$chn.'</b>';
            _TextBoxGroupItem();
            _TextBoxGroup();
        }else{
            $rstate = $offlineRequest?1:0;
          //Box("style=display:block;width:inherit");
          TextBoxGroup("font-size:0.9em;margin:auto;width:95%");
              Switcher("id=mpPayStatus,state=$rstate,text=REQUEST APPROVAL (<strong id\='paidamt' class\=\"altColor2 big\">".number_format($Amt,2,'.','\,')."</strong>),style=width:100%,info=Request Offline Payment Approval,ontext=yes,offtext=no,align=right,onchange=Payment.ManualPay.SetStatus");
              if($rstate == 1){ //if request sent but not paid/Approved
                Note();
                 echo "<strong>NOT YET APPROVED</strong>";
                _Note();
              }
              _TextBoxGroup();
        }
          
          //_Box();
       // _Box();
           
        }
        $dis = $state == "on"?"none":"block";
        if($state == "on" && $idpref != ""){
           Box("style=width:270px; margin:auto; text-align:center;margin-top:3px;font-size:1.2em,class=altColor2");
             echo 'Payment of <strong class="altColor">'.number_format($Amt,2,'.',',').'</strong> Already Made';
           _Box();
           Hidden($idpref."paymade","1");
        }
         
         if($state == "off"  && $idpref != ""){ //if student not paid
            Line();
         Box("style=width:265px; margin:auto; text-align:center;margin-top:3px;display:$dis,id=paidamtbtncont");
              //echo "<div style=\"width:100%; height:1px;margin:10px 0px\" class=\"altBgColor2\" > </div>";
      FlatButton("text=Pay <span id\='{$idpref}paidamtbtn'>".str_replace(",","\,",number_format($Amt,2))."</span> Now,logo=money,onclick=Payment.PayNow.Pay(),style=width:265px,title=Make Payment,id={$idpref}paynowbtn");
      _Box();
         }
      
        Hidden($idpref."sysamt",$Amt);
       
   }

//}
//echo $paybrkdwn;exit;
function FormBreakDown(){
     global $RegNo;global $Lvl; global $PayID; global $Sem; global $SemPart; global $ItemPayBrkDn; global $pre; global $_POST;global $dbo;global $inserted;global $Amt;
     $studDet = NULL;
     
     if($pre != "#"){
     $studDet = GetBasicInfo($RegNo, "sch", $pre);
     }
     if(!is_array($studDet)){
        
         //try get stud det from payee_tb
         $studDet = $dbo->SelectFirstRow("payee_tb","","PayeeID = '$RegNo' LIMIT 1");
         //return "aaa";
       if(is_array($studDet)){
           $otherdet = $studDet['OtherDet'];
           if(trim($otherdet) != ""){
               $otherdet = json_decode($otherdet,true);
               $studDet = array_merge($studDet,$otherdet);
           }
       }else{
           
            $OtherDet['FacID'] = isset($_POST['FacID'])?$_POST['FacID']:1;
            $OtherDet['DeptID'] = isset($_POST['DeptID'])?$_POST['DeptID']:1;
            $OtherDet['ProgID'] = isset($_POST['ProgID'])?$_POST['ProgID']:1;
            $OtherDet['StudyID'] = isset($_POST['StudyID'])?$_POST['StudyID']:9;
            $jsotherdet = json_encode($OtherDet);
            $insert = $dbo->Insert("payee_tb",array(
                "PayeeID"=>$RegNo,
                "Name"=>$_POST['PayeeName'],
                "OtherDet"=>$jsotherdet
            ));
           // return $insert;
            $OtherDet['RegNo']= $RegNo;
            $studDet = $OtherDet;
            $inserted = true;
            //echo $insert;
       }
     }
     $brkdwn = "#";
     if(is_array($studDet)){
        if(trim($ItemPayBrkDn) != ""){
            
          $brkdwn = PaymentBreakDown($ItemPayBrkDn,$Lvl,$Sem,$studDet,$SemPart);
        }else{
            //no payment breakdown structure found
            //MessageBack("Payment Structure Defination Not Found");
            return "#";
        }
     }else{
         //student information not found
         //MessageBack("student details not found");
         return "##";
     }
     
    return $brkdwn;
}





?>