<?php

require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");

require("../../../../general/getinfo.php");
//AllowUser("manualp");

//require("../../../../epconfig/GenScript/PHP/getinfo.php");
//mpsssearchCriterial=regsc&mpsssearchtxt=&paytypetb=1&mpleveltb=1
//&mppaypolicytb=3&panalyLoading=&imgpd_image_file=%3F&loadimg=&camimg=&clearimg=&mpPayStatus=1&receiptnumtb=768788999&receiptbanktb=firstbank&receiptbankbrtb=uyo&receiptdatetb=17/9/2019
//exit(json_encode($_POST));
//exit(json_encode($_POST));
if(isset($_POST['paytypetb']) && isset($_POST['mpleveltb'])  && isset($_POST['mppaypolicytb']) && isset($_POST['mpPayStatus'])  && isset($_POST['RegNo']) && isset($_POST['receiptnumtb'])){
  $UID = $_POST['UID'];
    $RegNo = $_POST['RegNo'];$PayID = $_POST['paytypetb']; $Lvl = $_POST['mpleveltb'];$PayPol = $_POST['mppaypolicytb'];$PayStatus = $_POST['mpPayStatus'];
    $PayStatus = (int)$PayStatus;
  $studType = $_POST['studType'];

  $ReceiptNum = $_POST['receiptnumtb'];
  $ReceiptBank = $_POST['receiptbanktb'];
  $ReceiptBranch = $_POST['receiptbankbrtb'];
  $ReceiptDate = MysqlDateEncode($_POST['receiptdatetb']);
  $ReceiptDate = is_null($ReceiptDate)?'0000-00-00':$ReceiptDate;

  
    /* if($PayStatus == 1 && !isset($_FILES["imgpd_image_file"])){ //abort if status to be update to true and no reciept
                //echo "#Operation Aborted: New Payment Receipt Not Found";
                exit("#Operation Aborted: New Payment Receipt Not Found");       
    } */
    if($PayStatus == 1 && (!isset($_POST['receiptnumtb']) || trim($_POST['receiptnumtb']) == "")){ //abort if status to be update to true and no reciept
      //echo "#Operation Aborted: New Payment Receipt Not Found";
      exit("#Operation Aborted: Payment Receipt Number not Found");       
}
$PayPolstr = $PayPol;
if(count(explode("-",$PayPolstr)) == 1)$PayPolstr .= "-3";

    $fn = str_replace("/","_",$RegNo)."_".$PayID."_".$Lvl."_".$PayPolstr.".jpg";
    $receiptupl = false;
    if((int)$PayStatus == 1 && isset($_FILES["imgpd_image_file"])){
         $fileTmpLoc = $_FILES["imgpd_image_file"]["tmp_name"]; // File in the PHP tmp folder
         if ($fileTmpLoc) { // if file not chosen
             
            //$fn = "UserImages/Student/{$regfile}.jpg";
            if(move_uploaded_file($fileTmpLoc, $configdir."Files/Payment/Receipt/".$fn)){
                $receiptupl = true;
                
               // $data["Passport"] = $fn."?".mt_rand();
            } else {
               // echo "#Operation Aborted: Cannot Upload Payment Receipt";
                exit("#Operation Aborted: Cannot Upload Payment Receipt");
            }
         }else{
           // echo "#Operation Aborted:Payment Receipt not Found";
                exit("#Operation Aborted:Payment Receipt not Found"); 
         }

    }
    $PayPolArr = explode("-",$PayPol);
    $Sem = (int)$PayPolArr[0];
    $SemPart = isset($PayPolArr[1])?(int)$PayPolArr[1]:3;
    $rst = $dbo->RunQuery("SELECT * FROM order_tb WHERE RegNo='".$dbo->SqlSafe($RegNo)."' AND Sem=$Sem AND SemPart=$SemPart AND Lvl=$Lvl AND ItemID=$PayID");
    
    if(is_array($rst)){
      $studDet = GetBasicInfo($RegNo, "sch2", $studType, 0);
        if($rst[1] > 0){ //if order exist
        
          $orderdet = $rst[0]->fetch_array();
          if((int)$orderdet['Paid'] == 1){ //if student currently paid
            $rtninfo = $orderdet['Channel'] == "OFFLINE"?"Offline Payment Request Already Approved":"Payment Already Made";
                exit("*".$rtninfo);
              //paid 
              /* if($PayStatus == 1){//if status to be set to paid
                
                //if receipt uploaded, just echo back Receipt Uploaded
                if($receiptupl){
                   exit("*Receipt Set");
                }
                exit("*No Changes Found");
              }else{ //if status to be set to not paid
                //Delete Payment Details from payhistory_tb and order_tb
                $query = "DELETE FROM payhistory_tb WHERE RegNo='$RegNo' AND Sem=$Sem AND SemPart=$SemPart AND Lvl=$Lvl AND PayID=$PayID LIMIT 1 ;  DELETE FROM order_tb WHERE  RegNo='$RegNo' AND Sem=$Sem AND SemPart=$SemPart AND Lvl=$Lvl AND ItemID=$PayID LIMIT 1;";
                //$dbo->Begin();
                $delrst = $dbo->Connection->multi_query($query);
                if(!$delrst){
                   // echo "#Error Deleting Payment Record";
                   // $dbo->Rollback();
                    exit("#Error Deleting Payment Record");
                }
                //$dbo->Commit();
                //Delete the receipt if exist **********************
                 if(file_exists("../../../Files/Payment/Receipt/".$fn)){
                     unlink("../../../Files/Payment/Receipt/".$fn);
                 }
                //****************************************
                //echo "*All Payment Details Deleted Successfuly";
                exit("#");//*All Payment Details Deleted Successfuly
              } */
            
          }else{ //student not paid but has placed order
              //perform update based on the status to set to 
              if($PayStatus == 1){//if status to be set to paid
                 //Add in Payhistory_tb and update order_tb
                 //Add into Payhistory
                 /*ID,RegNo,Lvl,Sem,SemPart,Ses,Amt,TransID,PayID,PayBrkDn,Bank,BnkBranch,itemNum,PayDate,validationNo,aksl*/
                // $CursesRec = CurrentSes();
                 //$SesID = is_array($CursesRec)?$CursesRec[0]:1;
                 if($orderdet['Channel'] == "OFFLINE"){
                  exit("Offline Payment Approval Request Already Sent");
                 }

                 

                 //Update the order channel to offline and upload
                 $upd = $dbo->Update("order_tb",["Channel"=>"OFFLINE","UserID"=>$UID,"ReceiptNum"=>$ReceiptNum,"ReceiptBank"=>$ReceiptBank,"ReceiptBranch"=>$ReceiptBranch,"ReceiptDate"=>$ReceiptDate],"ID=".$orderdet['ID']);
                // $rtninfo = $orderdet['Channel'] == "OFFLINE"?"Offline Payment Request Already Approved":"Payment Already Made";
                exit("*Offline Payment Approval Request Sent");
                 /* $OAmt = $orderdet['Amt'];
                 if(isset($_POST['Amt'])){ //if dynamic amount
                   $OAmt = $_POST['Amt'];
                 }
                 //Bank = 'Manual Pay',
                 // BnkBranch = 'Manual Pay',
                 $fieldval = array("RegNo"=>$RegNo,"Lvl"=>$Lvl,"Sem"=>$Sem,"SemPart"=>$SemPart,"Ses"=>$orderdet['Ses'],"Amt"=>$OAmt,"TransID"=>$orderdet['TransNum'],"PayID"=>$PayID,"Bank"=>"Manual Pay","BnkBranch"=>"Manual Pay","PayBrkDn"=>$orderdet['BrkDwn'],"itemNum"=>$orderdet['ItemNo'],"PayDate"=>date("Y-m-d"),"Info"=>StudPatchDet($RegNo,$PayID),"TransAmt"=>$OAmt,"CollectBank"=>GetCollectBank($PayID));
                 $inst = $dbo->Insert("payhistory_tb",$fieldval);
                 if($inst == "#"){
                     //update order_tb
                     $uarr = array("Paid"=>1);
                     if((float)$_POST['Amt'] != (float)$orderdet['Amt']){ //if amount not desame
                     $uarr["Amt"]=$OAmt;
                   }
                     $upd = $dbo->Update("order_tb",$uarr,"ID=".$orderdet['ID']);
                     exit("*Payment Status Updated Successfuly");
                 }else{
                     //if receipt uploaded, delete it
                    if($receiptupl){ 
                      unlink("../../../Files/Payment/Receipt/".$fn);
                    }
                     exit("#Internal Error: Payment Update Failed: ".$inst);
                 } */
              }else{//if status is to be set to not paid
                //delete the order information
                $del = $dbo->RunQuery("DELETE FROM order_tb WHERE ID = ".$orderdet['ID']);
                if(is_array($del)){
                  $rtndisinfo = $orderdet['Channel'] == "OFFLINE"?"Offline Payment Request Deleted":"*Payment Analysis/Order placed by Student Deleted";
                  //if($receiptupl){ 
                    unlink($configdir."Files/Payment/Receipt/".$fn);
                  //}
                    exit("#");
                }
              }
              //echo "Not Yet Paid, But Placed Order";
          }
        }else{ //if no order exist
          $paymentit = GetPaymentItem($PayID);
          if(!is_array($paymentit)){
              exit("#Internal Error: Payment Structure Details");
          }
         
          
          
          $SafeRegNo = $dbo->SqlSafe($RegNo);
          if(!is_array($studDet)){ //if no student data found
            //check if is a candidate, in case there is no academic details
            $studDet = $dbo->SelectFirstRow("pstudentinfo_tb","","RegNo='$SafeRegNo' OR JambNo='$SafeRegNo' Limit 1",MYSQLI_ASSOC);
            if(!is_array($studDet)){
              exit("#Student Details Not Found");
            }
            $studDet['ProgID'] = 0;
             //exit($studDet);
          }
         //exit(json_encode($studDet));
          $ItemPayBrkDn = $paymentit['PayBrkDn'];
          $brkdwn = PaymentBreakDown($ItemPayBrkDn,$Lvl,$Sem,$studDet,$SemPart);
         if(!is_array($brkdwn)){
             exit("#Internal Error: Cannot Form Payment Details");
         }
          
         //$Amt = $brkdwn[0];
          $OAmt = $brkdwn[0];
                 if(isset($_POST['Amt'])){ //if dynamic amount
                   $OAmt = $_POST['Amt'];
                 }
                // exit(json_encode(StudPatchDet($RegNo,$PayID)));
         $rBrkdwn = $dbo->SqlSafe($brkdwn[2]);
        
           if($PayStatus == 1){//if status to be set to paid
                //if receipt not uploaded
                /* if(!$receiptupl){
                   exit("#No Payment Receipt Found");
                } */

                if(trim($ReceiptNum) == ""){
                  exit("#No Payment Receipt Number Found");
                }
                 
                if(!isset($_POST['paysestb']) && (int)$_POST['paysestb'] < 1){
                  $currSes = CurrentSes();
                  $currSesID = $currSes['SesID'];
                }else{
                  $currSesID = (int)$_POST['paysestb'];
                }
                
                
                //Insert in order and payhistory table
                //"ID","ItemNo","TransNum","ItemName","ItemDescr","Amt","Currency","RegNo","SemPart","Sem","Lvl","ItemID","Paid","RegDate","Ses","BrkDwn"
                $heiestsem = HighestSemester();
                $HeihestSemNum = $heiestsem["Num"];
                $PaySem = (int)$Sem > (int)$HeihestSemNum?$HeihestSemNum:$Sem;
                $transnumbers = generateTransInfoOnly();
               // exit("Curr Ses: ".$currSesID );
                $qur = "INSERT INTO order_tb SET 
                ItemNo = '".$transnumbers[0]."',
                 TransNum = '".$transnumbers[1]."',
                  ItemName = '".$paymentit['ItemName']."',
                  ItemDescr = '".$paymentit['ItemDescr']."',
                  Amt = $OAmt, 
                  RegNo = '$SafeRegNo', 
                  SemPart = $SemPart, 
                  Sem = $Sem,
                  Lvl = $Lvl, 
                  ItemID = $PayID, 
                  Paid = 0,
                  RegDate = '".date("Y-m-d"). "',
                  Ses = $currSesID,
                  BrkDwn = '$rBrkdwn',
                  Channel = 'OFFLINE',
                  UserID = $UID ,
                  ReceiptNum = '".$dbo->SqlSafe($ReceiptNum)."',
                  ReceiptBank = '".$dbo->SqlSafe($ReceiptBank)."',
                  ReceiptBranch = '".$dbo->SqlSafe($ReceiptBranch)."',
                  ReceiptDate = '".$dbo->SqlSafe($ReceiptDate)."',
                  Info = '".$dbo->SqlSafe(StudPatchDet($RegNo,$PayID,$Lvl))."',
                  SchSem = $PaySem ,
                  ProgID = ".$studDet['ProgID'].",
                  RequestDate = '".date("Y-m-d")."';  
                  ";
                  /* 
                  INSERT INTO payhistory_tb SET 
                   RegNo = '$RegNo', 
                  SemPart = $SemPart, 
                  Sem = $Sem,
                  Lvl = $Lvl,
                  Amt = $OAmt,
                  Ses = $currSesID,
                  TransID = '".$transnumbers[1]."',
                  PayID = $PayID,
                  PayBrkDn = '$rBrkdwn',
                  Bank = 'Manual Pay',
                  BnkBranch = 'Manual Pay',
                  itemNum = '".$transnumbers[0]."',
                  PayDate = '".date("Y-m-d"). "',
                  Info = '".StudPatchDet($RegNo,$PayID)."',
                  TransAmt = $OAmt,
                  CollectBank = '".GetCollectBank($PayID)."' ; */
                  //exit(urlencode($qur));
                  /*ID,RegNo,Lvl,Sem,SemPart,Ses,Amt,TransID,PayID,PayBrkDn,Bank,BnkBranch,itemNum,PayDate,validationNo,aksl*/
                  $instrst = $dbo->Connection->multi_query($qur);
                if(!$instrst){
                    exit("#Internal Error: Offline Payment Request Failed : ".$dbo->Connection->error);
                }
                exit("##".$transnumbers[1]);//*Manual Payment Updated Successfuly
           }else{ //if payment status is to be set to off
           if($receiptupl){
                      unlink($configdir."Files/Payment/Receipt/".$fn);
                    }
              exit("No Update Found");
           }
            //echo "#Not Paid";
        }
    }else{
        echo "#Server Error";
         if($receiptupl){
                      unlink($configdir."Files/Payment/Receipt/".$fn);
                    }
    }
  
}else{
    echo "#Invalid Payment Parameters";
}


?>